http://stackoverflow.com/q/48086626
answer count: 4
has comment: http://stackoverflow.com/comment/83150017
downvote count: 13
tagged with: list
has answer: http://stackoverflow.com/a/48086851
has answer: http://stackoverflow.com/a/48086638
type: Question
has title: Python 3: How to create a list to print its every element on a new line - without loops or sep = "\n"
has body: Let's say I have a list 'mylist'. For example, I prepared it like this: mylist = ['AB', 'CD', 'EF'] I need to print out each element of 'mylist' on a new line. However, I am not allowed to use loops (as in 'for i in mylist...') and I can't say: print(*mylist, sep = "\n") Although the last command gives exactly the output I need. No, I have to somehow create/prepare 'mylist' in such a way that the desired print output is achieved based on the following command: print(mylist) Is it even possible? Notice, it's not a duplicate post - it's more about how to format the list to begin with, not about printing per se.
upvote count: 0
has answer: http://stackoverflow.com/a/48086710
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48086689
score: -13
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48126255
answers question: http://stackoverflow.com/q/48126043
score: 0
accepted answer of: http://stackoverflow.com/q/48126043
type: Answer
has body: A few changes in your code: with open("numbers.txt", "r") as f: a = [int(n) for line in f.readlines() for n in line.split()] for i in a: print(i) print("Sum: ", sum(a)) Output: 69 71 78 82 84 95 96 Sum: 747
type: AcceptedAnswer

http://stackoverflow.com/a/48031342
score: 0
type: AcceptedAnswer
has body: I saw two problems. Let's take a look at your list which you printed out: [[(13506636000.0,)], [(20156784500.0,)], ... ] What it told me is you have a list of nested lists (e.g. [(13506636000.0,)]). This represents the a single row and a single column, because you return c.fetchall(). In this case, you know for sure that at most 1 row of data is returned, so we can use c.fetchone() to reduce the number of nested lists. Next, take a look at this line: data = query_symbol(symbolId) Since c.fetchone() returns (13506636000.0,), which is a tuple of 1 element, you can use the following trick to extract the number: (data,) = query_symbol(symbolId) Putting it together: def query_symbol(symbolId): uniqueId = '{}@{}'.format(symbolId, datetime.date.today()) with sqlite3.connect('sql/database.db') as conn: c = conn.execute( "SELECT number FROM symbols WHERE uniqueId=?", (uniqueId,)) return c.fetchone() def calc(filename): symbolIds = def_sec.load_symbolIds(filename) print(len(symbolIds)) numbers = [] for symbolId in symbolIds: (data, ) = query_symbol(symbolId) # instead of `data =` numbers.append(data) print(numbers) total = sum(numbers) print(total) calc('index_symbolids') At this point, you should get the desired result. Update This update explains how (data,) = works. Let say, if you have a tuple of 3 elements and want to assign to variables a, b, c: (a, b, c) = (1, 2, 3) # a=1, b=2, c=3 In practice, we can drop the parentheses from the left side of the equal sign: a, b, c = (1, 2, 3) # a=1, b=2, c=3 For a 1-element tuple, the notation is (1,), not (1) (which is simply 1): data = (1,) # data = (1,), which is the whole tuple (data,) = (1,) # data = 1, which is what we want data, = (1,) # data = 1, but the syntax looks kind of wrong Back to your problem, the function query_symbol() returns a 1-element tuple, thus we have to use: (data,) = query_symbol(symbolId) data, = query_symbol(symbolId) I personally like the first syntax because the second looks like the comma was there b…
type: Answer
answers question: http://stackoverflow.com/q/48030970
accepted answer of: http://stackoverflow.com/q/48030970
has comment: http://stackoverflow.com/comment/83058319

http://stackoverflow.com/q/48173166
has comment: http://stackoverflow.com/comment/83326070
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83326050
has body: I have written code that creates a text file (if it doesn't exist) and asks you to input a name and an age to record peoples names and ages. I would like to add an elif into my code so that I can update peoples ages. For example if a text file held the name Paul and their age was 46 and I typed in Paul when asked to input a name, I'd like it to just ask for an updated age. Here is my attempt that simply doesn't work. Code: while True: family=open("FamilyAges.txt",'a+') familyR=open("FamilyAges.txt",'r') line1= familyR.readlines(1) name = input('Enter name of person : ') if name == 'end': break elif name == line1: print('test') else: age = input('Enter age of person : ') family.write((name)+' '+(age)+'\n') family.close() Text File: Paul 46 Sarah 46
has comment: http://stackoverflow.com/comment/83326010
answer count: 4
has answer: http://stackoverflow.com/a/48173601
has comment: http://stackoverflow.com/comment/83326095
has answer: http://stackoverflow.com/a/48173333
type: Question
has answer: http://stackoverflow.com/a/48173557
has answer: http://stackoverflow.com/a/48174004
has comment: http://stackoverflow.com/comment/83325983
has title: How to check if the input has already been entered into a txt file
score: 0
has comment: http://stackoverflow.com/comment/83326467
has comment: http://stackoverflow.com/comment/83325956
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83326072

http://stackoverflow.com/a/48074146
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48073161
upvote count: 1
has body: use a nested loop: for m,x in A.items(): for y,z in x.items(): print(m,'{0}='.format(y), z[0],'({0})'.format(z[1]))
downvote count: 0

http://stackoverflow.com/q/48072091
tagged with: numpy
score: 3
upvote count: 3
tagged with: buildozer
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48080592
type: UnansweredQuestion
tagged with: android
has title: Buildozer Numpy RuntimeError: Broken toolchain: cannot link a simple C program
has body: Writing my first Android app in Python and using Buildozer to package it. Because I will need to use numpy later on in the project, I tried packaging the following test code: import numpy import kivy kivy.require('1.0.6') from kivy.app import App from kivy.uix.button import Button class TestApp(App): def build(self): return Button(text='Hello World') TestApp().run() However, I got the following error: Traceback (most recent call last): File "setup.py", line 251, in &lt;module&gt; setup_package() File "setup.py", line 243, in setup_package setup(**metadata) File "/home/kivy/Desktop/cam/.buildozer/android/platform/build/build/other_builds/numpy/armeabi-v7a/numpy/numpy/distutils/core.py", line 169, in setup return old_setup(**new_attr) File "/home/kivy/Desktop/cam/.buildozer/android/platform/build/build/python-installs/myapp/lib/python2.7/distutils/core.py", line 152, in setup dist.run_commands() File "/home/kivy/Desktop/cam/.buildozer/android/platform/build/build/python-installs/myapp/lib/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/home/kivy/Desktop/cam/.buildozer/android/platform/build/build/python-installs/myapp/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/home/kivy/Desktop/cam/.buildozer/android/platform/build/build/other_builds/numpy/armeabi-v7a/numpy/numpy/distutils/command/build_ext.py", line 59, in run self.run_command('build_src') File "/home/kivy/Desktop/cam/.buildozer/android/platform/build/build/python-installs/myapp/lib/python2.7/distutils/cmd.py", line 326, in run_command self.distribution.run_command(command) File "/home/kivy/Desktop/cam/.buildozer/android/platform/build/build/python-installs/myapp/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "/home/kivy/Desktop/cam/.buildozer/android/platform/build/build/other_builds/numpy/armeabi-v7a/numpy/numpy/distutils/command/build_src.py", line 153, in run self.build_sources() File "/home/kivy/Desktop/cam/.…
tagged with: python
tagged with: kivy
downvote count: 0
type: Question

http://stackoverflow.com/comment/83148494
has text: @Icy another story would be if you now want to have a model per each store (case where your dataset per model will be exclusively from that store), or if you want to have a single model that includes store as a variable to consider (case where you will have to encode the store ID to your input as one-hot vectors, so you can compare predicted sales on a product across different stores). If you don't want to consider store as variable then my last comment would be the way to go. :) cheers
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48065620

http://stackoverflow.com/a/48142085
accepted answer of: http://stackoverflow.com/q/48142060
answers question: http://stackoverflow.com/q/48142060
type: Answer
upvote count: 3
has body: Use Python os module's geteuid(). According to its documentation: Return the current process’s effective user id. Considering that the root user's UID is always 0, you just need to check if os.geteuid() returns 0: if os.geteuid() == 0: # UID is 0, your program is being run by the root user
score: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48071002
tagged with: request
answer count: 1
downvote count: 1
tagged with: hue
type: UnansweredQuestion
has title: hue execute query via python
type: Question
has comment: http://stackoverflow.com/comment/83117671
has comment: http://stackoverflow.com/comment/83116138
favorite count: 0
has answer: http://stackoverflow.com/a/60638343
has body: I know how to use chrome hue query. I want to use Python query. I have the hue account and password. Question: How to use python query? def login_djangosite(): import requests session = requests.Session() next_url = "/" login_url = "http://hue.bi.com/accounts/login/?next=/" r = session.get(login_url) form_data = dict(username=u'',password=u'', csrfmiddlewaretoken=session.cookies['csrftoken'],next=next_url) r = session.post(login_url, data=form_data, cookies=dict(), headers=dict(Referer=login_url)) # check if request executed successfully? print(r.status_code) cookies = session.cookies headers = session.headers response=session.get('http://hue.bi.hujiang.com/beeswax/#query', cookies=session.cookies, headers=session.headers) response.status_code response.text
score: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/q/48090681
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83155709
has comment: http://stackoverflow.com/comment/83157859
has answer: http://stackoverflow.com/a/48090719
type: Question
tagged with: numpy
downvote count: 0
score: 4
has body: I am trying to build a list of matrices using numpy, but when I try to append a matrix to an empty tensor, I get the error: ValueError: all the input arrays must have same number of dimensions Concatenate and append both seem to fail. I tried calling: tensor = np.concatenate((tensor, matrix), axis=0) and tensor = np.append(tensor, matrix, axis=0) but I get the same error either way. The tensor starts with a size of [0, h, w], and the matrix is of size [h, w]. The matrix is the correct shape in the direction I want to append to, but it won't seem to attach.
upvote count: 4
has comment: http://stackoverflow.com/comment/83183631
accepted answer: http://stackoverflow.com/a/48090719
tagged with: matrix
has title: Numpy Append Matrix to Tensor
answer count: 1
has comment: http://stackoverflow.com/comment/83155825
favorite count: 0
tagged with: tensor
tagged with: python
tagged with: append

http://stackoverflow.com/a/48063371
accepted answer of: http://stackoverflow.com/q/48053628
answers question: http://stackoverflow.com/q/48053628
has comment: http://stackoverflow.com/comment/83114794
type: AcceptedAnswer
downvote count: 0
score: 1
has body: I don't believe you have an index on column 'a', which means that each partition access is probably using a lot of memory within sqlite while scanning the table. In any case, pandas' access to DBs via sqlalchemy is not particularly memory-efficient, so I am not hugely surprised that you have a memory spike during access. You can, however, increase the number of partitions to be able to access the data. For example: df = ddf.read_sql_table('testTbl', connString, index_col = 'a', npartitions=20) or perhaps reduce the number of threads/processes available, so that there is more memory for each thread. Note that chest is not helping you at all here, it can only save completed results, and the memory spike is happening during the loading of the data (furthermore, the distributed workers should spill to disc without explicitly giving a cache).
type: Answer
has comment: http://stackoverflow.com/comment/83108446
upvote count: 1

http://stackoverflow.com/a/48105134
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48059908
answers question: http://stackoverflow.com/q/48059908
type: Answer
has comment: http://stackoverflow.com/comment/83229747
score: 1
upvote count: 1
has body: What about: def process_response(response): forms = { 'foo': FooForm, 'bar': BarForm, } if response.get('response_type') == 'parent': for subresponse in response.get('subresponses'): result = self.process_response(subresponse) if result.status_code != 200: return result else: form = forms[response.get('response_type')](response) if not form.is_valid(): return JsonResponse({"message": str(form.errors)}, status=400) form.save() return HttpResponse(status=200) The difference being that instead of simply calling process_response, we call it, and see if there was a problem.
has comment: http://stackoverflow.com/comment/83228268

http://stackoverflow.com/q/48118743
has title: Django Rest Framework, display data from a table referenced with a foreign key
tagged with: python
has answer: http://stackoverflow.com/a/48118942
type: AnsweredQuestion
tagged with: django
has body: I got stuck a bit with a small problem when doing my school project, the problem is that I have an api with DRF and wanting to show my patient data "main table" shows them without problems but when I want to show other patient data in a different table (this table is this reference with a foreign key to Patient) I have not managed to obtain the patient data from this other table. I can not make my api send me the other patient data from the foreign key referenced to the patient, could you help me? models.py class Paciente(TimeStampedModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) udi = models.UUIDField(default=uuid.uuid4, editable=False) first_name = models.CharField('Nombre(s)', max_length=100) last_name = models.CharField('Apellidos', max_length=100) gender = models.CharField('Sexo', max_length=20, choices=GENDER_CHOICES) birth_day = models.DateField('Fecha de nacimiento', blank=True, null=True) phone_number = models.CharField('Número de telefono', max_length=13) civil_status = models.CharField('Estado civil', max_length=20, choices=CIVIL_STATUS_CHOICES) etc..... class Antecedentes(TimeStampedModel): """ Modelo de motivo y antecedentes de la enfermedad presentada en el momento de la consulta """ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE, null=True) motivo = models.TextField('Motivo de la consulta') antecedentes = models.TextField('Antecedentes de la enfermedad actual', blank=True, null=True) serializers.py class antecedenteSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source="user.username") class Meta: model = Antecedentes fields = ('paciente' ,'motivo', 'antecedentes', ) views.py I was trying this but I'm not if this is correct or not from historiaClinica import models as modelsHC class antecedenteList(APIView): """ Lista todos los antecedentes o crea uno nuevo """ def get_object(self, pk): try: pacie…
type: Question
accepted answer: http://stackoverflow.com/a/48118942
score: 0
answer count: 1
tagged with: django-rest-framework

http://stackoverflow.com/q/48132333
has comment: http://stackoverflow.com/comment/83242028
score: 0
has comment: http://stackoverflow.com/comment/83242693
has title: Nested dictionaries - obtaining values (Python)
answer count: 1
tagged with: nested
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has body: I have a JSON file, converted from XML which was originally equation: x^2 + 4*x + 4 = 0: { "mrow": { "mrow": { "msup": { "mi": "x", "mn": "2" }, "mo": [ "+", "+" ], "mrow": { "mn": "4", "mo": "*", "mi": "x" }, "mn": "4" }, "mo": "=", "mn": "0" } } When I open this file with Python I get nested dictionaries, like this: {'mrow': {'mrow': {'msup': {'mi': 'x', 'mn': '2'}, 'mo': ['+', '+'], 'mrow': {'mn': '4', 'mo': '*', 'mi': 'x'}, 'mn': '4'}, 'mo': '=', 'mn': '0'}} Is there a simple way to obtain only the values representing the initial equation, so that I get the initial equation again?
has answer: http://stackoverflow.com/a/48132645
has comment: http://stackoverflow.com/comment/83241763
has comment: http://stackoverflow.com/comment/83242042
tagged with: http://stackoverflow.com/tag/json
type: Question

http://stackoverflow.com/a/48032815
score: 2
has body: There are a few things that you should neaten up to make your code work properly and just generally better: Rename data to n, this isn't going to make much of a difference, but I would say it just makes more sense. There is no need to do endless conversions to int, n only needs to be converted from a string to an integer once. Don't put your entire code in a function then call it once, instead have the main algorithm in a smaller function which you then can call from the main body of your code or even create another function to call the algorithm which handles the inputting side of things. Use the integer division operator (//) instead of the floating point divider (/), since the number will be even, you can be sure that the decimal place will be 0. You don't need to check if n % 2 is 0 and then on the next line check if it n % 2 is 1, you can just use an if ... else clause. And that's about it! Here's what it looks like: #even / 2 #odd * 3 + 1 def collatz(n): while n != 1: if n % 2 == 0: #Number is even n = n // 2 else: n = n * 3 + 1 print(n) number = input("Enter number:") try: number = int(number) collatz(number) except ValueError: print("Please input a valid value") And a test shows it works (input of 24): 12 6 3 10 5 16 8 4 2 1
has comment: http://stackoverflow.com/comment/83036837
answers question: http://stackoverflow.com/q/48032792
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48032792
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/83035955

http://stackoverflow.com/a/48015762
upvote count: 1
answers question: http://stackoverflow.com/q/48015635
downvote count: 0
type: Answer
has body: run which pip, which python, make sure they are same suite when run pip install, it should feedback the package is installed in which path run this code in python import sys for i in sys.path: print i to check if your syspath including that path or not.
score: 1

http://stackoverflow.com/comment/83139368
score: 0
comment on: http://stackoverflow.com/q/48082439
type: Comment
type: QuestionComment
has text: If you only have a single byte, it doesn't matter if you have dozens of bytes of overhead, because you're only paying that overhead once. You have billions of bytes of memory.

http://stackoverflow.com/comment/83393866
comment on: http://stackoverflow.com/a/48043743
type: Comment
has text: Thank you, I shall have a look into it!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/116212081
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48138599
type: Comment
has text: Frankly I think the output should have been [(3, 4), (6, 5), (6,1)] in your example instead of its transpose in the documentation, in order to consistent with the output of np.unravel_index(1621, (6,7,8,9)) being (3, 1, 4, 1)

http://stackoverflow.com/q/48043595
has answer: http://stackoverflow.com/a/48043905
has body: List a and b are the keys and the values. The values in variable b are assigned as topicnumbers and data is sent every 10 seconds to a topic. Is this is a stable way to distribute information? Does one see any difficulties for in the near future when the keys and thus topics are scaled up to 100+? import zmq import random import time from multiprocessing import Process a = ['one', 'two', 'three', 'four', 'five'] b = [10, 20, 30, 40, 50] d = dict(zip(a, b)) def pub001(): port = "5100" context = zmq.Context() socket = context.socket(zmq.PUB) socket.bind("tcp://*:%s" % port) while True: for i, x in d.items(): topic = x number = random.randrange(1, 215) print(topic, number) socket.send_string("%d %d" % (topic, number)) print("Data published", topic) time.sleep(10) if __name__ == "__main__": a =Process(target=pub001, args=()) a.start()
downvote count: 0
score: 1
favorite count: 0
tagged with: pyzmq
type: Question
tagged with: python
upvote count: 1
has title: ZeroMQ multiple topics in publisher
answer count: 1
tagged with: zeromq
type: UnansweredQuestion

http://stackoverflow.com/q/48060775
has title: How to get full spelling of month is using calender module in python pandas?
tagged with: calendar
downvote count: 1
type: Question
has body: I have following table NMonth 01 02 03 if i using following code(calender module) SMonth=df['NMonth'].apply(lambda x: calendar.month_abbr[x]) My result will be : NMonth SMonth 01 Jan 02 Feb 03 Mar How to get the full spelling of the month if using calender module? below is my desire result NMonth SMonth 01 January 02 February 03 March
has answer: http://stackoverflow.com/a/48060862
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48060815
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83094029
has comment: http://stackoverflow.com/comment/83094031
tagged with: datetime
tagged with: python
possible better answer: http://stackoverflow.com/a/48060862
has answer: http://stackoverflow.com/a/48060815
type: AnsweredQuestion
score: 2
upvote count: 3

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/48016376
tags question: http://stackoverflow.com/q/48072001
tags question: http://stackoverflow.com/q/48143089
tags question: http://stackoverflow.com/q/48153359
tags question: http://stackoverflow.com/q/48104109
tags question: http://stackoverflow.com/q/48040008
tags question: http://stackoverflow.com/q/48078932
tags question: http://stackoverflow.com/q/48094940
tags question: http://stackoverflow.com/q/48152379
tags question: http://stackoverflow.com/q/48020008
tags question: http://stackoverflow.com/q/48157899
tags question: http://stackoverflow.com/q/48119810
tags question: http://stackoverflow.com/q/48086513
tags question: http://stackoverflow.com/q/48070027
tags question: http://stackoverflow.com/q/48142723
tags question: http://stackoverflow.com/q/48127714
tags question: http://stackoverflow.com/q/48129467
tags question: http://stackoverflow.com/q/48124483
tags question: http://stackoverflow.com/q/48159489
tags question: http://stackoverflow.com/q/48165672
tags question: http://stackoverflow.com/q/48095529
tags question: http://stackoverflow.com/q/48089257
type: Tag
tags question: http://stackoverflow.com/q/48115281
tags question: http://stackoverflow.com/q/48142485
tags question: http://stackoverflow.com/q/48076783
tags question: http://stackoverflow.com/q/48160172
tags question: http://stackoverflow.com/q/48159958
tags question: http://stackoverflow.com/q/48049123
tags question: http://stackoverflow.com/q/48103203
tags question: http://stackoverflow.com/q/48155275
tags question: http://stackoverflow.com/q/48017778
tags question: http://stackoverflow.com/q/48157613

pandas
tags question: http://stackoverflow.com/q/48067726
tags question: http://stackoverflow.com/q/48120471
tags question: http://stackoverflow.com/q/48050906
tags question: http://stackoverflow.com/q/48037945
tags question: http://stackoverflow.com/q/48150111
tags question: http://stackoverflow.com/q/48157422
tags question: http://stackoverflow.com/q/48052125
tags question: http://stackoverflow.com/q/48111231
tags question: http://stackoverflow.com/q/48171887
tags question: http://stackoverflow.com/q/48168918
tags question: http://stackoverflow.com/q/48151423
tags question: http://stackoverflow.com/q/48084356
tags question: http://stackoverflow.com/q/48022199
tags question: http://stackoverflow.com/q/48155564
tags question: http://stackoverflow.com/q/48108025
tags question: http://stackoverflow.com/q/48168292
tags question: http://stackoverflow.com/q/48147971
tags question: http://stackoverflow.com/q/48166840
tags question: http://stackoverflow.com/q/48039864
tags question: http://stackoverflow.com/q/48023061
tags question: http://stackoverflow.com/q/48142757
tags question: http://stackoverflow.com/q/48120216
tags question: http://stackoverflow.com/q/48095457
tags question: http://stackoverflow.com/q/48109266
tags question: http://stackoverflow.com/q/48084262
tags question: http://stackoverflow.com/q/48074166
tags question: http://stackoverflow.com/q/48044975
tags question: http://stackoverflow.com/q/48131816
tags question: http://stackoverflow.com/q/48035105
tags question: http://stackoverflow.com/q/48117256
tags question: http://stackoverflow.com/q/48065753
tags question: http://stackoverflow.com/q/48082403
tags question: http://stackoverflow.com/q/48111324
tags question: http://stackoverflow.com/q/48169141
tags question: http://stackoverflow.com/q/48028092
tags question: http://stackoverflow.com/q/48117832
tags question: http://stackoverflow.com/q/48123740
tags question: http://stackoverflow.com/q/48085579
tags question: http://stackoverflow.com/q/48064468
tags question: http://stackoverflow.com/q/48086457
tags question: http://stackoverflow.com/q/48082257
tags question: http://stackoverflow.com/q/48016370
tags question: http://stackoverflow.com/q/48028823
tags question: http://stackoverflow.com/q/48090691
tags question: http://stackoverflow.com/q/48098985
tags question: http://stackoverflow.com/q/48101560
tags question: http://stackoverflow.com/q/48099843
tags question: http://stackoverflow.com/q/48142528
tags question: http://stackoverflow.com/q/48032379
tags question: http://stackoverflow.com/q/48148328
tags question: http://stackoverflow.com/q/48050769
tags question: http://stackoverflow.com/q/48156043
tags question: http://stackoverflow.com/q/48049087
tags question: http://stackoverflow.com/q/48106544
tags question: http://stackoverflow.com/q/48105937
tags question: http://stackoverflow.com/q/48043424
tags question: http://stackoverflow.com/q/48042915
tags question: http://stackoverflow.com/q/48044405
tags question: http://stackoverflow.com/q/48141933
tags question: http://stackoverflow.com/q/48070697
tags question: http://stackoverflow.com/q/48109418
tags question: http://stackoverflow.com/q/48068076
tags question: http://stackoverflow.com/q/48090128
tags question: http://stackoverflow.com/q/48093083
tags question: http://stackoverflow.com/q/48167165
tags question: http://stackoverflow.com/q/48120214
tags question: http://stackoverflow.com/q/48115731
tags question: http://stackoverflow.com/q/48107796
tags question: http://stackoverflow.com/q/48073021
tags question: http://stackoverflow.com/q/48055428
tags question: http://stackoverflow.com/q/48125501
tags question: http://stackoverflow.com/q/48151540
tags question: http://stackoverflow.com/q/48128371
tags question: http://stackoverflow.com/q/48150346
tags question: http://stackoverflow.com/q/48067021
tags question: http://stackoverflow.com/q/48019231
tags question: http://stackoverflow.com/q/48172863
tags question: http://stackoverflow.com/q/48172428
tags question: http://stackoverflow.com/q/48103892
tags question: http://stackoverflow.com/q/48161421

http://stackoverflow.com/comment/134164295
comment on: http://stackoverflow.com/a/48154459
score: 0
type: AnswerComment
type: Comment
has text: The imports `from PyQt5 import QtCore from PyQt5.QtCore import QUrl, Qt from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView, QWebEngineProfile from PyQt5.QtNetwork import QNetworkCookie`

http://stackoverflow.com/a/48053364
type: Answer
has body: After lines=input.readlines()[1:] # reads all lines after the header # you read already and skips the 1st one uniques = list(set(x.split('\t')[0] for x in lines)) Caveat: This might reorder your uniques
upvote count: 1
answers question: http://stackoverflow.com/q/48053305
has comment: http://stackoverflow.com/comment/83079122
has comment: http://stackoverflow.com/comment/83079246
downvote count: 0
score: 1

http://stackoverflow.com/comment/83275939
type: Comment
has text: what about option 2 then? You could decouple the abc() method and call from within both routes.
comment on: http://stackoverflow.com/a/48148513
score: 3
type: AnswerComment

http://stackoverflow.com/comment/83212117
type: QuestionComment
score: 0
has text: your slice operation is invalid
comment on: http://stackoverflow.com/q/48117832
type: Comment

concurrency
tags question: http://stackoverflow.com/q/48124257
tag name: concurrency
tags question: http://stackoverflow.com/q/48118194
tags question: http://stackoverflow.com/q/48055157
tags question: http://stackoverflow.com/q/48029672
tags question: http://stackoverflow.com/q/48165302
type: Tag
tags question: http://stackoverflow.com/q/48143565

http://stackoverflow.com/q/48158017
has title: Pytorch Operation to detect NaNs
has body: Is there a Pytorch-internal procedure to detect NaNs in Tensors? Tensorflow has the tf.is_nan and the tf.check_numerics operations ... Does Pytorch have something similar, somewhere? I could not find something like this in the docs... I am looking specifically for a Pytorch internal routine, since I would like this to happen on the GPU as well as on the CPU. This excludes numpy - based solutions (like np.isnan(sometensor.numpy()).any()) ...
type: Question
has answer: http://stackoverflow.com/a/65367978
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48171528
possible better answer: http://stackoverflow.com/a/53420874
has comment: http://stackoverflow.com/comment/134228657
upvote count: 64
answer count: 5
has answer: http://stackoverflow.com/a/53420874
has answer: http://stackoverflow.com/a/62223581
score: 64
tagged with: pytorch
has comment: http://stackoverflow.com/comment/116914514
tagged with: python
has answer: http://stackoverflow.com/a/66129023
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48171528

http://stackoverflow.com/a/70710536
upvote count: 4
has comment: http://stackoverflow.com/comment/140025734
score: 4
downvote count: 0
has body: As of Python 3.7, you can check for the existence of sys.getandroidapilevel(): import sys if hasattr(sys, 'getandroidapilevel'): # Yes, this is Android else: # No, some other OS
type: Answer
answers question: http://stackoverflow.com/q/48019043

http://stackoverflow.com/q/48046440
favorite count: 0
tagged with: compiler-errors
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/48051042
downvote count: 3
tagged with: mysql
type: Question
has body: I am trying to use the pip install mysql-python command and I get the error below. I have no idea what this means someone please help. I have already updated my verison of pip and setuptools and wheels so I am at a loss. I get a big error message but only have the first half presented below. C:\Users\Alex\Desktop\Cornell Stuff\Computer Programs\WinPython-64bit- 3.4.3.3\python-3.4.3.amd64&gt;pip install mysql-python Collecting mysql-python Downloading MySQL-python-1.2.5.zip (108kB) 100% |################################| 112kB 179kB/s Building wheels for collected packages: mysql-python Running setup.py bdist_wheel for mysql-python ... error Complete output from command "C:\Users\Alex\Desktop\Cornell Stuff\Computer Programs\WinPython-64bit-3.4.3.3\python-3.4.3.amd64\python.exe" -u -c "import setuptools, tokenize;__file__='C:\\Users\\Alex\\AppData\\Local\\Temp\\pip-build- 1kxb8j7_\\mysql-python\\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 C:\Users\Alex\AppData\Local\Temp\tmpzz01n6ylpip-wheel- --python-tag cp34: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.4 copying _mysql_exceptions.py -&gt; build\lib.win-amd64-3.4 creating build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\__init__.py -&gt; build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\converters.py -&gt; build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\connections.py -&gt; build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\cursors.py -&gt; build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\release.py -&gt; build\lib.win-amd64-3.4\MySQLdb copying MySQLdb\times.py -&gt; build\lib.win-amd64-3.4\MySQLdb creating build\lib.win-amd64-3.4\MySQLdb\constants copying MySQLdb\constants\__init__.py -&gt; build\lib.win-amd64- 3.4\MySQLdb\constants copying MySQLdb\constants\CR.py -&gt; build\lib.win-amd64- 3.4\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -&gt; buil…
score: -2
has title: pip Install error for mysql-python not working
answer count: 1
has comment: http://stackoverflow.com/comment/83064271
tagged with: python

http://stackoverflow.com/comment/88627583
has text: Cross-posted as https://gis.stackexchange.com/q/266696/115
comment on: http://stackoverflow.com/q/48042637
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48141135
tagged with: pyenv
linked to: http://stackoverflow.com/q/5048112
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/83260988
upvote count: 8
has comment: http://stackoverflow.com/comment/83260590
tagged with: python
tagged with: python-c-api
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/53007303
has body: Im using python3.6.1 installed in pyenv. I have problem with running gdb on my code. When I run gdb --args python mycode.py it ends with error "/home/vydra/.pyenv/shims/python": not in executable format: File format not recognized
has title: Cannot start dbg on my python C extension
type: Question
tagged with: gdb
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83261244
has answer: http://stackoverflow.com/a/53007303

xpath
tags question: http://stackoverflow.com/q/48097819
tags question: http://stackoverflow.com/q/48103019
tags question: http://stackoverflow.com/q/48050870
tags question: http://stackoverflow.com/q/48075257
tag name: xpath
tags question: http://stackoverflow.com/q/48163269
tags question: http://stackoverflow.com/q/48129892
tags question: http://stackoverflow.com/q/48028931
tags question: http://stackoverflow.com/q/48040118
tags question: http://stackoverflow.com/q/48015404
tags question: http://stackoverflow.com/q/48047766
tags question: http://stackoverflow.com/q/48141221
tags question: http://stackoverflow.com/q/48124409
tags question: http://stackoverflow.com/q/48065269
tags question: http://stackoverflow.com/q/48164675
tags question: http://stackoverflow.com/q/48085095
tags question: http://stackoverflow.com/q/48083073
tags question: http://stackoverflow.com/q/48144574
type: Tag
tags question: http://stackoverflow.com/q/48049289
tags question: http://stackoverflow.com/q/48074233
tags question: http://stackoverflow.com/q/48134390
tags question: http://stackoverflow.com/q/48048657
tags question: http://stackoverflow.com/q/48146486
tags question: http://stackoverflow.com/q/48104633

pyqt
type: Tag
tags question: http://stackoverflow.com/q/48137040
tags question: http://stackoverflow.com/q/48049836
tags question: http://stackoverflow.com/q/48037355
tags question: http://stackoverflow.com/q/48105026
tags question: http://stackoverflow.com/q/48096381
tags question: http://stackoverflow.com/q/48132313
tags question: http://stackoverflow.com/q/48045736
tags question: http://stackoverflow.com/q/48121711
tags question: http://stackoverflow.com/q/48035032
tags question: http://stackoverflow.com/q/48084565
tags question: http://stackoverflow.com/q/48157811
tags question: http://stackoverflow.com/q/48039309
tags question: http://stackoverflow.com/q/48018458
tags question: http://stackoverflow.com/q/48101833
tags question: http://stackoverflow.com/q/48125641
tags question: http://stackoverflow.com/q/48053521
tags question: http://stackoverflow.com/q/48121393
tags question: http://stackoverflow.com/q/48071926
tags question: http://stackoverflow.com/q/48116698
tags question: http://stackoverflow.com/q/48047239
tags question: http://stackoverflow.com/q/48105646
tags question: http://stackoverflow.com/q/48077955
tags question: http://stackoverflow.com/q/48097207
tags question: http://stackoverflow.com/q/48135532
tags question: http://stackoverflow.com/q/48027254
tags question: http://stackoverflow.com/q/48055036
tags question: http://stackoverflow.com/q/48142341
tags question: http://stackoverflow.com/q/48103685
tags question: http://stackoverflow.com/q/48022786
tags question: http://stackoverflow.com/q/48054334
tags question: http://stackoverflow.com/q/48168432
tags question: http://stackoverflow.com/q/48057638
tags question: http://stackoverflow.com/q/48132799
tags question: http://stackoverflow.com/q/48019883
tags question: http://stackoverflow.com/q/48107167
tags question: http://stackoverflow.com/q/48151935
tags question: http://stackoverflow.com/q/48140576
tags question: http://stackoverflow.com/q/48028103
tags question: http://stackoverflow.com/q/48070224
tags question: http://stackoverflow.com/q/48133873
tags question: http://stackoverflow.com/q/48042953
tags question: http://stackoverflow.com/q/48073261
tags question: http://stackoverflow.com/q/48057922
tags question: http://stackoverflow.com/q/48066466
tags question: http://stackoverflow.com/q/48047184
tags question: http://stackoverflow.com/q/48139087
tags question: http://stackoverflow.com/q/48036742
tags question: http://stackoverflow.com/q/48080650
tag name: pyqt
tags question: http://stackoverflow.com/q/48123219
tags question: http://stackoverflow.com/q/48036069
tags question: http://stackoverflow.com/q/48140781
tags question: http://stackoverflow.com/q/48087336
tags question: http://stackoverflow.com/q/48046462

http://stackoverflow.com/comment/128621356
comment on: http://stackoverflow.com/a/48038206
type: AnswerComment
type: Comment
has text: Consider that "returning a value" means giving some value back to the caller, even if it's a `None`. `NoReturn` means that the function doesn't give anything back to the caller, including the top of the call stack. If there weren't exception handling, it would be like an infinite loop because the interpreter would never leave the function's stack frame. When you `raise`, you're telling the interpreter "if the caller can't recover this condition, drop the entire call stack and stop." That's why `try/except` is considered to be part of control flow, like `if` or `for`.
score: 1

http://stackoverflow.com/comment/83143037
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48084015
has text: @ParalysisByAnalysis `as_index=False` is slightly more efficient than `groupby` + `reset_index`. I'd recommend doing a timing comparison and accepting based on the answer's merit, not the speed of the answerer ;-)
type: Comment

http://stackoverflow.com/comment/83259297
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48140571
has text: Of course, get_speed and get_rpm would somehow recall each other at the end of each execution or find a way to get me the latest value at each call (I think there is something like this in python [generator with yield ?] )

http://stackoverflow.com/q/48034096
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83056209
has comment: http://stackoverflow.com/comment/83056056
answer count: 0
score: 1
tagged with: twitter
upvote count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83055991
has title: sorry page not found message while using valid WOEID for Twitter API
type: Question
has comment: http://stackoverflow.com/comment/83056181
has comment: http://stackoverflow.com/comment/83055725
tagged with: python-twitter
has body: I am trying to generate the trending topics for WOEID 23424911 (Nepal). It generates the following message TwitterError: [{u'message': u'Sorry, that page does not exist.', u'code': 34}] code used: import twitter consumer_key=..... consumer_secret=...... access_token=....... access_token_secret=..... api = twitter.Api(consumer_key, consumer_secret,access_token, access_token_secret) print api.GetTrendsWoeid(woeid=23424911, exclude=None) However, interestingly for WOEID 23424848 (India), the topics are topics are generated. WOEID could be extracted from https://query.yahooapis.com/v1/public/yql?q=select+*+from+geo.places+where+text+=+%27Nepal%27 Any thoughts why I am getting this error?
has comment: http://stackoverflow.com/comment/83040102
tagged with: woe-id
downvote count: 0

http://stackoverflow.com/q/48076908
has comment: http://stackoverflow.com/comment/83127942
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83127518
accepted answer: http://stackoverflow.com/a/48077313
answer count: 1
has body: I have a result object looking like this: result = [{ start: 0, length: 2 }, { start: 5, length: 3, }] I need to create a html tag like this: I tried something like this: and several other variations. How can I achieve my goal? I´m new to jinja, so excuse this maybe "stupid" question. :-)
has comment: http://stackoverflow.com/comment/83128248
tagged with: python
has comment: http://stackoverflow.com/comment/83128293
has comment: http://stackoverflow.com/comment/83127977
score: 0
has answer: http://stackoverflow.com/a/48077313
has title: jinja2: Writing data in tag attribute within a loop
tagged with: jinja2

http://stackoverflow.com/comment/83222449
comment on: http://stackoverflow.com/q/48122550
has text: @Likak you would still need to modify your algorithm, because you already store the data in RAM, that is RAM doesn't solve the issue, it just lets you consider more efficient ways to deal with the issue.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48033022
accepted answer of: http://stackoverflow.com/q/48032686
has body: You are almost there. You can either pivot your Cvalues, or better yet, directly go for pivot_table and utilize its built-in option of aggfunc. df = pd.DataFrame({'A':[2,0,1,1,2,0,1,0], 'B':[1,2,1,0,1,2,1,1], 'C':[10,20,30,40,50,60,70,80]}) Recommended One-Liner: res = df.pivot_table(index='A', columns='B', values='C', aggfunc='mean') Making Your Method Work: Cvalues = df.groupby(['A','B'],as_index=False).mean() res = Cvalues.pivot(index='A', columns='B', values='C') Why bother, but just in case, you can make this a little more compact: res = df.groupby(['A','B'],as_index=False).mean().pivot(index='A', columns='B', values='C') Here is the result of both ways: B 0 1 2 A 0 NaN 80.0 40.0 1 40.0 50.0 NaN 2 NaN 30.0 NaN where, at the intersection of A=2 and B=1: 30.0 = (10 + 50)/2
answers question: http://stackoverflow.com/q/48032686
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/83332966
type: AnswerComment
score: 0
type: Comment
has text: @ FatihAkici , like this? Next discussion , https://stackoverflow.com/questions/48175666/deploying-a-pandas-data-frame-to-a-url-using-urllib-and-getting-the-results-in-a
comment on: http://stackoverflow.com/a/48070870

http://stackoverflow.com/a/48083046
score: 0
has comment: http://stackoverflow.com/comment/83140662
type: Answer
has body: It is not mistake to use the super but not for that goal.Explained super I have changed your code #!/usr/bin/env python class Base1(object): def __init__(self): self.base1var = "this is base1" class Base2(object): def __init__(self): self.base2var = "this is base2" class MainClass(Base2, Base1): def __init__(self): super(MainClass, self).__init__() if __name__ == "__main__": a = MainClass() print (a.base2var) Than you have this is base2
has comment: http://stackoverflow.com/comment/83140639
answers question: http://stackoverflow.com/q/48082893

http://stackoverflow.com/comment/117659200
has text: I've installed xlrd and shows up when I run `pip freeze` however still having same error message...
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/53264098

http://stackoverflow.com/q/48087466
has answer: http://stackoverflow.com/a/48098257
score: 0
tagged with: api
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: How do use the tweet_mode='extended' in Twitter Api when streaming tweets?
tagged with: tweepy
tagged with: stream
tagged with: twitter
type: Question
has body: auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) twitterStream = Stream(auth, listener()) tweepy.Cursor(api.search, q='to:3NASA', tweet_mode='extended').items(limit) I always get an error File "stream.py", line 41, in tweepy.Cursor(api.search, q='to:3NASA', tweet_mode='extended').items(limit) AttributeError: module 'api' has no attribute 'search'

machine-learning
tags question: http://stackoverflow.com/q/48127811
tags question: http://stackoverflow.com/q/48143753
tags question: http://stackoverflow.com/q/48098951
tags question: http://stackoverflow.com/q/48015235
tags question: http://stackoverflow.com/q/48065685
tags question: http://stackoverflow.com/q/48140133
tags question: http://stackoverflow.com/q/48026129
tags question: http://stackoverflow.com/q/48138475
tags question: http://stackoverflow.com/q/48029870
tags question: http://stackoverflow.com/q/48045708
tags question: http://stackoverflow.com/q/48090757
tags question: http://stackoverflow.com/q/48053907
tags question: http://stackoverflow.com/q/48061976
tags question: http://stackoverflow.com/q/48033430
tags question: http://stackoverflow.com/q/48074158
tags question: http://stackoverflow.com/q/48102364
tags question: http://stackoverflow.com/q/48046052
tags question: http://stackoverflow.com/q/48100173
tags question: http://stackoverflow.com/q/48057841
tags question: http://stackoverflow.com/q/48041560
tags question: http://stackoverflow.com/q/48027263
tags question: http://stackoverflow.com/q/48158547
tags question: http://stackoverflow.com/q/48074705
tags question: http://stackoverflow.com/q/48032547
tags question: http://stackoverflow.com/q/48074462
tags question: http://stackoverflow.com/q/48117562
tags question: http://stackoverflow.com/q/48137617
tags question: http://stackoverflow.com/q/48088461
tags question: http://stackoverflow.com/q/48144371
tags question: http://stackoverflow.com/q/48027801
tags question: http://stackoverflow.com/q/48114820
tags question: http://stackoverflow.com/q/48060799
tag name: machine-learning
tags question: http://stackoverflow.com/q/48100762
tags question: http://stackoverflow.com/q/48035987
tags question: http://stackoverflow.com/q/48108723
tags question: http://stackoverflow.com/q/48063789
tags question: http://stackoverflow.com/q/48021890
tags question: http://stackoverflow.com/q/48046185
tags question: http://stackoverflow.com/q/48045217
tags question: http://stackoverflow.com/q/48092433
tags question: http://stackoverflow.com/q/48071753
tags question: http://stackoverflow.com/q/48090426
tags question: http://stackoverflow.com/q/48040685
tags question: http://stackoverflow.com/q/48044595
type: Tag
tags question: http://stackoverflow.com/q/48034625
tags question: http://stackoverflow.com/q/48134179
tags question: http://stackoverflow.com/q/48142421
tags question: http://stackoverflow.com/q/48084007
tags question: http://stackoverflow.com/q/48129527
tags question: http://stackoverflow.com/q/48043922
tags question: http://stackoverflow.com/q/48096066
tags question: http://stackoverflow.com/q/48093364
tags question: http://stackoverflow.com/q/48155026
tags question: http://stackoverflow.com/q/48114258
tags question: http://stackoverflow.com/q/48132807
tags question: http://stackoverflow.com/q/48092772
tags question: http://stackoverflow.com/q/48048776
tags question: http://stackoverflow.com/q/48138420
tags question: http://stackoverflow.com/q/48121895
tags question: http://stackoverflow.com/q/48050953
tags question: http://stackoverflow.com/q/48161116
tags question: http://stackoverflow.com/q/48026206
tags question: http://stackoverflow.com/q/48040346
tags question: http://stackoverflow.com/q/48062662
tags question: http://stackoverflow.com/q/48035531
tags question: http://stackoverflow.com/q/48106948
tags question: http://stackoverflow.com/q/48081971
tags question: http://stackoverflow.com/q/48070505
tags question: http://stackoverflow.com/q/48058044
tags question: http://stackoverflow.com/q/48153854
tags question: http://stackoverflow.com/q/48162279

http://stackoverflow.com/comment/127357352
score: 2
has text: Still works in 2022
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51631111

http://stackoverflow.com/q/48088193
type: Question
tagged with: opencv
has title: How to get rid of random, jagged edges with OpenCV findContours()?
has comment: http://stackoverflow.com/comment/83151195
upvote count: 4
answer count: 2
linked to: http://stackoverflow.com/q/47936474
has answer: http://stackoverflow.com/a/48089151
linked to: http://stackoverflow.com/q/37068448
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83151211
has body: I previously posted here And I've seen this post Despite the great information provided by the community, I have been unable to smoothly trace an image using cv2.findContours(). While in my previous post I asked about generating splines to smoothly trace curves, my focus now is to get a smooth trace of an object, regardless of how many points are generated for the contour. I consistently get results with jagged edges: My desired output would be something similar to this, which I've manually created in Adobe Illustrator: I have experimented extensively with blurring and thresholding, and have been unable to get a smooth outline. I am running openCV version 3.3.0. import numpy as np import cv2 import math from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas print(cv2.__version__) im = cv2.imread('img.jpg') # orient the image properly # grab the dimensions of the image and calculate the center # of the image (h, w) = im.shape[:2] center = (w / 2, h / 2) # rotate the image 180 degrees M = cv2.getRotationMatrix2D(center, 180, 1.0) rotated = cv2.warpAffine(im, M, (w, h)) # flip the image across flippedColor = cv2.flip(rotated, 1) #for testing imgray = cv2.cvtColor(rotated, cv2.COLOR_BGR2GRAY) flipped = cv2.flip(imgray, 1) (thresh, binRed) = cv2.threshold(flipped, 180, 255, cv2.THRESH_BINARY) _, Rcontours, hier_r = cv2.findContours(binRed,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE) r_areas = [cv2.contourArea(c) for c in Rcontours] max_rarea = np.argmax(r_areas) CntExternalMask = np.ones(binRed.shape[:2], dtype="uint8") * 255 contour= Rcontours[max_rarea] cv2.drawContours(flippedColor,[contour],-1,(255,0,0),1)
score: 2
downvote count: 2
has answer: http://stackoverflow.com/a/48088823

http://stackoverflow.com/comment/83147506
has text: can you please share test-data-01.csv ?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48034625
type: Comment

http://stackoverflow.com/q/48037284
downvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83044765
tagged with: plotly
possible better answer: http://stackoverflow.com/a/48037403
has comment: http://stackoverflow.com/comment/83044885
type: Question
answer count: 2
tagged with: plotly-dash
upvote count: 1
has answer: http://stackoverflow.com/a/48973367
accepted answer: http://stackoverflow.com/a/48973367
tagged with: utf-8
has answer: http://stackoverflow.com/a/48037403
favorite count: 0
tagged with: python-3.x
has title: Syntax error: Non-UTF-8 code starting with '\xe1"
score: -3
has comment: http://stackoverflow.com/comment/83053445
tagged with: python
has body: Technically: I just want to use "Dash" by "plotly", "getting started" example (https://plot.ly/dash/getting-started), but I cannot. Any assumptions? I cannot define the error more then it is in title. (I do not want to feed you with inaccurate assumptions. Thank you for possible answer :) )

http://stackoverflow.com/comment/83295860
comment on: http://stackoverflow.com/q/48158027
type: QuestionComment
score: 0
has text: Have you looked at the XML library? And are you set on xml for a particular reason?
type: Comment

http://stackoverflow.com/comment/83139694
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48082504
has text: If he is operating on a dataframe that has multiple `ID` and `Document` categories wouldn't you have to `groupby(["ID","Document","DueDate"])` to get a generalizable outcome?

http://stackoverflow.com/q/48161421
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: networkx
type: Question
has title: How to add attribute to the highest degree centrality node using Python?
has comment: http://stackoverflow.com/comment/83308648
has comment: http://stackoverflow.com/comment/83318254
has body: I am looking for a way to increase the size of the highest degree centrality node so that I can add attributes like C1 or C2 based on their category. I have tried a solution, but it is not perfect. I want to reduce to data frame transformation and the node location code. Ask/Help needed: 1. The data frame transformation took 15 steps before I get the df that I need. Is there any way to do it on single line? To locate x,y of the label, I used trial and error method for ex. -0.186 and -0.341 but the node label is still outside not inside the center node. Is there a better way to find node's x, y values? Please see my solution: data= { '0': [1,0,0,0,0,1], '1': [0,1,0,0,0,0], '2': [0,0,1,0,1,0], '3': [0,0,0,1,0,0], 'Newspaper': ['G1','G2','G3','G4','G5','G6'] } df_result=pd.DataFrame(data) df_C0=df_result'newspaper','C0'[df_result['C0'] ==1] df_C1=df_result'newspaper','C1'[df_result['C1'] ==1] df_C2=df_result'newspaper','C2'[df_result['C2'] ==1] df_C3=df_result'newspaper','C3'[df_result['C3'] ==1] #selecting df_C0.C0= df_C0.C0.apply(lambda x: 'C0') df_C1.C1= df_C1.C1.apply(lambda x: 'C1') df_C2.C2= df_C2.C2.apply(lambda x: 'C2') df_C3.C3= df_C3.C3.apply(lambda x: 'C3') #changing col=['newspaper', 'C'] df_C0.columns=col df_C1.columns=col df_C2.columns=col df_C3.columns=col frames = [df_C0, df_C1, df_C2,df_C3] result = pd.concat(frames) #Creating the Graph object G=nx.from_pandas_dataframe(result, 'newspaper', 'C') fig=plt.figure(figsize=(12, 10)) ax = fig.add_subplot(111) pos = nx.spring_layout(G,k=.25) x0,y0=pos.get('C0') x1,y1=pos.get('C1') x2,y2=pos.get('C2') x3,y3=pos.get('C3') x0 +=-0.186 y0 +=-0.341 x1 +=-0.186 y1 +=-0.341 x2 +=-0.186 y2 +=-0.341 x3 +=-0.186 y3 +=-0.341 ax.text(x0,y0, 'C0',color='green', fontsize=15) ax.text(x1,y1, 'C1',color='green', fontsize=15) ax.text(x2,y2, 'C2',color='green', fontsize=15) ax.text(x3,y3, 'C3',color='green', fontsize=15) nx.draw_networkx(G, pos=pos, node_size=100, with_labels=False, alpha=0.5) plt.show()
score: 0

http://stackoverflow.com/comment/82998607
type: QuestionComment
has text: Possible duplicate of [bash: pip: command not found](https://stackoverflow.com/questions/9780717/bash-pip-command-not-found)
comment on: http://stackoverflow.com/q/48014769
score: 0
type: Comment

http://stackoverflow.com/comment/83157280
has text: possible duplicate to https://stackoverflow.com/q/13685201/2312051
comment on: http://stackoverflow.com/q/48091504
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48090219
has comment: http://stackoverflow.com/comment/83154782
has comment: http://stackoverflow.com/comment/83154772
has comment: http://stackoverflow.com/comment/83154727
has comment: http://stackoverflow.com/comment/83154845
type: Answer
has comment: http://stackoverflow.com/comment/83154750
score: 4
has comment: http://stackoverflow.com/comment/83154959
downvote count: 0
answers question: http://stackoverflow.com/q/48090128
upvote count: 4
has body: You can use: first create index from column fill_until create mask by numpy broadcasting use mask and apply fillna with method ffill (same as ffill) last reset_index and for same order of columns add reindex df = pd.DataFrame([[1, 2 ,np.nan,np.nan,10 , 2009], [1, 3 , np.nan , np.nan , np.nan , 2010], [4, np.nan , 7 , np.nan,np.nan , 2011]], columns=[2007,2008,2009,2010,2011 , 'fill_until']) print (df) 2007 2008 2009 2010 2011 fill_until 0 1 2.0 NaN NaN 10.0 2009 1 1 3.0 NaN NaN NaN 2010 2 4 NaN 7.0 NaN NaN 2011 df1 = df.set_index('fill_until') m = df1.columns.values &lt;= df1.index.values[:, None] print (m) [[ True True True False False] [ True True True True False] [ True True True True True]] df = df1.mask(m, df1.ffill(axis=1)).reset_index().reindex(columns=df.columns) print (df) 2007 2008 2009 2010 2011 fill_until 0 1 2.0 2.0 NaN 10.0 2009 1 1 3.0 3.0 3.0 NaN 2010 2 4 4.0 7.0 7.0 7.0 2011

http://stackoverflow.com/q/48043313
tagged with: opencsv
answer count: 0
has comment: http://stackoverflow.com/comment/83057601
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83057455
type: Question
has comment: http://stackoverflow.com/comment/83057866
has title: str object has no attribute day error
has body: Here's my code. Not sure what the issue is. Where do I get the day attribute for the CSV file? does it need to be added in filtering? import apache_log_parser from pandas import DataFrame parser = apache_log_parser.make_parser('%h %l %u %t "%r" %&gt;s') data = {'day': [], 'time': []} with open('coursework.csv') as in_f: reader = DictReader(in_f) for line in reader: identifier = '%s_%s' % (line['time_received_isoformat'], line['remote_host']) data['day'].append(line['time_received_isoformat'].day) if 'search' in line['request_url_path']: data['category'].append('search') elif 'browse' in line['request_url_path']: data['category'].append('browse') elif 'add-to-cart' in line['request_url_path'] or 'remove-from-cart' in line['request_url_path']: data['category'].append('cart') elif 'book' in line['request_url_path']: data['category'].append('item') elif line['request_url_path'] == '/baseline/': data['category'].append('baseline') elif line['request_url_path'] == '/explore/' or line['request_url_path'] =='/review/': data['category'].append('modern') else: print(line['request_url_path']) print(data['day'])
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/a/48088251
has body: You can use np.where(np.logical_and(a&gt;=-1024 , a&lt;=0),0,a) This will check if the element of a is in the range [-1024,0] and make it 0 else leave it unchanged. You can also refer this answer Numpy where function multiple conditions
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48088196
downvote count: 0
type: Answer

http://stackoverflow.com/a/49490415
answers question: http://stackoverflow.com/q/48098829
downvote count: 0
score: 13
upvote count: 13
has body: You can think of signatures in Celery as placeholders for running tasks. For example, let's say you wish to construct a complex workflow consisting of chords, groups and chains, and use it in a different piece of code. In this case, it would be easier to define various task signatures and place them in your workflow as neccessary: def create_workflow(): return chord([sig_1, sig_2, chain([sig_3, sig_4])], body=group([sig_5, sig_6]).set(queue=PRIORITY_QUEUE)) Where each signature in this example has been pre-defined, which can ,make a lot of difference should those signatures be complicated. Then you can call create_workflow() and apply delay() to it whenever needed
type: Answer

http://stackoverflow.com/q/48030702
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/48030764
has comment: http://stackoverflow.com/comment/83031892
has comment: http://stackoverflow.com/comment/83031774
has answer: http://stackoverflow.com/a/48030915
score: 0
has comment: http://stackoverflow.com/comment/83031814
accepted answer: http://stackoverflow.com/a/48030737
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48030760
has answer: http://stackoverflow.com/a/48030760
has comment: http://stackoverflow.com/comment/83031658
tagged with: list-comprehension
has title: Nested Control Flow in list comprehension Python
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/83031693
has body: How can I convert this for loop into a list comprehension with a nested if statement? stock = [] for i in range(10): if i &lt;= 5: trade = "buy" elif i &gt; 5 and i &lt;= 7: trade = "hold" if i == 6: trade = "short-sell" else: trade = "sell" stock.append(trade.capitalize()) stock ['Buy', 'Buy', 'Buy', 'Buy', 'Buy', 'Buy', 'Short-sell', 'Hold', 'Sell', 'Sell'] The best I've got so far is: ["Buy" if i &lt;= 5 else "Hold" if i &gt; 5 and i &lt;= 7 else "Sell" for i in range(10)] ['Buy', 'Buy', 'Buy', 'Buy', 'Buy', 'Buy', 'hold', 'hold', 'Sell', 'Sell'] Any help would be totally appreciated! :)
has answer: http://stackoverflow.com/a/48030737
has comment: http://stackoverflow.com/comment/83031815
tagged with: control-flow
tagged with: nested

http://stackoverflow.com/q/48028092
accepted answer: http://stackoverflow.com/a/48028128
tagged with: pandas
answer count: 1
has body: I'm trying to get the last viable date in a multi-index dataframe: ix = pd.MultiIndex.from_product([["a"], pd.PeriodIndex(start="2017-01", end="2017-03")]) df = pd.DataFrame(data=[0,1, np.nan], index=ix, columns=["test"]) df # outputs test a 2017-01 0.0 2017-02 1.0 2017-03 NaN So far so good, but slicing this and returning the last returns the entire index: df.loc[df["test"].notnull(), "test"].index MultiIndex(levels=[['a'], [2017-01, 2017-02, 2017-03]], labels=[[0, 0], [0, 1]]) My thinking is this should return an array where .index.levels[1][-1] last element is something like Period('2017-02')?
favorite count: 0
has comment: http://stackoverflow.com/comment/83026385
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48028128
upvote count: 1
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/83026257
has comment: http://stackoverflow.com/comment/83026303
has title: Pandas PeriodIndex boolean slice returning entire index

http://stackoverflow.com/comment/83214172
score: 1
comment on: http://stackoverflow.com/a/48118815
type: AnswerComment
type: Comment
has text: Interesting addition. So you say `word in word_b` is going to be O(1) if it is a set then? Still, you are doing `for word in word_a`, so that makes your algorithm O(n) right?

http://stackoverflow.com/comment/83214102
score: 0
type: Comment
type: QuestionComment
has text: @StevenRumbalski I was going to say: use `if must_delete in line:` .. but you got a point
comment on: http://stackoverflow.com/q/48118831

http://stackoverflow.com/comment/83304293
type: Comment
has text: @e.s., Thanks, it's working with `if __name__ == '__main__'. Any idea, how to increment the score on the fly and return the final score only. Is it possible to pass article instead of list-of-keywords to worker method?
comment on: http://stackoverflow.com/q/48162230
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83254769
type: QuestionComment
has text: Did you try printing data, or conditional expression results? were there any clues?
comment on: http://stackoverflow.com/q/48138578
type: Comment
score: 0

http://stackoverflow.com/q/48131742
type: UnansweredQuestion
tagged with: python
has title: Stuck on Format specifier
answer count: 0
has comment: http://stackoverflow.com/comment/83240709
type: Question
has comment: http://stackoverflow.com/comment/83243332
tagged with: python-3.6
score: 0
has body: I was going through this tutorial on making a RNN LSTM network and I came across this format specifier: '{0:020b}'.format(i) the expected output is a 20 character long string of 0's and 1's but I can't seem to figure out why and how this specifier works. Could anyone explain this? Cheers
has comment: http://stackoverflow.com/comment/83240587

http://stackoverflow.com/a/48120126
has body: Just do for loop inside of the file(text file ofc) and add every word and how many times it occurs and return the dictionary. To split words just add the whole text of the file in one string amd use split function to separate the words into list and loop through it and do the dictionary thing i told you at the begging.
answers question: http://stackoverflow.com/q/48119814
score: 0
type: Answer

resampling
tags question: http://stackoverflow.com/q/48024559
tags question: http://stackoverflow.com/q/48142528
tag name: resampling
type: Tag
tags question: http://stackoverflow.com/q/48081837

http://stackoverflow.com/a/48032234
accepted answer of: http://stackoverflow.com/q/48031979
answers question: http://stackoverflow.com/q/48031979
score: 0
type: AcceptedAnswer
has body: df date 0 02.01.2013 1 03.01.2013 2 05.01.2013 3 06.01.2014 4 15.01.2014 Convert the column to datetime using pd.to_datetime, and test the dt.year attribute - m = pd.to_datetime(df.date).dt.year != 2014 m 0 True 1 True 2 True 3 False 4 False Name: date, dtype: bool Use the mask to filter on df - df = df[m] If the datetime column is the index, you'd instead need to convert the df.index - m = pd.to_datetime(df.index).year != 2014
type: Answer

http://stackoverflow.com/comment/83081327
comment on: http://stackoverflow.com/q/48054448
type: Comment
type: QuestionComment
has text: @HughBothwell I fixed my indentation. Do you know why it is returning equal odds? I know it is way more complicated than necessary, that's just how I did it.
score: 0

http://stackoverflow.com/q/48054671
has comment: http://stackoverflow.com/comment/83082036
has comment: http://stackoverflow.com/comment/83082209
has comment: http://stackoverflow.com/comment/83082538
has comment: http://stackoverflow.com/comment/83085051
has comment: http://stackoverflow.com/comment/83082002
has comment: http://stackoverflow.com/comment/83081974
has comment: http://stackoverflow.com/comment/83081823
answer count: 0
has title: Re-configuring allauth to fit custom specifications
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/83081803
has comment: http://stackoverflow.com/comment/83081884
has comment: http://stackoverflow.com/comment/83081858
type: Question
has body: I have a set of expectations I'm trying to achieve. I want a sign up, login, and forget password page. I also want to have social sign in using Twitter, Facebook, or Google. Another thing I want is to send a confirmation email to the user validating their account. I know I can do this with Django allauth, but allauth comes with extra features that I don't need. For example, I don't need the password reset and change email pages. I want to remove these pages and their corresponding functionality, but I'm afraid I might break the code if I do this. I was thinking about two solutions. One solution would be to go through the allauth templates and change some of the code to fit my specifications, but I feel like it would be very tedious because a lot of things might break if I remove some funcionality. The second solution I was thinking of doing was building on top of auth and using a custom User model and building custom login, sign up, and reset pages. Adding the required functionality and everything. I could also build the models to provide social login by copying allauth's templates. I am just debating on what would be the best possible choice to do this. I would be happy if anyone can point me in the right direction.
has comment: http://stackoverflow.com/comment/83081913
has comment: http://stackoverflow.com/comment/83084842
score: 0
has comment: http://stackoverflow.com/comment/83082446
has comment: http://stackoverflow.com/comment/83082147
has comment: http://stackoverflow.com/comment/83082512
has comment: http://stackoverflow.com/comment/83082186
has comment: http://stackoverflow.com/comment/83082064
has comment: http://stackoverflow.com/comment/83082470
has comment: http://stackoverflow.com/comment/83081894
tagged with: python
has comment: http://stackoverflow.com/comment/83081887

http://stackoverflow.com/comment/83075378
score: 0
type: AnswerComment
type: Comment
has text: please check when you write the URL on the browser, does it show your image or not? can you show your image with a specific URL? if yes please write the true full address here.
comment on: http://stackoverflow.com/a/48050220

http://stackoverflow.com/q/48034678
accepted answer: http://stackoverflow.com/a/48034698
upvote count: 0
has comment: http://stackoverflow.com/comment/83039263
tagged with: scope
has title: Scope of variable in python
has comment: http://stackoverflow.com/comment/83039330
has body: Can some please explain to me this code def zap(): print stype def main(): if True: stype="something" zap() else: stype="something else" if __name__ == '__main__': main() stype is already defined before I called zap function But I'm getting this error. Traceback (most recent call last): File "C:\Users\x126\Desktop\ss.py", line 12, in &lt;module&gt; main() File "C:\Users\x126\Desktop\ss.py", line 7, in main zap() File "C:\Users\x126\Desktop\ss.py", line 2, in zap print stype NameError: global name 'stype' is not defined
favorite count: 0
duplicate of: http://stackoverflow.com/q/423379
has answer: http://stackoverflow.com/a/48034776
has comment: http://stackoverflow.com/comment/83039262
has comment: http://stackoverflow.com/comment/83039278
score: -3
tagged with: python
linked to: http://stackoverflow.com/q/423379
possible better answer: http://stackoverflow.com/a/48034776
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48034698
downvote count: 3
type: Question
answer count: 2

http://stackoverflow.com/q/48146012
has comment: http://stackoverflow.com/comment/83270267
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83270681
has title: Converting between DEC(base 10) and HEX(base 16) using two's complement
downvote count: 0
tagged with: twos-complement
score: 1
type: Question
has answer: http://stackoverflow.com/a/48147017
has body: As the title says I need to make a function that converts between the 2 bases, DEC and HEX in twos complement. The number of bits the value uses is known from the start. After doing more than a little digging around i found the following algorithm: Given a number in DEC. Get the absolute value of the number. Get the binary(BIN) value of the abs from step 2. Pad with 0s on the left until the number is the desired length. NOT all the bits obtained in step 4. Add 1 to the result. (Easiest way in practice is probably to convert back to DEC, add 1, and back to BIN) Convert to HEX. Done. This algorithm from what I observer might only work if the original number is negative(&lt;0). I managed to get results that seem correct by making the following modification: On step 6, don't add 1. Instead add the opposite of the signature of the original number. For example if the original number was negative, like -455 then add 1, if it was positive, like 10002 then "add" -1. This does seem to give positive results but I'm not sure about it's soundness as I have never worked with two's complement before this and this modification to step 6 was in my view logic + guesswork - formal_knowledge. Here is the Python 3.6 function I came up with, the DEC value is an int, all other values are represented as strings, the desired length i assumed was just the next multiple of 4: def d2h(i: int) -&gt; str: sign = (i // abs(i)) if i is not 0 else 1 step1 = i step2 = abs(step1) step3 = bin(step2)[2:] step4 = step3 while len(step4) % 4 != 0: step4 = '0' + step4 step5 = step4.replace('0', 'O') \ .replace('1', '0') \ .replace('O', '1') step6 = bin(int(step5, 2) + -sign)[2:] step7 = hex(int(step6, 2))[2:] return step7 As for converting back, from a HEX value to a DEC one, what I managed to kind of "reverse engineer"(as I was not able to find something that actually explained this): Given a number in HEX. Get it's representation in binary, BIN. Pad with 0 until the desired length. Check if the leftmost …
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83270358
upvote count: 1
has comment: http://stackoverflow.com/comment/83270706
answer count: 1
favorite count: 0
tagged with: hex
tagged with: binary

http://stackoverflow.com/comment/83139990
has text: What exactly is the problem? `B` is only approximately an isometry, the observed differences are not that large. As this is not a coding problem, the question would be better asked on the mathematics, statistics or scientific computing portals of the stackexchange.com network.
comment on: http://stackoverflow.com/q/48081971
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/97557923
type: Comment
comment on: http://stackoverflow.com/a/48178857
score: 2
type: AnswerComment
has text: Just remember that PyTorch uses a cached GPU memory allocator. You might see low GPU-Utill for nividia-smi even if it's fully used.

http://stackoverflow.com/q/48029852
has comment: http://stackoverflow.com/comment/83029922
score: -1
accepted answer: http://stackoverflow.com/a/48070871
has comment: http://stackoverflow.com/comment/83029917
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83030289
upvote count: 0
has body: I was programming a project of secret messages which uses a few lists and appends. To my understanding, I don't think that any of my lists are out of range so I am very confused on why I am getting this error. Here is my code. from tkinter import Tk, messagebox, simpledialog def is_even(number): return number % 2 == 0 def get_even_letters(message): even_letters = [] for counter in range(0, len(message)): if is_even(counter): even_letters.append(message[counter]) return even_letters def get_odd_letters(message): odd_letters = [] for counter in range(0, len(message)): if not is_even(counter): odd_letters.append(message[counter]) return odd_letters def swap_letters(message): letter_list = [] if not is_even(len(message)): message = message + 'x' even_letters = get_even_letters(message) odd_letters = get_odd_letters(message) for counter in range(0, int(len(message)/2)): letter_list.append(odd_letters[counter]) letter_list.append(even_letters[counter]) new_message = ''.join(letter_list) return new_message def get_task(): task = simpledialog.askstring('Task', 'Do you want to encrypt or decrypt?') return task def get_message(): message = simpledialog.askstring('Message', 'Enter the secret message: ') return message root = Tk() root.withdraw() while True: task = get_task() if task == 'encrypt': message = get_message() encrypted = swap_letters(message) messagebox.showinfo('Ciphertext of the secret message: ', encrypted) elif task == 'decrypt': message = get_message() decrypted = swap_letters(message) messagebox.showinfo('Plaintext of the secret message: ', decrypted) else: break root.mainloop() Here is my error code: Traceback (most recent call last): File "C:/Users/Osprey/AppData/Local/Programs/Python/Python36-32/secret_messages.py", line 52, in encrypted = swap_letters(message) File "C:/Users/Osprey/AppData/Local/Programs/Python/Python36-32/secret_messages.py", line 31, in swap_letters letter_list.append(odd_letters[counter]) IndexError: list index out of range
favorite count: 0
has title: IndexError: list index out of range i am not reading files and my list does not seem to be out of range
tagged with: python
has answer: http://stackoverflow.com/a/48070871
possible better answer: http://stackoverflow.com/a/48030086
has answer: http://stackoverflow.com/a/48030086
downvote count: 1
has comment: http://stackoverflow.com/comment/83029891
has comment: http://stackoverflow.com/comment/83029942
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83029944

http://stackoverflow.com/comment/83220475
has text: I'm accepting this because the key insight is to have the function that populates the UI destroy any existing widgets first
type: AnswerComment
comment on: http://stackoverflow.com/a/48121168
score: 0
type: Comment

http://stackoverflow.com/comment/83228337
type: Comment
has text: @ateesdalejr That did not work. Why is sending a reply necessary to receive another byte?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48121053

http://stackoverflow.com/q/48031599
has comment: http://stackoverflow.com/comment/83081399
has body: I'm novice to programming and learning python3. Recently I'm trying to make cryptocurrency trading system using binance's api. Here's the api document. The logic and explanation about timestamp in the document is as follows : Timestamp, to be sent which should be the millisecond timestamp of when the request was created and sent. if (timestamp < serverTime && (serverTime - timestamp) <= recvWindow) { // process request } else { // reject request } According to this logic, the time I sent the request should be less than the time on the server. The problem is that I have not passed this logic. When I call time.time() and server time using this code, import requests import simplejson as json import time base_url = "https://api.binance.com" servertime_endpoint="/api/v1/time" url = base_url + servertime_endpoint t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) print(int(t)-result["serverTime"]) time.time() is bigger than server time so that I get return from last sentence with positive value. What should I do?
has answer: http://stackoverflow.com/a/48089613
score: 0
has comment: http://stackoverflow.com/comment/83034071
tagged with: api
has comment: http://stackoverflow.com/comment/83081343
answer count: 1
has comment: http://stackoverflow.com/comment/83081284
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83034044
accepted answer: http://stackoverflow.com/a/48089613
tagged with: time
has comment: http://stackoverflow.com/comment/83071735
tagged with: python
has comment: http://stackoverflow.com/comment/83033399
tagged with: trading
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83034181
linked to: http://stackoverflow.com/q/1938048
has comment: http://stackoverflow.com/comment/83033405
type: Question
has title: My time.time() is bigger than server time
has comment: http://stackoverflow.com/comment/83051065

http://stackoverflow.com/comment/83302030
has text: There will always be a loop, whether it's explicit like in your code or hidden inside a `np.sum()` call. Your code looks fine to me, is there any good reason why you are not happy with it?
comment on: http://stackoverflow.com/q/48161256
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48101317
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48101040
has comment: http://stackoverflow.com/comment/83181883
answers question: http://stackoverflow.com/q/48101040
has body: You can use moveaxis to move the to split axis all the way to the left and then use sequence unpacking: x,y,z = np.moveaxis(arr, -1, 0)
type: Answer
has comment: http://stackoverflow.com/comment/83182595
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/83046494
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162232/discussion-between---and-eyllanesc).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48037355
type: Comment

http://stackoverflow.com/q/48104097
has answer: http://stackoverflow.com/a/48104219
has answer: http://stackoverflow.com/a/67562861
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/33870538
has comment: http://stackoverflow.com/comment/94685626
upvote count: 20
possible better answer: http://stackoverflow.com/a/48104219
tagged with: base64
has answer: http://stackoverflow.com/a/48104215
answer count: 6
score: 19
tagged with: http://stackoverflow.com/tag/pdf
has answer: http://stackoverflow.com/a/48104374
has answer: http://stackoverflow.com/a/76403330
favorite count: 0
has comment: http://stackoverflow.com/comment/94685505
has title: How to convert a PDF from base64 string to a file?
accepted answer: http://stackoverflow.com/a/48104215
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75684406
tagged with: file-writing
has body: I have a PDF as a base64 string and I need to write it to file using Python. I tried this: import base64 base64String = "data:application/pdf;base64,JVBERi0xLjQKJeHp69MKMSAwIG9iago8PC9Qcm9kdWNlciAoU2tpYS9..." with open('temp.pdf', 'wb') as theFile: theFile.write(base64.b64decode(base64String)) But it didn't create a valid PDF file. What am I missing?

recurrent-neural-network
tags question: http://stackoverflow.com/q/48158113
tags question: http://stackoverflow.com/q/48060415
tags question: http://stackoverflow.com/q/48042012
tags question: http://stackoverflow.com/q/48040685
type: Tag
tags question: http://stackoverflow.com/q/48028385
tags question: http://stackoverflow.com/q/48041000
tags question: http://stackoverflow.com/q/48152730
tags question: http://stackoverflow.com/q/48060041
tags question: http://stackoverflow.com/q/48015101
tags question: http://stackoverflow.com/q/48155026
tags question: http://stackoverflow.com/q/48137219
tags question: http://stackoverflow.com/q/48084798
tag name: recurrent-neural-network

http://stackoverflow.com/comment/83221208
score: 0
type: Comment
type: QuestionComment
has text: What fields? It works on your example DataFrames https://imgur.com/a/5SvEO
comment on: http://stackoverflow.com/q/48122105

http://stackoverflow.com/a/48156884
upvote count: 1
answers question: http://stackoverflow.com/q/48123591
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48123591
has comment: http://stackoverflow.com/comment/83294040
has body: Key name assigned with load_from argument kicks in when the field’s name is not found on the input, your method will work if original key get removed: data[outer + '__' + inner] = data[outer][inner] del data[outer] but, why not change the value of the nested field directly, then load_from=... become unnecessary: data[outer] = data[outer][inner]

http://stackoverflow.com/a/48247856
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48127226
has body: As @stranac mentioned in the comment: The name of the method is start_requests you can revise you code and try again
answers question: http://stackoverflow.com/q/48127226
score: 0

http://stackoverflow.com/comment/83281801
type: QuestionComment
comment on: http://stackoverflow.com/q/48150016
has text: You cannot do this with a high-level socket connection. However, it is possible if you access the Hardware tab. The Client connection will close after receiving the first packet, and you will send the second data into space.
score: 0
type: Comment

http://stackoverflow.com/a/48133522
has body: You are getting an error because Python doesn't know where to find the the function printcommand. First import the file Main.py so you can use it in GUI.py. import Main.py The problem now is that the method printcommand is an instance method meaning you need to have an object to call it. To accomplish this. Create an instance of the GUIFunctions class and reference the method using the object guifuncs = Main.GUIFunctions(master) command = guifuncs.printcommand Note: you must prefix references to Main.py with Main with the import syntax used above. I hope this helps you and if you have any further questions please feel free to post a comment below!
type: Answer
answers question: http://stackoverflow.com/q/48133372
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/comment/83041871
comment on: http://stackoverflow.com/q/48035389
type: Comment
type: QuestionComment
has text: Maybe - https://docs.python.org/3/library/traceback.html
score: 0

http://stackoverflow.com/a/72661104
upvote count: 2
score: 2
has body: Note that the above answers do not give you the values in the range you are asking. Here I present an alternative function that may be easy to follow and gives you the result in the range you are asking. def normalize(x, newRange=(0, 1)): #x is an array. Default range is between zero and one xmin, xmax = np.min(x), np.max(x) #get max and min from input array norm = (x - xmin)/(xmax - xmin) # scale between zero and one if newRange == (0, 1): return(norm) # wanted range is the same as norm elif newRange != (0, 1): return norm * (newRange[1] - newRange[0]) + newRange[0] #scale to a different range. #add other conditions here. For example, an error message Aplying our new function to your problem x = np.array([0.92323, 0.7232322, 0.93832, 0.4344433]) #your input vector must be an array normalize(x, newRange=(0.25, 0.5)) #set your range as a python tuple #array([0.49251305, 0.39328352, 0.5 , 0.25 ]) #note that the new values have a maximum value of 0.5 (the third entry) and minimum of 0.25 (the last value).
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48109228

http://stackoverflow.com/comment/83037190
score: 0
type: AnswerComment
type: Comment
has text: @aguy good luck with that, being a Machine Learning enthusiast myself i'm inclined to tell you that in case you need help in some Machine Learning projects, you can contact me on rayhane.mamah@gmail.com, it can never hurt to get some work done
comment on: http://stackoverflow.com/a/48029865

http://stackoverflow.com/comment/83159494
score: 0
type: Comment
type: QuestionComment
has text: Yes, you can pack your installation of Firefox with your job. You can go through the trouble of configuring Firefox (e.g. where to load the profile?) yourself or download a pre-configured *portable* Firefox installation :) I'm not sure about the geckodriver, sorry!
comment on: http://stackoverflow.com/q/48083634

python
tags question: http://stackoverflow.com/q/48045590
tags question: http://stackoverflow.com/q/48139582
tags question: http://stackoverflow.com/q/48046342
tags question: http://stackoverflow.com/q/48102585
tags question: http://stackoverflow.com/q/48167257
tags question: http://stackoverflow.com/q/48032644
tags question: http://stackoverflow.com/q/48143345
tags question: http://stackoverflow.com/q/48109011
tags question: http://stackoverflow.com/q/48104635
tags question: http://stackoverflow.com/q/48123861
tags question: http://stackoverflow.com/q/48165129
tags question: http://stackoverflow.com/q/48046378
tags question: http://stackoverflow.com/q/48151172
tags question: http://stackoverflow.com/q/48102142
tags question: http://stackoverflow.com/q/48138557
tags question: http://stackoverflow.com/q/48069508
tags question: http://stackoverflow.com/q/48088886
tags question: http://stackoverflow.com/q/48083138
tags question: http://stackoverflow.com/q/48054082
tags question: http://stackoverflow.com/q/48161175
tags question: http://stackoverflow.com/q/48040529
tags question: http://stackoverflow.com/q/48161447
tags question: http://stackoverflow.com/q/48089391
tags question: http://stackoverflow.com/q/48157208
tags question: http://stackoverflow.com/q/48119212
tags question: http://stackoverflow.com/q/48034478
tags question: http://stackoverflow.com/q/48131242
tags question: http://stackoverflow.com/q/48027171
tags question: http://stackoverflow.com/q/48122170
tags question: http://stackoverflow.com/q/48030298
tags question: http://stackoverflow.com/q/48102255
tags question: http://stackoverflow.com/q/48063266
tags question: http://stackoverflow.com/q/48094789
tags question: http://stackoverflow.com/q/48159303
tags question: http://stackoverflow.com/q/48068607
tags question: http://stackoverflow.com/q/48064058
tags question: http://stackoverflow.com/q/48132494
tags question: http://stackoverflow.com/q/48042137
tags question: http://stackoverflow.com/q/48168073
tags question: http://stackoverflow.com/q/48146904
tags question: http://stackoverflow.com/q/48088582
tags question: http://stackoverflow.com/q/48065269
tags question: http://stackoverflow.com/q/48125304
tags question: http://stackoverflow.com/q/48160827
tags question: http://stackoverflow.com/q/48056574
tags question: http://stackoverflow.com/q/48023061
tags question: http://stackoverflow.com/q/48082264
tags question: http://stackoverflow.com/q/48057991
tags question: http://stackoverflow.com/q/48017878
tags question: http://stackoverflow.com/q/48059700
tags question: http://stackoverflow.com/q/48054604
tags question: http://stackoverflow.com/q/48015117
tags question: http://stackoverflow.com/q/48051104
tags question: http://stackoverflow.com/q/48038526
tags question: http://stackoverflow.com/q/48121053
tags question: http://stackoverflow.com/q/48065878
tags question: http://stackoverflow.com/q/48133520
tags question: http://stackoverflow.com/q/48134865
tags question: http://stackoverflow.com/q/48042637
tags question: http://stackoverflow.com/q/48142757
tags question: http://stackoverflow.com/q/48038577
tags question: http://stackoverflow.com/q/48030217
tags question: http://stackoverflow.com/q/48111245
tags question: http://stackoverflow.com/q/48043758
tags question: http://stackoverflow.com/q/48030474
tags question: http://stackoverflow.com/q/48038335
tags question: http://stackoverflow.com/q/48089545
tags question: http://stackoverflow.com/q/48141135
tags question: http://stackoverflow.com/q/48158178
tags question: http://stackoverflow.com/q/48046421
tags question: http://stackoverflow.com/q/48030787
tags question: http://stackoverflow.com/q/48154857
tags question: http://stackoverflow.com/q/48085269
tags question: http://stackoverflow.com/q/48161508
tags question: http://stackoverflow.com/q/48026203
tags question: http://stackoverflow.com/q/48142859
tags question: http://stackoverflow.com/q/48081783
tags question: http://stackoverflow.com/q/48158017
tags question: http://stackoverflow.com/q/48100714
tags question: http://stackoverflow.com/q/48019360

http://stackoverflow.com/a/48157044
type: Answer
answers question: http://stackoverflow.com/q/48156771
has comment: http://stackoverflow.com/comment/83293252
score: 0
has body: The error is in the file formatting; somehow there's an extra empty line after each valid line in the text file, despite that not visually appearing to be the case. There must be extra new line characters or something. Thank you all.

http://stackoverflow.com/a/48099419
answers question: http://stackoverflow.com/q/48090043
type: Answer
has body: You need to convert the dates first into a Python datetime object. This can then be converted into a matplotlib number. With this you can then tell matplotlib to add ticks based on year or month changes: from datetime import datetime import matplotlib import matplotlib.pyplot as plt import urllib as u import numpy as np import csv stock_price_url = 'https://pythonprogramming.net/yahoo_finance_replacement' date = [] high = [] text = u.request.urlopen(stock_price_url).read().decode() with open('nw.csv', 'w') as f_nw: f_nw.write(text) with open('nw.csv', 'r', newline='') as f_nw: csv_nw = csv.reader(f_nw) header = next(csv_nw) for row in csv_nw: date.append(matplotlib.dates.date2num(datetime.strptime(row[0], '%Y-%m-%d'))) high.append(row[2]) ax = plt.gca() #ax.xaxis.set_minor_locator(matplotlib.dates.MonthLocator([1, 7])) #ax.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter('%b')) ax.xaxis.set_major_locator(matplotlib.dates.YearLocator()) ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y')) #ax.tick_params(pad=20) plt.plot(date, high, linewidth=0.5) plt.show() This would give you just the years: Or if you uncomment the minor locator/formatter you would get: Note: You do not need to close a file if you are opening it with a with block. The script assumes you are using Python 3.x. To skip the header just read it in using next() before iterating over the rows in your for loop.
score: 17
upvote count: 17
downvote count: 0
has comment: http://stackoverflow.com/comment/83181243

http://stackoverflow.com/comment/83239039
has text: @Ranny, please post some reproducible data next time. You can do it easily with `df.to_dict()`. Thanks!
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48130703
type: QuestionComment

numpy
tags question: http://stackoverflow.com/q/48131371
tags question: http://stackoverflow.com/q/48080359
tags question: http://stackoverflow.com/q/48023385
tags question: http://stackoverflow.com/q/48039293
tags question: http://stackoverflow.com/q/48032299
tags question: http://stackoverflow.com/q/48116700
tags question: http://stackoverflow.com/q/48091094
tags question: http://stackoverflow.com/q/48118436
tags question: http://stackoverflow.com/q/48101388
tags question: http://stackoverflow.com/q/48039409
tags question: http://stackoverflow.com/q/48139621
tags question: http://stackoverflow.com/q/48133358
tags question: http://stackoverflow.com/q/48072007
tags question: http://stackoverflow.com/q/48139582
tags question: http://stackoverflow.com/q/48167257
tags question: http://stackoverflow.com/q/48038577
tags question: http://stackoverflow.com/q/48137976
tags question: http://stackoverflow.com/q/48167838
tags question: http://stackoverflow.com/q/48161256
tags question: http://stackoverflow.com/q/48116496
tags question: http://stackoverflow.com/q/48115430
tags question: http://stackoverflow.com/q/48020122
tags question: http://stackoverflow.com/q/48099479
tags question: http://stackoverflow.com/q/48037418
tags question: http://stackoverflow.com/q/48165212
tags question: http://stackoverflow.com/q/48099343
tags question: http://stackoverflow.com/q/48078267
tags question: http://stackoverflow.com/q/48053572
tags question: http://stackoverflow.com/q/48036473
tags question: http://stackoverflow.com/q/48079421
tags question: http://stackoverflow.com/q/48026172
tags question: http://stackoverflow.com/q/48053016
tags question: http://stackoverflow.com/q/48094341
tags question: http://stackoverflow.com/q/48116430
tags question: http://stackoverflow.com/q/48026056
tags question: http://stackoverflow.com/q/48097068
tags question: http://stackoverflow.com/q/48146072
tags question: http://stackoverflow.com/q/48163488
tags question: http://stackoverflow.com/q/48129237
tags question: http://stackoverflow.com/q/48099546
tags question: http://stackoverflow.com/q/48138475
tags question: http://stackoverflow.com/q/48158654
tags question: http://stackoverflow.com/q/48070143
tags question: http://stackoverflow.com/q/48081672
tags question: http://stackoverflow.com/q/48088516
tags question: http://stackoverflow.com/q/48018417
tags question: http://stackoverflow.com/q/48097941
tags question: http://stackoverflow.com/q/48132740
tags question: http://stackoverflow.com/q/48071144
tags question: http://stackoverflow.com/q/48156059
tags question: http://stackoverflow.com/q/48100341
tags question: http://stackoverflow.com/q/48051192
tags question: http://stackoverflow.com/q/48133518
tags question: http://stackoverflow.com/q/48015770
tags question: http://stackoverflow.com/q/48069439
tags question: http://stackoverflow.com/q/48103343
tags question: http://stackoverflow.com/q/48158746
tags question: http://stackoverflow.com/q/48138757
tags question: http://stackoverflow.com/q/48057845
tags question: http://stackoverflow.com/q/48125575
tags question: http://stackoverflow.com/q/48159562
tags question: http://stackoverflow.com/q/48081412
tags question: http://stackoverflow.com/q/48127217
tags question: http://stackoverflow.com/q/48137451
tags question: http://stackoverflow.com/q/48054531
tags question: http://stackoverflow.com/q/48143177
tags question: http://stackoverflow.com/q/48061769
tags question: http://stackoverflow.com/q/48170398
tags question: http://stackoverflow.com/q/48081912
tags question: http://stackoverflow.com/q/48170703
tags question: http://stackoverflow.com/q/48069701
tags question: http://stackoverflow.com/q/48143533
tags question: http://stackoverflow.com/q/48026452
tags question: http://stackoverflow.com/q/48154925
tags question: http://stackoverflow.com/q/48018514
tags question: http://stackoverflow.com/q/48039983
tags question: http://stackoverflow.com/q/48117288
tags question: http://stackoverflow.com/q/48085507
tags question: http://stackoverflow.com/q/48038422
tags question: http://stackoverflow.com/q/48088886

http://stackoverflow.com/q/48073923
score: 3
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48074114
has answer: http://stackoverflow.com/a/48074307
possible better answer: http://stackoverflow.com/a/48074307
answer count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48074114
has title: Django allauth custom template not hashing passwords
has body: I am using my own custom view and inheriting from SignupView (in from allauth.account.views import SignupView) I am also using my own forms.py to pass on to my custom view. It is signing up the user just fine, but one thing it's not doing is hashing the passwords. It's saving the passwords for the user the way it is. How can I make it so that the passwords are stored in the table as a hash? forms.py from .models import User from django import forms class RegisterForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'placeholder': 'Username:'})) email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'placeholder': 'Email:'})) password = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password:'})) views.py from allauth.account.views import SignupView from .forms import RegisterForm class RegisterView(SignupView): form_class = RegisterForm template_name = 'oauth/auth_form.html' project urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('oauth.urls')), //app name I created where my custom sign up view is url(r'^profiles/', include('profiles.urls')), url(r'^accounts/', include('allauth.urls')), ]
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83179702
has text: Thank you for pointing this out, i thought `and or` condition simply works like `? :` in other language, but it doesn't.
type: Comment
comment on: http://stackoverflow.com/a/48102186
score: 0
type: AnswerComment

http://stackoverflow.com/q/48067726
has comment: http://stackoverflow.com/comment/83112176
has body: I have used sklearn in python to read an excel sheet and predict a group names based on its description. The next step i want to take is grouping similar groups. I am not sure which method will best satisfy what i'm attempting to do. from __future__ import print_function from sklearn.datasets import load_iris import pandas as pd from sklearn.neighbors import KNeighborsClassifier from sklearn.feature_extraction.text import CountVectorizer from sklearn.cross_validation import train_test_split from sklearn.naive_bayes import MultinomialNB from sklearn import metrics import numpy as np path = 'data/mydata.csv' exp = pd.read_csv(path, names=['group_name', 'description']) X = exp.description y = exp.group_name fixed_X = X[pd.notnull(X)] fixed_y = y[pd.notnull(y)] vect = CountVectorizer(token_pattern=u'(?u)\\b\\w\\w+\\b') nb = MultinomialNB() X_train, X_test, y_train, y_test = train_test_split(fixed_X, fixed_y, random_state=1) X_train_dtm = vect.fit_transform(X_train) X_test_dtm = vect.transform(X_test) nb.fit(X_train_dtm, y_train) y_pred_class = nb.predict(X_test_dtm) print(metrics.classification_report(y_test, y_pred_class)) This prints the accuracy of the predicted groups, which is what i want. How do i group similar 'group_names' based on the data and predictions provided? Desired output(based on predictions and data behind it) if there are 10 groups total group 1: [group_name1, group_name5,group_name10] group 2: [group_name2, group_name4] group 3: [group_name3, group_name6, group_name7, group_name9] group 4: [group_name10] (the number of groups wont matter shouldn't matter, i just want the correct group_names, with similar group_names all in one group. or a visual model which shows a clustering of all group names
tagged with: pandas
has comment: http://stackoverflow.com/comment/83112605
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/83112261
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83111973
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/83112546
has comment: http://stackoverflow.com/comment/83115800
has comment: http://stackoverflow.com/comment/83112160
type: Question
has title: python classify predictions

http://stackoverflow.com/comment/83034866
has text: @syam Python just doesn't work this way. Are you thinking of a different programming language that does? The fact is, practically every mainstream programming language treats variables (and attributes) as boxes in which you put computed values which are NEVER "dynamically reassigned"! That said, Python, like other languages, gives you language mechanisms to give you exactly that appearance. In Python's case, it is `@property`.
comment on: http://stackoverflow.com/a/48032331
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/a/48074894
answers question: http://stackoverflow.com/q/48074834
upvote count: 6
has comment: http://stackoverflow.com/comment/83124380
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83123968
score: 6
type: Answer
downvote count: 0
has body: your view is totally wrong, use this def login_page(request): form = LoginForm(request.POST or None) context = { 'form': form } if request.method == 'POST': if form.is_valid(): print(form.cleaned_data) username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("/") else: print("Error") else: print('form not valid') return render(request, "auth/login.html", context) and html to {% csrf_token %} {{ form }} Submit
accepted answer of: http://stackoverflow.com/q/48074834

http://stackoverflow.com/a/48142551
type: Answer
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83263642
answers question: http://stackoverflow.com/q/48142516
has comment: http://stackoverflow.com/comment/83263368
score: 0
has body: What you can do is use defaultdict from collections import defaultdict d=defaultdict(list) #this will return a empty list everytime a new key is used or if key exists it will appendt the value to the list d[venue_name]=a Example: &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; city_list = [('TX','Austin'), ('TX','Houston'), ('NY','Albany'), ('NY', 'Syracuse'), ('NY', 'Buffalo'), ('NY', 'Rochester'), ('TX', 'Dallas'), ('CA','Sacramento'), ('CA', 'Palo Alto'), ('GA', 'Atlanta')] &gt;&gt;&gt; &gt;&gt;&gt; cities_by_state = defaultdict(list) &gt;&gt;&gt; for state, city in city_list: ... cities_by_state[state].append(city) ... for state, cities in cities_by_state.iteritems(): ... print state, ', '.join(cities) ... NY Albany, Syracuse, Buffalo, Rochester CA Sacramento, Palo Alto GA Atlanta TX Austin, Houston, Dallas
has comment: http://stackoverflow.com/comment/83263407

http://stackoverflow.com/comment/83028559
type: QuestionComment
comment on: http://stackoverflow.com/q/48029204
score: 1
has text: The return value is `1` when you hit `j==1`, but be aware than in the `else` you're multiplying that by `j`. There's a video tutorial about it that I was watching just yesterday (for Java, but the general idea still stands) https://youtu.be/ozmE8G6YKww
type: Comment

http://stackoverflow.com/comment/83211203
score: 0
has text: thanks for that, however if sql query returns only 1 row I feel its bad practice to loop through rows... as there is only and always 1 row
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48116662

http://stackoverflow.com/comment/83296976
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48157533
has text: @OPP, sorry, I thought that's what your requirements actually were. It's deleting the output file contents before writing the new output (otherwise it would add more different contents to the output file each time you run it). Is the output file empty when you run the script I referred to?
score: 0

http://stackoverflow.com/q/48083105
downvote count: 0
accepted answer: http://stackoverflow.com/a/48087467
has title: How to add data via directories for training images
has answer: http://stackoverflow.com/a/48087467
tagged with: keras
possible better answer: http://stackoverflow.com/a/48090296
favorite count: 0
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48090296
tagged with: git
has comment: http://stackoverflow.com/comment/83140992
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83157008
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83144652
answer count: 2
has body: I have been going through git repository by flyyufelix "https://github.com/flyyufelix/cnn_finetune" to fine tune an inception v3 network I want to train network to detect a disease so I have 2 set of images one with disease and without disease. The git says X_train, Y_train, X_valid, Y_valid = load_data() he loads the cifar dataset ,The git asks us to create our own load_data() function.The author has the code as below import cv2 import numpy as np from keras.datasets import cifar10 from keras import backend as K from keras.utils import np_utils nb_train_samples = 3000 # 3000 training samples nb_valid_samples = 100 # 100 validation samples num_classes = 10 def load_cifar10_data(img_rows, img_cols): # Load cifar10 training and validation sets (X_train, Y_train), (X_valid, Y_valid) = cifar10.load_data() # Resize trainging images if K.image_dim_ordering() == 'th': X_train = np.array([cv2.resize(img.transpose(1,2,0), (img_rows,img_cols)).transpose(2,0,1) for img in X_train[:nb_train_samples,:,:,:]]) X_valid = np.array([cv2.resize(img.transpose(1,2,0), (img_rows,img_cols)).transpose(2,0,1) for img in X_valid[:nb_valid_samples,:,:,:]]) else: X_train = np.array([cv2.resize(img, (img_rows,img_cols)) for img in X_train[:nb_train_samples,:,:,:]]) X_valid = np.array([cv2.resize(img, (img_rows,img_cols)) for img in X_valid[:nb_valid_samples,:,:,:]]) # Transform targets to keras compatible format Y_train = np_utils.to_categorical(Y_train[:nb_train_samples], num_classes) Y_valid = np_utils.to_categorical(Y_valid[:nb_valid_samples],num_classes) return X_train, Y_train, X_valid, Y_valid can i know how to generate a function which loads data X_train, Y_train, X_valid, Y_valid = load_data() when i have directries in pc

http://stackoverflow.com/comment/83292640
score: 0
has text: @PeterWood i dont need to define type i could deal with it later but is there a way to define the length of each tuple argument past to the fucntion to be 3 exactly?
type: QuestionComment
comment on: http://stackoverflow.com/q/48156691
type: Comment

http://stackoverflow.com/a/48079944
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/83133998
upvote count: 6
has comment: http://stackoverflow.com/comment/83133938
answers question: http://stackoverflow.com/q/48079856
has comment: http://stackoverflow.com/comment/83133870
accepted answer of: http://stackoverflow.com/q/48079856
has comment: http://stackoverflow.com/comment/83134050
type: AcceptedAnswer
downvote count: 0
has body: Astype int of boolean will give you want you want i.e arr = np.array([[[-1024, -1024, -1024, 0, -1024, -1024, -1024], [-1024, -1024, -1024, 150, -1024, -1024, -1024], [-1024, -1024, -1024,300, -1024, -1024, -1024]]]) (arr&gt;100).astype(int) array([[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0]]])
has comment: http://stackoverflow.com/comment/83134119

http://stackoverflow.com/q/48074770
accepted answer: http://stackoverflow.com/a/48074808
favorite count: 0
has comment: http://stackoverflow.com/comment/83123302
has comment: http://stackoverflow.com/comment/83124468
score: -3
tagged with: python
has body: As far as I can tell, raise would function just as well if it were a function, rather than a statement. A distinctive feature of statements seems to me to be that their arguments aren't interpreted as "code". E.g. import math doesn't require you to have defined math, and a similar function would require a string argument: import("math"). Another is that, if an argument is to be interpreted as code, it's not necessarily evaluated. E.g. assert testbool, myfunc() will only call myfunc() if testbool is True. Lastly, I imagine that using a statement rather than a function avoids a bit of overhead due to calling a function. None of these advantages apply to raise: its argument always already has to be defined, and there is no situation in which the raise statement is executed, but its argument is not evaluated. Lastly, I imagine the overhead of calling a function to be insignificant compared to all the other book-keeping involved in raising an exception. At the same time, having raise as a statement comes at the cost of not being able to use the word raise as the name of a variable, which would see plenty of uses, considering it's a decently common English verb. (I can raise a platform, raise a number by 1, ...) I also imagine having fewer statements would simplify compilers. So why is raise a statement?
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/83124544
type: Question
downvote count: 5
has comment: http://stackoverflow.com/comment/83123943
has title: Why is "raise" a statement, rather than a function?
answer count: 1
has answer: http://stackoverflow.com/a/48074808

http://stackoverflow.com/comment/83263271
comment on: http://stackoverflow.com/a/48142494
type: AnswerComment
score: 0
type: Comment
has text: @PMende why wouldnt it be?

http://stackoverflow.com/a/48022713
type: Answer
accepted answer of: http://stackoverflow.com/q/48022124
answers question: http://stackoverflow.com/q/48022124
score: 8
type: AcceptedAnswer
downvote count: 0
upvote count: 8
has body: Your code has 2 errors: the first is caused by a bad programming practice: you should not call the variables with names that you used with other variables, functions or classes. In your case flags is the name of the method and therefore you should not use it in the name of the variable: def flags(self, index): fl = super(self.__class__,self).flags(index) fl |= Qt.ItemIsEditable fl |= Qt.ItemIsSelectable fl |= Qt.ItemIsEnabled fl |= Qt.ItemIsDragEnabled fl |= Qt.ItemIsDropEnabled return fl The second error is caused because you are not using the proper method to access and assign the data in pandas, this must be done through the iloc method. Another problem is that you are using a valid method for PyQt4 to notify the changes, you must use the new syntax plus the dataChanged signal to add new fields in Qt5 as you can see in the docs: def setData(self, index, value, role=Qt.EditRole): if index.isValid(): row = index.row() col = index.column() self._data.iloc[row][col] = float(value) self.dataChanged.emit(index, index, (Qt.DisplayRole, )) return True return False Plus: I have also previously implemented a class that creates a model using pandas as you can see in the question How to display a Pandas data frame with PyQt5
has comment: http://stackoverflow.com/comment/83014739

http://stackoverflow.com/q/48122796
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48122878
tagged with: python
tagged with: frame
has body: I have a problem wherein I cannot create multiple distinct frames within a given frame. This is just a small chunk of my overall application but basically I've separated different Frames into classes and i call those classes depending on the situation. What I am looking for is how to create 2 or more frames within this frame class. As of right now, the distinct frames aren't being created so when place them in a grid they overlap and replace each other. (i.e. frame2.label overlaps with frame1.label) class MainPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) #First frame inside the current MainPage Window Frame frame1 = Frame(self, bg = "red") frame1.grid(row = 0, column = 0, sticky = W) frame1.label = tk.Label(self, text="Main Page", font=SMALL_FONT) frame1.label.grid(row = 0, column = 0, sticky = W) itemScanNumber = StringVar() frame1.EntryBox = ttk.Entry(self, textvariable = itemScanNumber) frame1.EntryBox.grid(row = 0, column = 1, sticky = W) print(itemScanNumber.get()) def printNumber(): print("Your Number: " + itemScanNumber.get()) return frame1.button = ttk.Button(self, text = "CLICK ME FOR SCAN NUMBER!", command = printNumber) frame1.button.grid(row = 0, column = 2, sticky = W) frame1.button1 = ttk.Button(self, text = "CLICK ME!", command = lambda: controller.show_frame(MasterFilePage)) frame1.button1.grid(row = 0, column = 3, sticky = W) #Second frame inside the current MainPage Window Frame frame2 = Frame(self, bg = "blue") frame2.grid(row = 1, column = 0, sticky = W) frame2.label = tk.Label(self, text="Main Page2", font=SMALL_FONT) frame2.label.grid(row = 0, column = 0, sticky = W)
accepted answer: http://stackoverflow.com/a/48122878
tagged with: python-3.x
tagged with: gridview
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83222509
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/83222437
has comment: http://stackoverflow.com/comment/83222501
has comment: http://stackoverflow.com/comment/83222464
has comment: http://stackoverflow.com/comment/83222474
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Tkinter: Creating multiple frames inside a frame class

http://stackoverflow.com/comment/83395120
has text: Oh. I've just updated my pandas version, and the error you mentioned occurred ! . Something changed between 20.1 and the current version of pandas. Maybe it's a bug?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48161445

http://stackoverflow.com/comment/83315426
type: Comment
comment on: http://stackoverflow.com/q/48168011
score: 0
has text: The aim of this function is the return a list of prime numbers. When I rewrite the function in a list comprehension I receive a simple list of integer from 3 untill 99.
type: QuestionComment

http://stackoverflow.com/q/48123899
type: AnsweredQuestion
tagged with: webcam
has answer: http://stackoverflow.com/a/48457118
score: 0
has title: Capture webcam using ffmpeg-python library
has answer: http://stackoverflow.com/a/52015829
type: Question
possible better answer: http://stackoverflow.com/a/52015829
has body: Hi I'm attempting to capture a webcam stream with python using the ffmpeg-python wrapper library (https://github.com/kkroening/ffmpeg-python) I have a working ffmpeg command which is: ffmpeg -f v4l2 -video_size 352x288 -i /dev/video0 -vf "drawtext='fontfile=fonts/FreeSerif.ttf: text=%{pts} : \ x=(w-tw)/2: y=h-(2*lh): fontcolor=white: box=1: boxcolor=0x00000000@1'" -an -y -t 15 videotests/out_localtime8.mp4 This captures 15s of video in resolution 352x288, and writes a timestamp in the bottom centre of the video. To play with the ffmpeg-python library, I'm simply attempting to only get the drawtext filter working, here is my script: #!/usr/bin/env python import ffmpeg stream = ffmpeg.input('videotests/example.mov') stream = ffmpeg.filter_(stream,'drawtext',("fontfile=fonts/FreeSerif.ttf:text=%{pts}")) stream = ffmpeg.output(stream, 'videotests/output4.mp4') ffmpeg.run(stream) The error is [Parsed_drawtext_0 @ 0x561f59d494e0] Either text, a valid file or a timecode must be provided [AVFilterGraph @ 0x561f59d39080] Error initializing filter 'drawtext' with args 'fontfile\\\=fonts/FreeSerif.ttf\\\:text\\\=%{pts}' Error initializing complex filters. Invalid argument The above appears to at least reach ffmpeg but the format of the arguments is incorrect, how to correct them? Alternatively, when I attempting to split the argument to just pass one of them, I get a different error, as follows: stream = ffmpeg.filter_(stream,'drawtext',('text=%{pts}')) Error is subprocess.CalledProcessError: Command '['ffmpeg', '-i', 'videotests/example.mov', '-filter_complex', "[0]drawtext=(\\\\\\\\\\\\\\'text\\\\\\\\\\\\=%{pts}\\\\\\\\\\\\\\'\\,)[s0]", '-map', '[s0]', 'videotests/output4.mp4']' returned non-zero exit status 1. How come there are so many backslashes? Any advice on how to proceed please. Thank you
accepted answer: http://stackoverflow.com/a/48457118
answer count: 2
has comment: http://stackoverflow.com/comment/83906826
tagged with: ffmpeg
tagged with: python
tagged with: timestamp

http://stackoverflow.com/comment/83005680
score: 0
comment on: http://stackoverflow.com/q/48018162
has text: Even if your computer is locked the processes still runs in the background, untill unless your computer has been put on 'sleep mode' after some time. Check if sleep mode is on!!
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48078652
has body: food = [sh/2, sw/2] In Python 3, the division / operator always produces floating-point values. You should consider using the integer division operator, //.
type: Answer
answers question: http://stackoverflow.com/q/48078566
has comment: http://stackoverflow.com/comment/83132019
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/83131256
downvote count: 0

http://stackoverflow.com/q/48126592
has body: I have a database where I want to make a class called Employee, giving only the empid and getting the rest from a database. def__init__(self, empid): conn = sqlite3.connect("employee.db") cur = conn.cursor() self.empid = empid self.name = cur.execute("SELECT name FROM employees WHERE empid = " + str(empid)) self.bday = cur.execute("SELECT bday FROM employees WHERE empid = " + str(empid)) Only it does not return the values, rather an object when I print it. &lt;sqlite3.Cursor object at 0x104687c00&gt; &lt;sqlite3.Cursor object at 0x104687c00&gt; How do I resolve this?
tagged with: sqlite
tagged with: python
has answer: http://stackoverflow.com/a/48126646
favorite count: 0
type: UnansweredQuestion
upvote count: 1
score: 1
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48126629
has title: Python Class SQLite3 request returns object

python-3.x
tags question: http://stackoverflow.com/q/48103261
tags question: http://stackoverflow.com/q/48140693
tags question: http://stackoverflow.com/q/48083817
tags question: http://stackoverflow.com/q/48139078
tags question: http://stackoverflow.com/q/48147102
tags question: http://stackoverflow.com/q/48133357
tags question: http://stackoverflow.com/q/48106838
tags question: http://stackoverflow.com/q/48105094
tags question: http://stackoverflow.com/q/48150321
tags question: http://stackoverflow.com/q/48056684
tags question: http://stackoverflow.com/q/48026242
tags question: http://stackoverflow.com/q/48027064
tags question: http://stackoverflow.com/q/48113250
tags question: http://stackoverflow.com/q/48119587
tags question: http://stackoverflow.com/q/48040687
tags question: http://stackoverflow.com/q/48141367
tags question: http://stackoverflow.com/q/48025016
tags question: http://stackoverflow.com/q/48020132
tags question: http://stackoverflow.com/q/48079425
tags question: http://stackoverflow.com/q/48016351
tags question: http://stackoverflow.com/q/48071359
tags question: http://stackoverflow.com/q/48030675
tags question: http://stackoverflow.com/q/48127642
tags question: http://stackoverflow.com/q/48094844
tags question: http://stackoverflow.com/q/48066220
tags question: http://stackoverflow.com/q/48130901
tags question: http://stackoverflow.com/q/48044406
tags question: http://stackoverflow.com/q/48017614
tags question: http://stackoverflow.com/q/48118111
tags question: http://stackoverflow.com/q/48056052
tags question: http://stackoverflow.com/q/48154441
tags question: http://stackoverflow.com/q/48137037
tags question: http://stackoverflow.com/q/48027883
tags question: http://stackoverflow.com/q/48078267
tags question: http://stackoverflow.com/q/48086568
tags question: http://stackoverflow.com/q/48127811
tags question: http://stackoverflow.com/q/48038807
tags question: http://stackoverflow.com/q/48078445
tags question: http://stackoverflow.com/q/48104031
tags question: http://stackoverflow.com/q/48018820
tags question: http://stackoverflow.com/q/48121307
tags question: http://stackoverflow.com/q/48026559
tags question: http://stackoverflow.com/q/48105256
tags question: http://stackoverflow.com/q/48108800
tags question: http://stackoverflow.com/q/48152513
tags question: http://stackoverflow.com/q/48037634
tags question: http://stackoverflow.com/q/48045089
tags question: http://stackoverflow.com/q/48044405
tags question: http://stackoverflow.com/q/48116430
tags question: http://stackoverflow.com/q/48070697
tags question: http://stackoverflow.com/q/48126003
tags question: http://stackoverflow.com/q/48147254
tags question: http://stackoverflow.com/q/48170332
tags question: http://stackoverflow.com/q/48065685
tags question: http://stackoverflow.com/q/48084114
tags question: http://stackoverflow.com/q/48134680
tags question: http://stackoverflow.com/q/48124627
tags question: http://stackoverflow.com/q/48046350
tags question: http://stackoverflow.com/q/48136052
tags question: http://stackoverflow.com/q/48144150
tags question: http://stackoverflow.com/q/48067955
tags question: http://stackoverflow.com/q/48137974
tags question: http://stackoverflow.com/q/48014905
tags question: http://stackoverflow.com/q/48051158
tags question: http://stackoverflow.com/q/48051750
tags question: http://stackoverflow.com/q/48099546
tags question: http://stackoverflow.com/q/48084482
tags question: http://stackoverflow.com/q/48165636
tags question: http://stackoverflow.com/q/48138978
tags question: http://stackoverflow.com/q/48047254
tags question: http://stackoverflow.com/q/48088916
tags question: http://stackoverflow.com/q/48049474
tags question: http://stackoverflow.com/q/48132024
tags question: http://stackoverflow.com/q/48040985
tags question: http://stackoverflow.com/q/48050998
tags question: http://stackoverflow.com/q/48094096
tags question: http://stackoverflow.com/q/48077263
tags question: http://stackoverflow.com/q/48038148
tags question: http://stackoverflow.com/q/48114599
tags question: http://stackoverflow.com/q/48144610

http://stackoverflow.com/q/48026265
tagged with: mysql
type: Question
has title: flask mysqldb call a related table
tagged with: relational-database
tagged with: foreign-keys
has body: Flask-mysqldb Is there a way to call the related table without making a new query? if it's stored within the teacher object or something. So I have the id under 'teacher' and they have a relation in MySQL. {% for class1 in classes %} &lt;tr&gt; &lt;td&gt;{{class1.name}}&lt;/td&gt; &lt;td&gt;{{class1.code}}&lt;/td&gt; &lt;td&gt;{{class1.teacher}}&lt;/td&gt; Outputs: 'Classname', 'Classcode', 2 Something like &lt;td&gt;{{class1.teacher.name}}&lt;/td&gt;
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/q/48103157
tagged with: dictionary
has answer: http://stackoverflow.com/a/48103866
type: AnsweredQuestion
tagged with: mapping
has body: I have 1K files each having 1M lines. I have a dictionary that has around 2M keys and assigns them to 2M unique numbers from 1 to 2M. So The entries are like the following: dictionary = { 'hakuchita.mutikama' : 3, 'mitiputu.mitanata' : 4, 'pulasika.rukayota' : 1, 'luschi.rulu.pitana' : 2 } Each line of each file is one of these keys. And I want to replace all of these keys with their values. Here is my code: for filename in os.listdir('data'): with fileinput.FileInput('data/' + filename, inplace=True) as file: for line in file: print(dictionary[line[:-1]]) But I just ran my code and it's taking ages. What is the fastest way to get this done?
has comment: http://stackoverflow.com/comment/83182420
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48103274
has title: python - What is the fastest way to replace lines of a file from a dictionary?
tagged with: performance
has comment: http://stackoverflow.com/comment/83182166
accepted answer: http://stackoverflow.com/a/48103866
score: 0
has answer: http://stackoverflow.com/a/48103263
answer count: 3
favorite count: 0
possible better answer: http://stackoverflow.com/a/48103263
has comment: http://stackoverflow.com/comment/83182493
tagged with: io
has comment: http://stackoverflow.com/comment/83182265
tagged with: python

http://stackoverflow.com/comment/83108681
score: 0
type: AnswerComment
has text: i guess the easiest way, and probably safest way to, pass it via argument. as I already do some pre-processing on arguments anyway. thanks for the help
type: Comment
comment on: http://stackoverflow.com/a/48067485

http://stackoverflow.com/q/48088354
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83341129
has body: In this(https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/g3doc/guide.md) tutorial, a method of implementing custom gradient function is provided. @tfe.custom_gradient def log1pexp(x): e = tf.exp(x) def grad(dy): return dy * (1 - 1 / (1 + e)) return tf.log(1 + e), grad grad_log1pexp = tfe.gradients_function(log1pexp) # Works as before at x = 0. assert 0.5 == float(grad_log1pexp(0.)[0]) # But now works at x = 100 as well. assert 1.0 == float(grad_log1pexp(100.)[0]) I would like to implement a gradient function for matrix exponential, in which case the variable is a tensor. I tried the straight forward approach but it seems failed. My questions are: What's the meaning of dy here? How should these code be adopted to tensors?
tagged with: tensorflow
type: Question
upvote count: 4
downvote count: 0
score: 4
has title: How to implement custom gradient of a tensor using eager execution in TensorFlow
favorite count: 0
answer count: 0
tagged with: gradient-descent

http://stackoverflow.com/comment/83285927
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48153004
has text: I read first two blocks (7 & 9) -> create the dictionary -> pass that dictionary to the function to parse the data -> write output to a file. Yes, block 12 will also be read: Now, again read two other blocks (9 & 12) -> pass that dictionary ... until all the end of the file.
score: 0

http://stackoverflow.com/comment/83088038
comment on: http://stackoverflow.com/q/48054797
has text: what Python version you use ? do you use Windows ? did you try to display `£` on screen (Windows has problem to display `UTF-8` in console because it uses `CP125x` instead of `UTF-8` and then you can see `UnicodeEncodeError`). Did you try to encode string to `UTF-8` and write it in file ? Create minial working example with real url so we could see this page and test it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48136487
type: Question
has comment: http://stackoverflow.com/comment/83252321
score: 1
tagged with: udp
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Python: write data to CSV from UDP
has body: I used a socket library to receive data from UDP. Data which I send have 32bit width (4 Bytes), My code: with open(csvf, 'w', newline='', encoding='ascii') as csv_handle: csv_writer = csv.writer(csv_handle, delimiter=',') while(True): try: data,addr = s.recvfrom(buf) csv_writer.writerow(data) except (socket.timeout,KeyboardInterrupt, SystemExit): raise except Exception: traceback.print_exc() But in CSV file it presents 8 bit data. For example: I receive this UDP data in Wireshark: Desired CSV file output: 4,4,8,12,16, etc. Actual CSV file output: 0,0,0,4,0,0,0,4,0,0,0,8 32bit Unsigned Int, from memory (on FPGA) I read u32 value, these values create buffer, which I send via lwIP stack u32 data; ... data = XIo_In32(XPAR_AXI_BRAM_CTRL_0_S_AXI_BASEADDR+ptr); now, I see a second problem, there is also problem with litte/big endian, in Python I will need byteswap operation too
has answer: http://stackoverflow.com/a/48145135
upvote count: 1
has comment: http://stackoverflow.com/comment/83253792

http://stackoverflow.com/comment/83266086
comment on: http://stackoverflow.com/a/48143425
has text: You're leaking memory,too, the allocated bytestring is never released.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48118464
answer count: 3
has comment: http://stackoverflow.com/comment/83213458
tagged with: beautifulsoup
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83213423
has answer: http://stackoverflow.com/a/48119304
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/48118589
has body: I've written a script in python to collect some information from a webpage. I've written it using css selector in a very compact manner. My script is capable of fetching the data. However, the problem I'm facing is I can't use the css selector in my script to get the result side by side not in serially as I've used comma separated css selector to fetch two types of values all at once. If I'm unable to bring the clarity, please see the below example. The script I'm trying with: import requests from bs4 import BeautifulSoup res = requests.get("https://www.drugbank.ca/drugs/DB04789") soup = BeautifulSoup(res.text ,"lxml") items = '\n'.join([item.text for item in soup.select("dl &gt; dt , dl &gt; dd")]) print(items) Output I'm having: Name Accession Number Type 5-methyltetrahydrofolic acid DB04789 Small Molecule Output I wish to have: Name 5-methyltetrahydrofolic acid Accession Number DB04789 Type Small Molecule Is it possible to get the expected output applying some minor changes in the selector keeping it in a single line as I've tried above. Thanks for taking a look into it.
type: Question
has title: How to rectify my below script to get the output side by side?
has answer: http://stackoverflow.com/a/48118636
linked to: http://stackoverflow.com/q/48116316
score: 0
has comment: http://stackoverflow.com/comment/83214935

http://stackoverflow.com/comment/83121898
has text: And the full traceback. The code you've shown here would not show that error (because you obviously are passing arguments in the only use of `{% url %}`).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48073595

http://stackoverflow.com/comment/83322370
comment on: http://stackoverflow.com/q/48171436
type: Comment
type: QuestionComment
score: 2
has text: OK on my machine.

http://stackoverflow.com/comment/83008228
comment on: http://stackoverflow.com/a/48019029
type: Comment
has text: during my research, I coudn't find a way to prevent box change under your conditions. But my edited answear has a workaround to deal with maximum number of characters (given by you) avoiding the need to force the box size.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48029692
has answer: http://stackoverflow.com/a/48029865
type: Question
has body: import numpy as np def nonlin(x, deriv=False): if(deriv==True): return(x*(1-x)) return 1/(1+np.exp (-x)) x = np.array([[0,0,1], [0,1,1], [1,0,1], [1,1,1]]) y = np.array([[0], [1], [1], [0]]) #seed np.random.seed(1) #weights/synapses syn0 = 2*np.random.random((3,4)) - 1 syn1 = 2*np.random.random((4,1)) - 1 #training for j in range(60000): #layers (input, hidden, output) #not a class, just thinking of neurons this way #np.dot is mattrix multiplication L0 = x L1 = nonlin(np.dot(L0, syn0)) L2 = nonlin(np.dot(L1, syn1)) #backpropagation l2_error = y - L2 if (j % 10000) == 0: print ("Error:" + str(np.mean(np.abs(L2_error)))) #calculate deltas L2_delta = L2_error*nonlin(L2, deriv=True) L1_error = L2_delta.dot(syn1.T) L1_delta = L1_error * nonlin(L1, deriv=True) #update our synapses syn1 += L1.T.dot(L2_delta) syn0 += L0.T.dot(L1_delta) print ("output after training") print (L2) The error says: " L2 = nonlin(np.dot(L1, syn1)) TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'" This is suppose to be a very basic neural network. The portion where there is an error involves adding Layer1 and syn1 as a matrix. I am not sure if I need to change L2 to a float. This is my first time working with matrixes on python.
score: -1
has title: TypeError: unsupported operand type(s) for *: 'NoneType' and 'float' help FOR "nonlin np.dot"
tagged with: numpy
tagged with: nonlinear-functions
answer count: 2
tagged with: neural-network
has comment: http://stackoverflow.com/comment/83029608
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48029914
downvote count: 2
upvote count: 1

http://stackoverflow.com/comment/83075801
type: Comment
has text: thanks. I was trying to use remove() but I kept getting it wrong.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48051847

http://stackoverflow.com/comment/83167989
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48096203
has text: you can always use more complex list `badguys = [ [[800,100],150] ]` or dictionary `badguys = [ {"pos": [800,100], "health": 150} ]`.
score: 0

http://stackoverflow.com/q/48119073
favorite count: 0
has title: set output in sympy for 2**3 * 2**4 = 2**7 instead of 128
tagged with: python
has body: I would like to set the output in sympy for expression 2**3 * 2**4 = to 2**7 instead of 128. Is there an easy way?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48119158
has comment: http://stackoverflow.com/comment/83214605
type: Question
possible better answer: http://stackoverflow.com/a/48119110
has answer: http://stackoverflow.com/a/48119110
score: 4
accepted answer: http://stackoverflow.com/a/48119158
upvote count: 4
answer count: 2
tagged with: sympy
downvote count: 0

http://stackoverflow.com/a/48125669
has comment: http://stackoverflow.com/comment/83239164
type: Answer
has body: It does not seem you need inheritance here: class MyPlot(): def __init__(self, e_dat1, e_dat2): self.e_dat1 = e_dat1 self.e_dat2 = e_dat2 With e_dat1 and e_dat2 two E_Dat objects.
accepted answer of: http://stackoverflow.com/q/48124894
has comment: http://stackoverflow.com/comment/83239273
score: 0
answers question: http://stackoverflow.com/q/48124894
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83239146

http://stackoverflow.com/comment/83187804
has text: Casting it to an integer fixed the problem. Thanks everyone!
comment on: http://stackoverflow.com/q/48105967
score: 0
type: QuestionComment
type: Comment

flask
tags question: http://stackoverflow.com/q/48042926
tags question: http://stackoverflow.com/q/48125239
tags question: http://stackoverflow.com/q/48156310
tags question: http://stackoverflow.com/q/48140193
tags question: http://stackoverflow.com/q/48091964
tags question: http://stackoverflow.com/q/48096737
tags question: http://stackoverflow.com/q/48054922
tags question: http://stackoverflow.com/q/48062366
tags question: http://stackoverflow.com/q/48073635
tags question: http://stackoverflow.com/q/48024441
tags question: http://stackoverflow.com/q/48102986
tags question: http://stackoverflow.com/q/48064451
tags question: http://stackoverflow.com/q/48017866
tags question: http://stackoverflow.com/q/48082426
tags question: http://stackoverflow.com/q/48153448
tags question: http://stackoverflow.com/q/48143581
tags question: http://stackoverflow.com/q/48091060
tags question: http://stackoverflow.com/q/48030850
tags question: http://stackoverflow.com/q/48015950
tags question: http://stackoverflow.com/q/48019145
tags question: http://stackoverflow.com/q/48112466
tags question: http://stackoverflow.com/q/48090648
tags question: http://stackoverflow.com/q/48029111
tags question: http://stackoverflow.com/q/48087552
tags question: http://stackoverflow.com/q/48039515
tags question: http://stackoverflow.com/q/48056297
tags question: http://stackoverflow.com/q/48037337
tags question: http://stackoverflow.com/q/48041147
tags question: http://stackoverflow.com/q/48098813
tags question: http://stackoverflow.com/q/48048623
tags question: http://stackoverflow.com/q/48023625
tags question: http://stackoverflow.com/q/48060556
tags question: http://stackoverflow.com/q/48027332
tags question: http://stackoverflow.com/q/48129537
tags question: http://stackoverflow.com/q/48158628
tags question: http://stackoverflow.com/q/48157699
tags question: http://stackoverflow.com/q/48046074
tags question: http://stackoverflow.com/q/48021748
tags question: http://stackoverflow.com/q/48167243
tags question: http://stackoverflow.com/q/48047118
tags question: http://stackoverflow.com/q/48021238
tags question: http://stackoverflow.com/q/48099019
tags question: http://stackoverflow.com/q/48122283
tags question: http://stackoverflow.com/q/48031463
tags question: http://stackoverflow.com/q/48023363
type: Tag
tags question: http://stackoverflow.com/q/48105503
tags question: http://stackoverflow.com/q/48154467
tags question: http://stackoverflow.com/q/48148131
tags question: http://stackoverflow.com/q/48058185
tags question: http://stackoverflow.com/q/48070612
tags question: http://stackoverflow.com/q/48017347
tags question: http://stackoverflow.com/q/48162626
tags question: http://stackoverflow.com/q/48055135
tags question: http://stackoverflow.com/q/48015074
tags question: http://stackoverflow.com/q/48097513
tags question: http://stackoverflow.com/q/48060354
tags question: http://stackoverflow.com/q/48139939
tags question: http://stackoverflow.com/q/48161464
tags question: http://stackoverflow.com/q/48027005
tags question: http://stackoverflow.com/q/48093976
tags question: http://stackoverflow.com/q/48128268
tags question: http://stackoverflow.com/q/48023481
tags question: http://stackoverflow.com/q/48150480
tags question: http://stackoverflow.com/q/48015707
tags question: http://stackoverflow.com/q/48089942
tags question: http://stackoverflow.com/q/48125990
tags question: http://stackoverflow.com/q/48136491
tags question: http://stackoverflow.com/q/48050769
tags question: http://stackoverflow.com/q/48058178
tags question: http://stackoverflow.com/q/48034871
tags question: http://stackoverflow.com/q/48049300
tags question: http://stackoverflow.com/q/48139864
tags question: http://stackoverflow.com/q/48124312
tags question: http://stackoverflow.com/q/48095713
tags question: http://stackoverflow.com/q/48065865
tags question: http://stackoverflow.com/q/48069555
tags question: http://stackoverflow.com/q/48040159
tags question: http://stackoverflow.com/q/48170206
tags question: http://stackoverflow.com/q/48110630

http://stackoverflow.com/comment/83116077
has text: Sorry yes. That's just to help with debugging and show that it's a list. I think there's a problem with your logic here. What are you trying to test? That one particular element is not in the set? That none of the elements in the list are in the set? That some elements in the list are not in the set?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48070895
type: AnswerComment

http://stackoverflow.com/a/48155846
downvote count: 0
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/48135059
has body: As depicted in https://github.com/mrjbq7/ta-lib/issues/175#issuecomment-356042378: This is what the function does. It gets an input price array, and a periods array that are the same length. The output price array is the moving average at the point using the specified period at the point. So, if you have an array of [1, 5, 3, 8] and you specify periods [2,3,3,2] then the output will be: [SMA(2)[0], SMA(3)[1], SMA(3)[2], SMA(2)[3]] With the exception that it puts maxperiods number of nan's at the front, for some reason so you'd need to call it like: &gt;&gt;&gt; prices = np.array([1,5,7,8], dtype=float) &gt;&gt;&gt; periods =np.array([2,3,3,2], dtype=float) &gt;&gt;&gt; ta.MAVP(prices, periods, maxperiod=3) array([ nan, nan, 4.33333333, 7.5 ]) &gt;&gt;&gt; ta.SMA(prices, 2) array([ nan, 3. , 6. , 7.5]) &gt;&gt;&gt; ta.SMA(prices, 3) array([ nan, nan, 4.33333333, 6.66666667])

http://stackoverflow.com/q/48159303
type: Question
tagged with: python-venv
score: 14
has comment: http://stackoverflow.com/comment/83298227
upvote count: 14
has comment: http://stackoverflow.com/comment/83298419
answer count: 1
has comment: http://stackoverflow.com/comment/83298347
has comment: http://stackoverflow.com/comment/83298252
has comment: http://stackoverflow.com/comment/83298183
favorite count: 0
has comment: http://stackoverflow.com/comment/83298167
type: UnansweredQuestion
tagged with: python
has body: I have successfully activated a virtual environment and installed packages there, but when I try to list those packages with pip list I get the list of global packages, not those in the activated venv. $ source ./venv/bin/activate [venv] pip list # ... global 2.7 packages are listed [venv] pip3 list # ... global 3 packages are listed but $ cd venv/lib/pythonXX/site-packages $ ls # ...venv's installed packages are listed even though python -version correctly lists the venv's Python (and not any global version). How do I list my pip-installed packages inside a venv?
has comment: http://stackoverflow.com/comment/83298214
downvote count: 0
has title: How do I list my pip-installed packages inside a venv?
has comment: http://stackoverflow.com/comment/83298182
has answer: http://stackoverflow.com/a/62632480
tagged with: pip

http://stackoverflow.com/comment/83089709
comment on: http://stackoverflow.com/q/48058082
type: Comment
score: 0
has text: In C, the end of a statement is signalled with `;`; that indicator is *required*. In Python, the end of a logical line is usually signalled by a newline (in your editor, hitting `<ENTER>` to go to the next line). The logical line can be extended across multiple physical lines by using `(....)` paretheses, `[...]` brackets, or `{...}` curly braces with newlines inside. *Or* you can end the line with a backslash, `\ `. This is entirely orthogonal to escape sequences in string literals, which in Python are a lot like those in C.
type: QuestionComment

http://stackoverflow.com/q/48129549
duplicate of: http://stackoverflow.com/q/4310489
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
upvote count: 2
score: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48129596
has body: I am making an application using Tkinter and I am facing some problem. This is a simple code in which I want to remove white border outside Blue Canvas. from tkinter import * root = Tk() root.config(bg='black') root.geometry('500x500') Canvas(root, bg='blue', bd=0).pack(pady=100) root.mainloop() This is output GUI Here, I have tried bd=0 to make border size 0. But it is not working.
has title: Tkinter: Remove white border outside Canvas
linked to: http://stackoverflow.com/q/4310489
answer count: 1

http://stackoverflow.com/comment/83192744
has text: Please consider adding a code sample, or revising the one you posted in this question. As it currently stands, its formatting and scope make it hard for us to help you; here is a [great resource](http://stackoverflow.com/help/mcve) to get you started on that. Good luck with your code!
comment on: http://stackoverflow.com/q/48108787
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83146941
type: AnswerComment
has text: I updated your import statement in the first one and now it works for both python 2 and 3, so no need for the second answer :)
comment on: http://stackoverflow.com/a/48070886
type: Comment
score: 1

http://stackoverflow.com/q/48046883
has comment: http://stackoverflow.com/comment/83066358
favorite count: 0
has body: I think I'm having a rounding problem causing my sprite to move faster/jump farther while moving left. My sprites update method is calling move, which calls move_single_axis for each axis. Inside this I'm doing some collision detection where I rely on pygame's rect class to both detect the collision, and set the new position. I think this is the problem but I'm uncertain how to get around the rounding issue because pygame's rect uses integers under the hood. Here's the update code: def update(self, dt, game): self.calc_grav(game, dt) self.animate(dt, game) self._old_position = self._position[:] self.move(dt, game) self.rect.topleft = self._position def move(self, dt, game): # Move each axis separately. Note that this checks for collisions both times. dx = self.velocity[0] dy = self.velocity[1] if dx != 0: self.move_single_axis(dx, 0, dt) if dy != 0: self.move_single_axis(0, dy, dt) def move_single_axis(self, dx, dy, dt): #print("hero_destination: ({}, {})".format(dx *dt, dy *dt)) self._position[0] += dx * dt self._position[1] += dy * dt #print("Game walls: {}".format(game.walls)) self.rect.topleft = self._position body_sensor = self.get_body_sensor() for wall in game.walls: if body_sensor.colliderect(wall.rect): if dx &gt; 0: # Moving right; Hit the left side of the wall #print(" -- Moving right; Hit the left side of the wall") self.rect.right = wall.rect.left if dx &lt; 0: # Moving left; Hit the right side of the wall #print(" -- Moving left; Hit the right side of the wall") self.rect.left = wall.rect.right - self.COLLISION_BOX_OFFSET if dy &gt; 0: # Moving down; Hit the top side of the wall #print(" -- Moving down; Hit the top side of the wall") self.rect.bottom = wall.rect.top if dy &lt; 0: # Moving up; Hit the bottom side of the wall #print(" -- Moving up; Hit the bottom side of the wall") self.rect.top = wall.rect.bottom self._position[0] = self.rect.topleft[0] self._position[1] = self.rect.topleft[1] Here is the whole source(https://github.com/davidahines/pyth…
type: Question
has comment: http://stackoverflow.com/comment/83065986
has answer: http://stackoverflow.com/a/48047450
has comment: http://stackoverflow.com/comment/83066189
tagged with: python
tagged with: pygame
accepted answer: http://stackoverflow.com/a/48047450
upvote count: 1
answer count: 1
tagged with: pytmx
type: AnsweredQuestion
has title: Sprite moving faster left than right pygame
downvote count: 0
score: 1

http://stackoverflow.com/q/48086277
has comment: http://stackoverflow.com/comment/83149851
tagged with: django
tagged with: python
has title: Django conn= connet(dsn, connetion_factory, async=async) django.db.utils.OperationalError psycopg2
has comment: http://stackoverflow.com/comment/83148041
answer count: 0
has comment: http://stackoverflow.com/comment/83150815
has comment: http://stackoverflow.com/comment/83203466
type: Question
linked to: http://stackoverflow.com/q/36629963
score: 0
has body: I am working on the connection of postgresql 9.5 and Django 1.11 in wimdows 7, but it throws me an error install python 3.4.2, add path install postgresql 9.5.10, add path install virtualenv version 15.1.0 create virtualenv myenv run Scripts\myenv\activate install psycopg2-2.6.2.win32-py3.4-pg9.5.3-release.exe, add folder psycopg2 in C:\proyectos\myenv\Lib\site-packages install Django 1.11 create project Django => django-admin.py startproject redsocial in the folder redsocial => django-admin.py startapp goodpeople in Sublime text3 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'goodpeople', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'goodpeople', 'USER': 'postgresql', 'PASSWORD': 'postgresl', 'HOST': 'localhost', 'PORT': '5432', } } #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "redsocial.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise 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?" ) raise execute_from_command_line(sys.argv) python manage.py migrate, python manage.py test, python manage.py runserver enter image description here enter image description here enter image description here same result of three enter image description here I appreciate the slightest help
tagged with: postgresql
type: UnansweredQuestion

http://stackoverflow.com/q/48090175
possible better answer: http://stackoverflow.com/a/52806852
accepted answer: http://stackoverflow.com/a/48410781
tagged with: python
has body: Does anyone here succeed to run im2txt with TensorFlow 1.4.1? I'm using this model(https://drive.google.com/file/d/0B_qCJ40uBfjEWVItOTdyNUFOMzg/view) 2018-01-04 00:46:59.268582: W tensorflow/core/framework/op_kernel.cc:1192] Not found: Key lstm/basic_lstm_cell/kernel not found in checkpoint Then I tried the following script to convert model. The script generated checkpoint, .meta, .data, and .index. OLD_CHECKPOINT_FILE = "/tmp/my_checkpoint/model.ckpt-3000000" NEW_CHECKPOINT_FILE = "/tmp/my_converted_checkpoint/model.ckpt-3000000" import tensorflow as tf vars_to_rename = { "lstm/BasicLSTMCell/Linear/Matrix": "lstm/basic_lstm_cell/weights", "lstm/BasicLSTMCell/Linear/Bias": "lstm/basic_lstm_cell/biases", } new_checkpoint_vars = {} reader = tf.train.NewCheckpointReader(OLD_CHECKPOINT_FILE) for old_name in reader.get_variable_to_shape_map(): if old_name in vars_to_rename: new_name = vars_to_rename[old_name] else: new_name = old_name new_checkpoint_vars[new_name] = tf.Variable(reader.get_tensor(old_name)) init = tf.global_variables_initializer() saver = tf.train.Saver(new_checkpoint_vars) with tf.Session() as sess: sess.run(init) print("save checkpoint") saver.save(sess, NEW_CHECKPOINT_FILE) Could anyone tell me how I can use those files to run im2txt with TensorFlow 1.4.1. (Actually, I could run im2txt with tensorflow 0.12.1) Env python 3.5.2 Mac OS X version 10.12.6 TensorFlow 1.4.1 Thank for your help.
has answer: http://stackoverflow.com/a/48410781
type: AnsweredQuestion
has title: im2txt & TensorFlow 1.4.1
tagged with: tensorflow
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/52806852
score: 0

http://stackoverflow.com/q/48072001
tagged with: django-models
answer count: 1
downvote count: 0
favorite count: 0
has title: Database and Models present still programming error is coming in DJango
has comment: http://stackoverflow.com/comment/83119421
tagged with: python
has answer: http://stackoverflow.com/a/48072039
has comment: http://stackoverflow.com/comment/83119507
type: AnsweredQuestion
has body: I am trying to get the models data on the browser using the urls.py and views.py for last 3 days and failing miserably, although I am able to get the database in a json file but not on browser. This is the error log [http://dpaste.com/2DQZX1Z][1] and the code is here models.py from __future__ import unicode_literals from django.db import models class Authors(models.Model): aid = models.AutoField(primary_key=True) aname = models.CharField(max_length=200, blank=True, null=True) adescription = models.CharField(max_length=8000, blank=True, null=True) class Books(models.Model): bid = models.IntegerField(primary_key=True) bname = models.CharField(max_length=200, blank=True, null=True) bdescription = models.CharField(max_length=8000, blank=True, null=True) class Bookauth(models.Model): bid = models.ForeignKey(Books, models.DO_NOTHING, db_column='bid', blank=True, null=True) aid = models.ForeignKey(Authors, models.DO_NOTHING, db_column='aid', blank=True, null=True) views.py from __future__ import unicode_literals from django.shortcuts import render import requests from django.http import HttpResponse from django.db import models from .models import Books import json from django.core import serializers def index(request): return HttpResponse("Hello, world. You're at the polls index.") def getObject(request): all_books = Books.objects.all() html = serializers.serialize('json', all_books) return HttpResponse(html) #data = serializers.serialize("json", Books.objects.all()) #return HttpResponse(data, mimetype='application/json') urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^non', views.index, name = 'index'), url(r'^auth', views.author_search, name = 'AuthSearch'), url(r'^book', views.getObject, name = 'Books') ]
tagged with: django
upvote count: 1
type: Question
score: 1
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/48072039

http://stackoverflow.com/q/48118602
downvote count: 1
has answer: http://stackoverflow.com/a/48118826
tagged with: http://stackoverflow.com/tag/json
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83213637
answer count: 1
has comment: http://stackoverflow.com/comment/83214212
has comment: http://stackoverflow.com/comment/83213993
favorite count: 0
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83213871
has title: Python generate JSON from two dictionaries
type: UnansweredQuestion
has body: I have two dictionaries in python 3, called a and b which when dumped as JSON come out as below: a = {"person": 26.94, "car": 99.49, "dog": 50.56} b = {"filename": "1234.jpg", "model": "model1", "prototxt": "prototxt.txt"} I need to combine these into the JSON format below but I am a bit lost on the approach in python, so welcome any pointers! { "payload": { "config": [{ "model": "model1", "filename": "1234.jpg", "prototxt": "prototxt.txt" }], "results": [{ "object": "person", "value": 26.94 }, { "object": "car", "value": 99.49 }, { "object": "dog", "value": 50.56 } ] } }
has comment: http://stackoverflow.com/comment/83214012
upvote count: 1

http://stackoverflow.com/comment/83182851
score: 0
type: Comment
type: QuestionComment
has text: Yikes, I was contemplating even asking this question because the forms in question have patient information (so they cannot be posted) and I know its difficult to explain what exactly is happening. If there are any suggestions for how to improve the accuracy of either template matching or feature detection that would be helpful. Basically they are all black and white forms with a lot of text and a small to medium sized company logo in the corner.
comment on: http://stackoverflow.com/q/48081791

http://stackoverflow.com/comment/83276503
comment on: http://stackoverflow.com/q/48147872
score: 0
type: Comment
type: QuestionComment
has text: solved it using np.logical_or

http://stackoverflow.com/comment/83288528
type: QuestionComment
type: Comment
score: 0
has text: @chrisz The indentation issue might be from copy/pasting to SO though.
comment on: http://stackoverflow.com/q/48154698

selenium
tags question: http://stackoverflow.com/q/48167037
tags question: http://stackoverflow.com/q/48117925
tags question: http://stackoverflow.com/q/48146486
tags question: http://stackoverflow.com/q/48104633
tags question: http://stackoverflow.com/q/48065179
tags question: http://stackoverflow.com/q/48097819
tags question: http://stackoverflow.com/q/48103019
tags question: http://stackoverflow.com/q/48050870
tags question: http://stackoverflow.com/q/48077068
tags question: http://stackoverflow.com/q/48017592
tags question: http://stackoverflow.com/q/48058169
tags question: http://stackoverflow.com/q/48025106
tags question: http://stackoverflow.com/q/48139454
tags question: http://stackoverflow.com/q/48145466
tags question: http://stackoverflow.com/q/48099835
tags question: http://stackoverflow.com/q/48120556
tags question: http://stackoverflow.com/q/48075257
tags question: http://stackoverflow.com/q/48045663
tags question: http://stackoverflow.com/q/48040412
tags question: http://stackoverflow.com/q/48131039
tags question: http://stackoverflow.com/q/48061088
tags question: http://stackoverflow.com/q/48054321
tags question: http://stackoverflow.com/q/48118496
tags question: http://stackoverflow.com/q/48163269
tags question: http://stackoverflow.com/q/48154250
tags question: http://stackoverflow.com/q/48020132
tags question: http://stackoverflow.com/q/48112142
tags question: http://stackoverflow.com/q/48020641
tags question: http://stackoverflow.com/q/48138919
tags question: http://stackoverflow.com/q/48056052
tags question: http://stackoverflow.com/q/48144078
tags question: http://stackoverflow.com/q/48099403
tags question: http://stackoverflow.com/q/48088916
tags question: http://stackoverflow.com/q/48045073
tags question: http://stackoverflow.com/q/48073360
tags question: http://stackoverflow.com/q/48158045
tags question: http://stackoverflow.com/q/48029897
tags question: http://stackoverflow.com/q/48042281
tags question: http://stackoverflow.com/q/48015404
tags question: http://stackoverflow.com/q/48047766
tags question: http://stackoverflow.com/q/48040836
tag name: selenium
tags question: http://stackoverflow.com/q/48141221
tags question: http://stackoverflow.com/q/48124409
tags question: http://stackoverflow.com/q/48040364
tags question: http://stackoverflow.com/q/48028782
tags question: http://stackoverflow.com/q/48159055
tags question: http://stackoverflow.com/q/48075864
tags question: http://stackoverflow.com/q/48046342
tags question: http://stackoverflow.com/q/48143345
tags question: http://stackoverflow.com/q/48065269
tags question: http://stackoverflow.com/q/48056574
tags question: http://stackoverflow.com/q/48088796
tags question: http://stackoverflow.com/q/48113622
tags question: http://stackoverflow.com/q/48162795
tags question: http://stackoverflow.com/q/48139676
tags question: http://stackoverflow.com/q/48051365
tags question: http://stackoverflow.com/q/48119282
tags question: http://stackoverflow.com/q/48122169
tags question: http://stackoverflow.com/q/48018277
tags question: http://stackoverflow.com/q/48020561
tags question: http://stackoverflow.com/q/48173192
tags question: http://stackoverflow.com/q/48017454
tags question: http://stackoverflow.com/q/48139340
tags question: http://stackoverflow.com/q/48027558
tags question: http://stackoverflow.com/q/48048663
tags question: http://stackoverflow.com/q/48076329
tags question: http://stackoverflow.com/q/48083073
tags question: http://stackoverflow.com/q/48173238
tags question: http://stackoverflow.com/q/48144574
tags question: http://stackoverflow.com/q/48068774
tags question: http://stackoverflow.com/q/48051368
tags question: http://stackoverflow.com/q/48015640
tags question: http://stackoverflow.com/q/48115462
tags question: http://stackoverflow.com/q/48165357
tags question: http://stackoverflow.com/q/48020177
tags question: http://stackoverflow.com/q/48111432
tags question: http://stackoverflow.com/q/48130525
tags question: http://stackoverflow.com/q/48087399
tags question: http://stackoverflow.com/q/48126785

qubole
type: Tag
tags question: http://stackoverflow.com/q/48019407
tag name: qubole

http://stackoverflow.com/a/52862146
answers question: http://stackoverflow.com/q/48069875
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/92745594
score: 0
has body: Module imports are indeed case sensitive. The way to check this is to first confirm if it's possible to: import flask_sqlalchemy If that succeeds, the package is installed correctly. Once the package is confirmed to be installed correctly, then this should succeed. from flask_sqlalchemy import SQLAlchemy
type: Answer

django
tags question: http://stackoverflow.com/q/48035878
tags question: http://stackoverflow.com/q/48160798
tags question: http://stackoverflow.com/q/48127363
tags question: http://stackoverflow.com/q/48086283
tags question: http://stackoverflow.com/q/48031010
tags question: http://stackoverflow.com/q/48111721
tags question: http://stackoverflow.com/q/48026322
tags question: http://stackoverflow.com/q/48154009
tags question: http://stackoverflow.com/q/48148354
tags question: http://stackoverflow.com/q/48064481
tags question: http://stackoverflow.com/q/48031800
tags question: http://stackoverflow.com/q/48159489
tags question: http://stackoverflow.com/q/48140157
tags question: http://stackoverflow.com/q/48128419
tags question: http://stackoverflow.com/q/48153585
tags question: http://stackoverflow.com/q/48067886
tags question: http://stackoverflow.com/q/48041190
tags question: http://stackoverflow.com/q/48099340
tags question: http://stackoverflow.com/q/48161312
tags question: http://stackoverflow.com/q/48113984
tags question: http://stackoverflow.com/q/48088783
tags question: http://stackoverflow.com/q/48015546
tags question: http://stackoverflow.com/q/48055517
tags question: http://stackoverflow.com/q/48037755
tags question: http://stackoverflow.com/q/48017881
tags question: http://stackoverflow.com/q/48053101
tags question: http://stackoverflow.com/q/48087095
tags question: http://stackoverflow.com/q/48075739
tags question: http://stackoverflow.com/q/48051548
tags question: http://stackoverflow.com/q/48120570
tags question: http://stackoverflow.com/q/48026782
tags question: http://stackoverflow.com/q/48120696
tags question: http://stackoverflow.com/q/48080315
tags question: http://stackoverflow.com/q/48055255
tags question: http://stackoverflow.com/q/48092397
tags question: http://stackoverflow.com/q/48062228
tags question: http://stackoverflow.com/q/48095529
tags question: http://stackoverflow.com/q/48015368
tags question: http://stackoverflow.com/q/48034675
tags question: http://stackoverflow.com/q/48048011
tags question: http://stackoverflow.com/q/48167088
tags question: http://stackoverflow.com/q/48167244
tags question: http://stackoverflow.com/q/48153880
tags question: http://stackoverflow.com/q/48061510
tags question: http://stackoverflow.com/q/48154246
tags question: http://stackoverflow.com/q/48062763
tags question: http://stackoverflow.com/q/48089571
tags question: http://stackoverflow.com/q/48163135
tags question: http://stackoverflow.com/q/48078932
tags question: http://stackoverflow.com/q/48169591
tags question: http://stackoverflow.com/q/48045438
tags question: http://stackoverflow.com/q/48015196
tags question: http://stackoverflow.com/q/48172676
tags question: http://stackoverflow.com/q/48102595
tags question: http://stackoverflow.com/q/48060126
tags question: http://stackoverflow.com/q/48109318
tags question: http://stackoverflow.com/q/48154787
tags question: http://stackoverflow.com/q/48095737
tags question: http://stackoverflow.com/q/48127921
tags question: http://stackoverflow.com/q/48063990
tags question: http://stackoverflow.com/q/48069019
tags question: http://stackoverflow.com/q/48089903
type: Tag
tags question: http://stackoverflow.com/q/48018081
tags question: http://stackoverflow.com/q/48096177
tags question: http://stackoverflow.com/q/48047486
tags question: http://stackoverflow.com/q/48153604
tags question: http://stackoverflow.com/q/48092558
tags question: http://stackoverflow.com/q/48020008
tags question: http://stackoverflow.com/q/48147193
tags question: http://stackoverflow.com/q/48115038
tags question: http://stackoverflow.com/q/48022957
tags question: http://stackoverflow.com/q/48100366
tags question: http://stackoverflow.com/q/48056466
tags question: http://stackoverflow.com/q/48173347
tags question: http://stackoverflow.com/q/48141625
tags question: http://stackoverflow.com/q/48125161
tags question: http://stackoverflow.com/q/48041841
tags question: http://stackoverflow.com/q/48142122
tags question: http://stackoverflow.com/q/48087980

http://stackoverflow.com/a/48115626
upvote count: 1
has comment: http://stackoverflow.com/comment/83209437
has comment: http://stackoverflow.com/comment/83270825
has comment: http://stackoverflow.com/comment/83320657
has body: If you want the optimal solution you have to be O(n^2), if you want an approximate of the optimal solution you can select a threshold and delete pairs that have a fair similarity ratio. I would suggest you use another metrics since you're adding complexity with the difflib's ratio (it depends on the length of the strings). These ratio could be entropy or manhattan/euclidean distance.
has comment: http://stackoverflow.com/comment/83323774
answers question: http://stackoverflow.com/q/48115430
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83207779
has comment: http://stackoverflow.com/comment/83207417
score: 1

http://stackoverflow.com/q/48125006
linked to: http://stackoverflow.com/q/36516183
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48125047
has answer: http://stackoverflow.com/a/48125043
accepted answer: http://stackoverflow.com/a/48125043
score: 7
has comment: http://stackoverflow.com/comment/83227116
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/83226890
tagged with: python-requests
upvote count: 8
type: Question
possible better answer: http://stackoverflow.com/a/48125047
answer count: 3
downvote count: 1
favorite count: 0
has body: I am trying to web scrape the content of few of the websites. But I noticed that for some of the websites I am getting the response with status code as 200. However, for some other of them I am getting 404 status code with the response. But when I am opening these websites (returning 404) in the browser, it is loading fine for me. What am I missing here? For example: import requests url_1 = "https://www.transfermarkt.com/jumplist/startseite/wettbewerb/GB1" url_2 = "https://stackoverflow.com/questions/36516183/what-should-i-use-instead-of-urlopen-in-urllib3" page_t = requests.get(url_2) print(page_t.status_code) #Getting a Not Found page and 404 status page = requests.get(url_1) print(page.status_code) #Getting a Valid HTML page and 200 status
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48125053
tagged with: python
has title: 404 status code while making HTTP request via Python's "requests" library. However page is loading fine in browser

http://stackoverflow.com/q/48118893
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/83224740
tagged with: opencv
has comment: http://stackoverflow.com/comment/83214202
has answer: http://stackoverflow.com/a/48120175
downvote count: 1
type: Question
tagged with: image-extraction
has comment: http://stackoverflow.com/comment/83214106
has body: I have a region of an image selected, like this: http://slideplayer.com/4593320/15/images/9/Intelligent+scissors+http%3A%2F%2Frivit.cs.byu.edu%2FEric%2FEric.html.jpg and now, using OpenCV I would like to extract the region selected. How could I do it? I have already researched but nothing useful got. Thanks in advance.
score: 0
linked to: http://stackoverflow.com/q/14161331
answer count: 1
favorite count: 0
has title: Extract selected region from image with OpenCV
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48022885
score: 0
has body: Thanks to all contributors to get me closer to a solution. The solution is actually quite simple. The challenge was that pandas interpreted (1,2) as range and not as string However, the target was to create a list of all values, originally by splitting a string on ','. Not needed! list(range(1,2)) does the job already. Here is the example and solution: list(range(11, 17)) &gt;&gt; [11, 12, 13, 14, 15, 16] tickets['seats'][0] &gt;&gt; range(1, 3) list(alltickets['seats'][0]) &gt;&gt; [1, 2] So solution(s): def single_seats_comma(row): strlist = list(row) return strlist tickets['seats'].apply(single_seats_comma) or tickets['seats'].apply(lambda row: list(row))
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48019434
accepted answer of: http://stackoverflow.com/q/48019434

http://stackoverflow.com/comment/83072904
type: Comment
type: QuestionComment
score: 3
has text: Change `print(self.mytext)` to `print(self.textEdit.toPlainText())`
comment on: http://stackoverflow.com/q/48049836

http://stackoverflow.com/comment/83166415
type: QuestionComment
comment on: http://stackoverflow.com/q/48095737
has text: @mohammedqudah I have also tried `request.sessionStorage["asd"] = 2`, but it gives an error, as sessionStorage does not exist.
score: 0
type: Comment

http://stackoverflow.com/a/61648709
answers question: http://stackoverflow.com/q/48129123
score: 0
type: Answer
has body: You just set the variable. foo = 'bar' And it persists throughout the session

http://stackoverflow.com/comment/83166786
has text: I understand that its trying to convert the city names into a float and it cant do it, I want to load only the numbers and I am not sure if its even possible
score: 0
comment on: http://stackoverflow.com/q/48095872
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83090539
type: Comment
has text: And http://www.nltk.org/book/ch05.html
score: 1
comment on: http://stackoverflow.com/q/48058311
type: QuestionComment

http://stackoverflow.com/comment/83098856
type: AnswerComment
comment on: http://stackoverflow.com/a/48062326
score: 0
type: Comment
has text: Only problem I found is that the dictionary has some missing keys so I have to find a way to reorder them so I can later iterate them one by one.

http://stackoverflow.com/comment/83218139
type: Comment
has text: dont we have any alternative?
comment on: http://stackoverflow.com/a/48103898
score: 0
type: AnswerComment

http://stackoverflow.com/a/48046507
answers question: http://stackoverflow.com/q/48045718
upvote count: 2
has comment: http://stackoverflow.com/comment/83077530
type: Answer
score: 2
downvote count: 0
has body: One approach may be to structure the file storage as a csv file. Given the following contents in testfile.csv: 'username','subject','unit','score','grade' 'qwe', 'history', 'ww2', '65', 'C' 'abc', 'maths', 'trigonometry', '80', 'A' 'qwe', 'gatos', 'cat behavior', '32', 'F' 'abc', 'cooking', 'making sushi', '99', 'A' Then here is a demonstration of using the csv standard library to conveniently handle reading contents of the file in a way that automatically retains the structure of the data as a dictionary. The column headers become the keys and each row's data becomes the values. In this case, the username of interest and filename are passed to a function which will return a list containing a dict for each test record found for that user. From there you have any number of options for how you want to process the information with the usual manipulations that apply to python dictionaries, though below it is only printed nicely for the sake of illustration. import csv from pprint import pprint # just pretty printing for demo filename = 'testfile.csv' user = 'abc' def main(): test_scores_list = get_scores(filename, user) if len(test_scores_list) &gt; 0: print 'The following test scores have been found for user: {}'.format(user) for row in test_scores_list: pprint(row) else: print 'No tests found for user: {}.'.format(user) def get_scores(filename, user): test_scores_list = [] with open(filename, 'rb') as csvfile: datareader = csv.DictReader(csvfile, delimiter=',', quotechar='\'') for row in datareader: if row['username'] == user: test_scores_list.append(row) return test_scores_list if __name__ == '__main__': main() This snippet and sample input file will produce this output if you assign the username "abc" in the code: The following test scores have been found for user: abc {'grade': " 'A'", 'score': " '80'", 'subject': " 'maths'", 'unit': " 'trigonometry'", 'username': 'abc'} {'grade': " 'A'", 'score': " '99'", 'subject': " 'cooking'", 'unit': " 'making sushi'", 'userna…

http://stackoverflow.com/comment/83195986
type: Comment
comment on: http://stackoverflow.com/a/48109729
score: 0
type: AnswerComment
has text: @pansen - and one improvement should be instaed `df["group_diff"]` create Series `group_number=df.sort_values("val")...` and last `df.groupby([group_number, "group_diff"])` ;)

http://stackoverflow.com/q/48140587
type: Question
has comment: http://stackoverflow.com/comment/83258984
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83259162
linked to: http://stackoverflow.com/q/509211
has body: I have a tuple of rows and columns and wanted to access the last row and last column from it. how to do this?
favorite count: 0
has answer: http://stackoverflow.com/a/48140659
has comment: http://stackoverflow.com/comment/83258917
downvote count: 8
type: UnansweredQuestion
score: -8
has title: Python Tuple last row and last column
tagged with: python
has comment: http://stackoverflow.com/comment/83258950
has comment: http://stackoverflow.com/comment/83259114

http://stackoverflow.com/q/48078937
has comment: http://stackoverflow.com/comment/89225811
type: Question
answer count: 2
tagged with: u-sql
score: 0
has title: Schedule web scraping jobs on Azure and store results on ADLS
tagged with: azure
tagged with: python
linked to: http://stackoverflow.com/q/41888772
has answer: http://stackoverflow.com/a/48086949
type: UnansweredQuestion
has body: I have a python job which uses beautiful soup to scrape data from the web.I have tried executing the script using U-SQL, however I keep receiving a generic error message : An unhandled exception from user code has been reported I haven't explored the error too much as I am not sure if it is possible to scrape the web through U-SQL. Is this possible using U-SQL, and if not which Azure resource can i use to schedule this script and store the results on Azure data lake store?
has answer: http://stackoverflow.com/a/48247629

http://stackoverflow.com/q/48127921
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/48128021
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: twitter-bootstrap
tagged with: django
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48128021
answer count: 1
has title: Django - Bootstrap Dropdown Lists Not Working
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83232448
has body: I'm working on my Django web application and I can't seem to get the dropdown list to actually drop down when clicked. Actions Start Clone Stop Run Anti-Anti-Forensics Checker and by request my urls.py, although i'm not entirely sure how that's related urlpatterns = [ #multiurl( url(r'^$', views.index, name='index'), #url(r'^$', views.transfer, name='transfer'), url(r'^malware/$', views.malware, name='malware'), # Add this /malware/ route url(r'^pokedex/$', views.pokedex, name='pokedex'), # Add this /malware/ route url(r'^about/$', views.about, name='about'), # Add this /about/ route #url(r'^(?P\d+)/results/$', views.results, name='results'), # url(r'^(?P<>\d+)/Clone/$', ) url(r'^clone/(?P<uuid>[\w\-]+)$', views.clone, name='clone'), url(r'^start/(?P<uuid>[\w\-]+)$', views.start, name='start'), url(r'^paranoidfish/(?P<uuid>[\w\-]+)$', views.paranoidfish, name='paranoidfish'), url(r'^stop/(?P<uuid>[\w\-]+)$', views.stop, name='stop'), url(r'^transfer/(?P<uuid>[\w\-]+)$', views.transfer, name='transfer'), # url(r'^(?P<uuid>[\w\-]+)/(?P<malware>[\w\-]+)$', views.execute, name='execute'), url(r'^execute/(?P<uuid>([0-9\-a-f]+))/(?P<malware>[-A-Z\0-9\-a-z]+)/$', views.execute, name='execute'), url(r'^transfer/(?P<uuid>([0-9\-a-f]+))/(?P<malware>[-A-Z\0-9\-a-z]+)/$', views.transfer, name='transfer'), #) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

http://stackoverflow.com/comment/83231492
comment on: http://stackoverflow.com/q/48127434
type: Comment
score: 1
has text: tuple of `(str, int, int, int)`
type: QuestionComment

http://stackoverflow.com/q/48114861
answer count: 1
tagged with: lxml
has answer: http://stackoverflow.com/a/48115032
favorite count: 0
tagged with: python-3.x
has body: I write a script to delete unwanted objects from huge datasets by their id-prefix. That's how these objects are structured: &lt;wfsext:Replace vendorId="AdV" safeToIgnore="false"&gt; &lt;AX_Anschrift gml:id="DENWAEDA0000001G20161222T083308Z"&gt; &lt;gml:identifier codeSpace="http://www.adv-online.de/"&gt;urn:adv:oid:DENWAEDA0000001G&lt;/gml:identifier&gt; ... &lt;/AX_Anschrift&gt; &lt;ogc:Filter&gt; &lt;ogc:FeatureId fid="DENWAEDA0000001G20161222T083308Z" /&gt; &lt;/ogc:Filter&gt; &lt;/wfsext:Replace&gt; I like to delete these full snippet within &lt;wfsext:Replace&gt;...&lt;/wfsext:Replace&gt; And there is a code snippet from my script: file = etree.parse(portion_file) root = file.getroot() nsmap = root.nsmap.copy() nsmap['adv'] = nsmap.pop(None) node = root.xpath(".//adv:geaenderteObjekte/wfs:Transaction", namespaces=nsmap)[0] for t in node: for obj in t: objecttype = str(etree.QName(obj.tag).localname) if objecttype == 'Filter': pass else: objid = (obj.xpath('@gml:id', namespaces=nsmap))[0][:16] if debug: print('{} - {}'.format(objid[:16], objecttype)) if objid[:6] != prefix: #parent = obj.getparent() t.remove(obj) The t.remove(obj) removes &lt;AX_Anschrift&gt;..&lt;/AX_Anschrift&gt; but not the rest of the object. I tried to get the parent node by using obj.getparent() but this gives me an error. How to catch it?
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/48115032
type: Question
has title: Get parent node?
has comment: http://stackoverflow.com/comment/83205596
downvote count: 0

http://stackoverflow.com/comment/83063868
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48046242
has text: have you thought about using https://networkx.github.io/documentation/latest/? They have a very good graph object that is pretty fast for construction.
score: 0

http://stackoverflow.com/comment/101813381
comment on: http://stackoverflow.com/a/48016620
score: 6
type: AnswerComment
has text: Now it is `--file=environment.yml` and not -f, which fails.
type: Comment

http://stackoverflow.com/a/48158238
has comment: http://stackoverflow.com/comment/83307280
answers question: http://stackoverflow.com/q/48152899
has comment: http://stackoverflow.com/comment/83308143
score: 0
type: AcceptedAnswer
has body: If you want the simplest extension to your existing code, to select only a few columns for the DataFrame, the following can be used as a starting point: import requests from bs4 import BeautifulSoup import pandas as pd headings=['Name','Accession Number','Type','Groups','Description'] # add more as needed, first hit on each is taken df = pd.DataFrame([], columns=headings) def get_details(url): global df global headings print('details:', url) r = requests.get(url) soup = BeautifulSoup(r.text ,"lxml") dts = soup.findAll('dt') dds = soup.findAll('dd') data = {} for dt, dd in zip(dts, dds): if (dt.text in headings) and (dt.text not in data): data[dt.text] = dd.text df = df.append(data,ignore_index=True) def drug_data(): url = 'https://www.drugbank.ca/drugs/' while url: print(url) r = requests.get(url) soup = BeautifulSoup(r.text ,"lxml") # get links to subpages links = soup.select('strong a') for link in links: # exeecute function to get subpage get_details('https://www.drugbank.ca' + link['href']) # next page url url = soup.findAll('a', {'class': 'page-link', 'rel': 'next'}) print(url) if url: url = 'https://www.drugbank.ca' + url[0].get('href') else: break drug_data() print df'Name', 'Accession Number' (NB the problem with the data in your URLs is you get multiple hits on eg. 'Description') Anyway, hope this may help.
type: Answer
accepted answer of: http://stackoverflow.com/q/48152899

http://stackoverflow.com/a/73744226
type: Answer
has body: Just run below command it was worked for me $ sudo chown -R www-data:www-data /var/www/TW96/tw96/ Checking file ownership If you have created any new files &amp; folders in your website’s folder then its owner may be the Linux user you are currently logged in as. For example, if you are currently logged in as user ubuntu and create a new file in /var/www/html then its owner will be ubuntu. By default Apache uses www-data user to access your website’s files &amp; folders by default. So in this case, you will need to change the user of newly created files &amp; folders. Run the following command to set the owner of your website files &amp; folders recursively. $ sudo chown -R www-data:www-data /var/www/html for more detailed references please check this below link https://fedingo.com/how-to-fix-errno-13-permission-denied-error-in-apache/
answers question: http://stackoverflow.com/q/48056297
score: 0

http://stackoverflow.com/a/48098055
type: Answer
answers question: http://stackoverflow.com/q/48097819
has body: Your html has an error, an extra space in the word class of the first circle. i this this should work to get the first circle: //svg//g[contains(@class,"_0")]//circle[contains(@class,"highlight")] i hope it helps :)
score: 0

http://stackoverflow.com/a/48046008
upvote count: 1
has body: Drop the anchors and use .search() instead of .match() &gt;&gt;&gt; import re &gt;&gt;&gt; my_number_finder = re.compile(r"""\$?\.?\d+\.?\,?\d+\.?\,?\%?\s?\d+""") &gt;&gt;&gt; m = my_number_finder.search("asbdf 12234") &gt;&gt;&gt; m.group() '12234' &gt;&gt;&gt; m = my_number_finder.search("asbdf $12234") &gt;&gt;&gt; m.group() '$12234' &gt;&gt;&gt; m = my_number_finder.search("asbdf 122.34%") &gt;&gt;&gt; m.group() '122.34' &gt;&gt;&gt; m = my_number_finder.search("asbdf 3,122.34%") &gt;&gt;&gt; m.group() '3,122.34' &gt;&gt;&gt; m = my_number_finder.search("asbdf 3,122 112") &gt;&gt;&gt; m.group() '3,122 112' I can't explain the inconsistent treatment of $ and % (because I haven't looked hard enough) but that behaviour was already present in your regex.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48045952
type: Answer

http://stackoverflow.com/comment/83264195
type: QuestionComment
score: 0
has text: What is the root of your project `simplesocial` or `simple_social_clone`?
comment on: http://stackoverflow.com/q/48142723
type: Comment

http://stackoverflow.com/q/48029517
has comment: http://stackoverflow.com/comment/83029346
has title: How to run 3 counters simultaneously in Python?
accepted answer: http://stackoverflow.com/a/48029695
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83029247
has comment: http://stackoverflow.com/comment/83029218
score: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/83029334
downvote count: 2
has comment: http://stackoverflow.com/comment/83029533
tagged with: simultaneous
has answer: http://stackoverflow.com/a/48029760
type: Question
tagged with: counter
has answer: http://stackoverflow.com/a/48030912
has comment: http://stackoverflow.com/comment/83029301
has comment: http://stackoverflow.com/comment/83029220
has answer: http://stackoverflow.com/a/48029695
has comment: http://stackoverflow.com/comment/83029759
tagged with: while-loop
tagged with: for-loop
has comment: http://stackoverflow.com/comment/83029329
possible better answer: http://stackoverflow.com/a/48029631
has body: I'd like to run simultaneously 3 different counters following a very specific pattern: counter_3 displays the number of iteration from 0 to 2144 counter_1 increases by 1 every 65 iterations counter_2 goes from 1 to 65, then starts back from 2 to 65, then from 3 to 65 ... The result should look like this: counter_1 counter_2 counter_3 0 1 0 0 2 1 0 3 2 0 4 3 0 5 4 ... ... ... 0 65 64 1 2 65 1 3 66 1 4 67 ... ... ... 1 65 128 1 3 129 2 4 130 2 5 131 ... ... ... 32 64 2142 32 65 2143 32 65 2144 I know how to run these counters separately. For counter_1 and counter_3 (refered below as i): counter_1 = 0 for i, e in enumerate(range(2145)): if i &gt; 1 and i % 65 == 0: counter_1 += 1 print(counter_1, i) For counter_2 (refered below as e): n = 0 g = 1 while n &lt;= 2145: for e in np.arange(g, 66): print(e) g += 1 n += 1 QUESTION: How can i run these 3 counters simultaneously ?
has answer: http://stackoverflow.com/a/48029631
favorite count: 0
has comment: http://stackoverflow.com/comment/83029379
has comment: http://stackoverflow.com/comment/83029363
tagged with: python
has comment: http://stackoverflow.com/comment/83029270

http://stackoverflow.com/q/48123091
answer count: 1
favorite count: 0
tagged with: sampling
tagged with: python
tagged with: mcmc
accepted answer: http://stackoverflow.com/a/48142275
type: AnsweredQuestion
has body: I'm working through a book called Bayesian Analysis in Python. The book focuses heavily on the package PyMC3 but is a little vague on the theory behind it so I'm quite confused. Say I have data like this: data = np.array([51.06, 55.12, 53.73, 50.24, 52.05, 56.40, 48.45, 52.34, 55.65, 51.49, 51.86, 63.43, 53.00, 56.09, 51.93, 52.31, 52.33, 57.48, 57.44, 55.14, 53.93, 54.62, 56.09, 68.58, 51.36, 55.47, 50.73, 51.94, 54.95, 50.39, 52.91, 51.5, 52.68, 47.72, 49.73, 51.82, 54.99, 52.84, 53.19, 54.52, 51.46, 53.73, 51.61, 49.81, 52.42, 54.3, 53.84, 53.16]) And I'm looking at a model like this: Using Metropolis Sampling, how can I fit a model that estimates mu and sigma. Here is my guess at pseudo-code from what I've read: M, S = 50, 1 G = 1 # These are priors right? mu = stats.norm(loc=M, scale=S) sigma = stats.halfnorm(scale=G) target = stats.norm steps = 1000 mu_samples = [50] sigma_samples = [1] for i in range(steps): # proposed sample... mu_i, sigma_i = mu.rvs(), sigma.rvs() # Something happens here # How do I calculate the likelidhood?? "..." # some evaluation of a likelihood ratio?? a = "some"/"ratio" acceptance_bar = np.random.random() if a &gt; acceptance_bar: mu_samples.append(mu_i) sigma_samples.append(sigma_i) What am I missing??
tagged with: pymc3
downvote count: 1
type: Question
upvote count: 5
tagged with: bayesian
score: 4
has title: Metropolis Sampling
has answer: http://stackoverflow.com/a/48142275

http://stackoverflow.com/comment/83068666
has text: In reference you can just set a threshold, say 0.4 to 0.6 as the neutral.
comment on: http://stackoverflow.com/a/48044722
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48081763
type: Answer
has comment: http://stackoverflow.com/comment/83138676
has comment: http://stackoverflow.com/comment/83139535
has comment: http://stackoverflow.com/comment/83140558
has comment: http://stackoverflow.com/comment/83140947
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83162999
has comment: http://stackoverflow.com/comment/83140793
accepted answer of: http://stackoverflow.com/q/48081103
has body: The reason query_str = "Set @null_val = \'\'; "\ " select @null_val" erpur_df = pd.read_sql(query_str, con = db) throws that exception is because all you are doing is setting null_value to '' and then selecting that '' - what exactly would you have expected that to give you? EDIT read_sql only seems to execute one query at a time, and as the first query returns no rows it results in that exception. If you split them in to two calls to read_sql then it will in fact return you the value of your @null value in the second call. Due to this behaviour read_sql is clearly not a good way to do this. I strongly suggest you use one of my suggestions below. Why are you wanting to set the variable in the SQL using '@' anyway? You could try using the .format style of string formatting. Like so: query_str = "select ... coalesce(field1, {c}), case(.. then {c})...".format(c=my_const) pd.read_sql(query_str) Just remember that if you do it this way and your my_const is a user input then you will need to sanitize it manually to prevent SQL injection. Another possibility is using a dict of params like so: query_str = "select ... coalesce(field1, %(my_const)s, case(.. then %(my_const)s)..." pd.read_sql(query_str, params={'my_const': const_value}) However this is dependent on which database driver you use. From the pandas.read_sql docs: Check your database driver documentation for which of the five syntax styles, described in PEP 249’s paramstyle, is supported. Eg. for psycopg2, uses %(name)s so use params={‘name’ : ‘value’}
has comment: http://stackoverflow.com/comment/83162382
answers question: http://stackoverflow.com/q/48081103
has comment: http://stackoverflow.com/comment/83163394
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83140170
has comment: http://stackoverflow.com/comment/83163206
has comment: http://stackoverflow.com/comment/83138378

http://stackoverflow.com/comment/83379483
has text: I was thinking of using `pickle` or `json`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48162876
score: 0

http://stackoverflow.com/a/48122334
has body: You could do it with a loop: count = 1 for index, row in df.iterrows(): if row['A'] == 'CUSTOM': row['A'] += str(count) count += 1 print(df) #output A 0 RK 1 G 2 CUSTOM1 3 CUSTOM2 4 KL 5 kj
upvote count: 1
answers question: http://stackoverflow.com/q/48122276
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/48115573
upvote count: 0
accepted answer: http://stackoverflow.com/a/48115826
has answer: http://stackoverflow.com/a/48115723
answer count: 2
tagged with: pandas
has title: Can't create a pandas series from numpy array
has comment: http://stackoverflow.com/comment/83207506
has comment: http://stackoverflow.com/comment/83207130
has comment: http://stackoverflow.com/comment/83207269
possible better answer: http://stackoverflow.com/a/48115723
has comment: http://stackoverflow.com/comment/83207738
has comment: http://stackoverflow.com/comment/83207794
favorite count: 0
has comment: http://stackoverflow.com/comment/83207207
has comment: http://stackoverflow.com/comment/83207617
tagged with: python
has answer: http://stackoverflow.com/a/48115826
score: -2
type: AnsweredQuestion
has body: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) TypeError Traceback (most recent call last) &lt;ipython-input-18-24949215fb6c&gt; in &lt;module&gt;() ----&gt; 1 s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) TypeError: 'int' object is not callable
downvote count: 2
type: Question

http://stackoverflow.com/comment/83243564
type: AnswerComment
has text: Sorry for spamming comments, but I don't understand why you're renaming `get_functions.get_item.get_item` as `get_functionsfromget_item.
type: Comment
comment on: http://stackoverflow.com/a/48133126
score: 0

http://stackoverflow.com/q/48123817
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83225166
tagged with: python
has comment: http://stackoverflow.com/comment/83290601
tagged with: excel
type: AnsweredQuestion
has body: I want to make a new array out of different numbers from each array. This is an example: import numpy as np a=[[0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10],[0,1,2,3,4,5,6,7,8,9,10]] b=[[0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10],[0,1,2,3,4,5,6,7,8,9,10]] c=[[0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10],[0,1,2,3,4,5,6,7,8,9,10]] d=[] for c in range (0,2): d.append([]) for s in range (0,10): d[c] =np.concatenate((a[c][s],b[c][s],c[c][s])) print(d) when I print 'd', it gives me a TypeError: 'int' object is not subscriptable. Is this due to the concatenante function? or can I use stack? I want the outcome to be something like: d[0][0]= [0,0,0] having the first term from each array. d[0][0] is indexing to a file and a row. that's why I want this format.
has answer: http://stackoverflow.com/a/48160216
accepted answer: http://stackoverflow.com/a/48160216
type: Question
tagged with: arrays
has title: Making an array from multiple elements from different arrays

postgresql
tags question: http://stackoverflow.com/q/48096745
tags question: http://stackoverflow.com/q/48099902
tags question: http://stackoverflow.com/q/48103203
tags question: http://stackoverflow.com/q/48112034
tags question: http://stackoverflow.com/q/48031568
tags question: http://stackoverflow.com/q/48141975
tags question: http://stackoverflow.com/q/48098432
tags question: http://stackoverflow.com/q/48111202
tags question: http://stackoverflow.com/q/48023625
tags question: http://stackoverflow.com/q/48060795
tags question: http://stackoverflow.com/q/48173124
tags question: http://stackoverflow.com/q/48161673
tags question: http://stackoverflow.com/q/48053070
tags question: http://stackoverflow.com/q/48090732
tags question: http://stackoverflow.com/q/48108218
tag name: postgresql
tags question: http://stackoverflow.com/q/48070409
tags question: http://stackoverflow.com/q/48116760
tags question: http://stackoverflow.com/q/48019381
tags question: http://stackoverflow.com/q/48103964
tags question: http://stackoverflow.com/q/48058833
tags question: http://stackoverflow.com/q/48021238
tags question: http://stackoverflow.com/q/48038472
type: Tag
tags question: http://stackoverflow.com/q/48046313
tags question: http://stackoverflow.com/q/48087980
tags question: http://stackoverflow.com/q/48123440
tags question: http://stackoverflow.com/q/48066546
tags question: http://stackoverflow.com/q/48049396
tags question: http://stackoverflow.com/q/48038807
tags question: http://stackoverflow.com/q/48069555
tags question: http://stackoverflow.com/q/48086277
tags question: http://stackoverflow.com/q/48075442

http://stackoverflow.com/comment/83228116
type: QuestionComment
has text: @furas Hey again! Thank you for your input. Yeah, it's been a long night over here as its 3am right now and I'd caught that too late. I'm using Jupyter notebook and have been monitoring everything via the r.text to see what comes in and it wasn't fetching what I needed. But I got the answer. Thank you again!
comment on: http://stackoverflow.com/q/48125300
score: 0
type: Comment

http://stackoverflow.com/a/48157838
has comment: http://stackoverflow.com/comment/83295511
has body: virtualenv is not a command out of the box with Python 3 (or at least the Homebrew variant I have). The command to create a virtualenv is python3 -mvenv dir to create a virtualenv in dir, and (in Bash) . dir/bin/activate to activate it.
score: 1
upvote count: 3
downvote count: 2
answers question: http://stackoverflow.com/q/48157247
type: Answer

http://stackoverflow.com/a/48153367
has body: Note: this no longer works. Use x.name in the map_diag function, which is passed the series of each column. import matplotlib.pyplot as plt import seaborn as sns iris = sns.load_dataset('iris') def diagfunc(x, **kws): ax = plt.gca() ax.annotate(x.name, xy=(0.05, 0.9), xycoords=ax.transAxes) sns.PairGrid(iris).map_diag(diagfunc) To also remove the normal axis titles, follow Remove axis titles from Seaborn PairGrid and add: for ax in g.axes.flatten(): ax.set_ylabel('') ax.set_xlabel('')
answers question: http://stackoverflow.com/q/48145811
score: 0
has comment: http://stackoverflow.com/comment/101521477
type: Answer

http://stackoverflow.com/a/48130802
answers question: http://stackoverflow.com/q/48130703
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/83239550
has comment: http://stackoverflow.com/comment/83238884
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/83238976
has body: Since you're working with unnamed index columns, one way is using query on ilevel_* - df.query("ilevel_0 == 'A2' and ilevel_1 == 'B1' and ilevel_2 &gt; 1") colA ColB A2 B1 2 ca6 cb6 Another method is using index.get_level_values - f = df.index.get_level_values df.loc[(f(0) == 'A2') &amp; (f(1) == 'B1') &amp; (f(2) &gt; 1)] colA ColB A2 B1 2 ca6 cb6
has comment: http://stackoverflow.com/comment/83239576
has comment: http://stackoverflow.com/comment/83238835

http://stackoverflow.com/comment/83174619
has text: so `place_sym` creates a "vertical" line right? in that case with only the outer loop: `r[p] = plyr[turn]`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48099712

http://stackoverflow.com/a/48125583
has comment: http://stackoverflow.com/comment/83228229
answers question: http://stackoverflow.com/q/48125300
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 11
has body: I tried scraping the page using requests and lxml but when iterating over the tags in the script, I could find no subtitles on the page (the textarea tag where the subtitles are do not show up in the script) This is likely because YouTube uses javascript to load the subtitles. Python's request library does not support javascript. You do however have a few options: Use selenium for scraping the subtitles (You said you would rather not do this.) Look into the POST and GET requests through your browser and try sending the request parameters needed to the url you traced the javascript to (May not always work if authentication is or dynamic tokens are used for parameters) Use youtube-dl to download the subtitles. (This seems to be the easiest / most reliable way to go about this.) youtube-dl is a command line utility, but you can also import it according to the docs on github. There are a couple of ways you could go about this. I will be using the video you pointed to in your post for my examples: youtube-dl --write-sub --skip-download --sub-lang en https://www.youtube.com/watch?v=Nxb2s2Mv6Pw With that being said, you can make a function in python to call the command: import os def download_subs(video_url, lang="en"): cmd = [ "youtube-dl", "--skip-download", "--write-sub", "--sub-lang", lang, video_url ] os.system(" ".join(cmd)) url = "https://www.youtube.com/watch?v=Nxb2s2Mv6Pw" download_subs(url) Alternatively, you could import youtube_dl from python directly and use it from there: import youtube_dl def download_subs(url, lang="en"): opts = { "skip_download": True, "writesubtitles": "%(name)s.vtt", "subtitlelangs": lang } with youtube_dl.YoutubeDL(opts) as yt: yt.download([url]) url = "https://www.youtube.com/watch?v=Nxb2s2Mv6Pw" download_subs(url) This creates a file in the working directory named CNN 'Exposed' In Controversial Secret Video and Anita Sarkeesian's 'Punishment'...-Nxb2s2Mv6Pw.en.vtt The contents of the file look something like this: WEBVTT Kind: caption…
accepted answer of: http://stackoverflow.com/q/48125300
score: 11

http://stackoverflow.com/q/48026545
has title: Reference argument in keyword argument
has answer: http://stackoverflow.com/a/48026936
tagged with: python
tagged with: parameter-passing
has comment: http://stackoverflow.com/comment/83022926
has answer: http://stackoverflow.com/a/48026751
answer count: 4
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/48026737
score: 1
has comment: http://stackoverflow.com/comment/83022987
type: Question
has answer: http://stackoverflow.com/a/48026720
accepted answer: http://stackoverflow.com/a/48026720
linked to: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/83024038
has comment: http://stackoverflow.com/comment/83023947
has comment: http://stackoverflow.com/comment/83022865
has answer: http://stackoverflow.com/a/48026737
upvote count: 1
linked to: http://stackoverflow.com/q/3394835
tagged with: keyword-argument
favorite count: 0
has body: Is there any way to use the value of an argument to dynamically set the default of a keyword argument? I was thinking of something like this: def foo(lst, r = 0, l = len(lst)): #I am referring to the "l = len(lst)" part print r, l foo([1,2,3]) This gives the following traceback: Traceback (most recent call last): File "C:/Python27/quicksort.py", line 25, in &lt;module&gt; def foo(lst, r = 0, l = len(lst)): NameError: name 'lst' is not defined One could do something similar to this: def foo(lst, r = 0, l = None): if l is None: l = len(lst) print r, l But I am hoping for a more elegant solution. Can anybody help?

http://stackoverflow.com/comment/112972535
has text: You... I like you. You even updated that blog of yours regarding the 32-bit scenario... You deserve a cookie. :)
comment on: http://stackoverflow.com/a/57566621
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/58162779
has comment: http://stackoverflow.com/comment/102799708
has body: I managed something when I moved my Wagtail site from sqlite to Postgres, so just adding for reference. I used this website as a base, but ran into an error when I couldn't delete ContentType objects right away due to a foreign key issue, as follows: django.db.utils.IntegrityError: insert or update on table "wagtailcore_page" violates foreign key constraint "wagtailcore_page_content_type_id_c28424df_fk_django_co" DETAIL: Key (content_type_id)=(1) is not present in table "django_content_type". Seemed like it was due to Wagtail page objects, so executed the following two lines in the Django shell first. Was then able to follow the rest of the instructions on that page, executing the ContentType deletion and the import. from wagtail.core.models import Page Page.objects.all().delete()
answers question: http://stackoverflow.com/q/48141975
score: 0
has comment: http://stackoverflow.com/comment/102733833
type: Answer

http://stackoverflow.com/comment/83039624
type: QuestionComment
has text: Hi, thanks for your comment. actually my situation is a bit complex. I firstly used selenium to login to the website and obtained the cookies, then I passed the session cookies to python. def request(driver): s = requests.Session() cookies = driver.get_cookies() for cookie in cookies: s.cookies.set(cookie['name'], cookie['value']) return s req = request(browser) Could you please detail a bit how to save the video after the above codes? thanks!
comment on: http://stackoverflow.com/q/48034696
score: 0
type: Comment

http://stackoverflow.com/a/48096798
upvote count: 1
has comment: http://stackoverflow.com/comment/83169388
score: 1
answers question: http://stackoverflow.com/q/48095790
downvote count: 0
type: Answer
has body: Under Run -> Edit Configurations... you can see the Configuration on the right Side. At the Bottom is a Section called Before launch: Activate tool window where you can hit the green plus Button and configure pylint to be executed before the run.
has comment: http://stackoverflow.com/comment/83169236

http://stackoverflow.com/comment/83323582
has text: Works great, thanks! Will try to implement it into my real-world problem and get back to you in case of further questions.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48171948

http://stackoverflow.com/a/48130296
answers question: http://stackoverflow.com/q/48123045
downvote count: 0
has body: Try this: # In[1]: df = pd.read_excel('help.xlsx', header=[0,1,2,3]) #Read file, use 4 rows as header df.columns = df.columns.map(','.join) #Concatenate by ',' the fields name df = df.rename_axis('PW').reset_index() #reset and rename index df2 = pd.melt(df, id_vars=list(df.columns)[0], value_vars=list(df.columns)[1:], value_name='Volume') #Unpivot table, g roping by 'variable' and 'volume' df2'Category', 'Field_Type', 'Growing_Method', 'Product' = df2['variable'].str.split(',',expand=True) #Split using ',' as delimeter df2.__delitem__('variable') #Delete extra field 'variable' #Reorder Columns cols = df2.columns.tolist() df2 = df2[[cols[0]] + cols[2:] + [cols[1]]] df2
has comment: http://stackoverflow.com/comment/83243768
has comment: http://stackoverflow.com/comment/83243024
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/48123045
type: AcceptedAnswer

http://stackoverflow.com/a/50455059
type: Answer
answers question: http://stackoverflow.com/q/48066517
has body: You need to install the "xlrd" lib For Linux (Ubuntu and Derivates): Installing via pip: python -m pip install --user xlrd Install system-wide via a Linux package manager: *sudo apt-get install python-xlrd Windows: Installing via pip: *pip install xlrd Download the files: https://pypi.org/project/xlrd/
score: 0

http://stackoverflow.com/comment/83408765
comment on: http://stackoverflow.com/q/48084938
has text: @ZachRickers Try `inspect.getsource(function)` for a string of the function code. Otherwise look at the documentation I linked to and try some simple tests in ipython. Also please tag me if you comment again otherwise I don't get notifications for your replies.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83281631
type: Comment
type: QuestionComment
has text: https://ufile.io/hmppl check the file i uploaded here @jezrael
comment on: http://stackoverflow.com/q/48151423
score: 0

recursion
type: Tag
tags question: http://stackoverflow.com/q/48125274
tags question: http://stackoverflow.com/q/48017422
tags question: http://stackoverflow.com/q/48032100
tags question: http://stackoverflow.com/q/48120431
tags question: http://stackoverflow.com/q/48059415
tags question: http://stackoverflow.com/q/48066384
tags question: http://stackoverflow.com/q/48084884
tag name: recursion
tags question: http://stackoverflow.com/q/48094990
tags question: http://stackoverflow.com/q/48059908
tags question: http://stackoverflow.com/q/48126050
tags question: http://stackoverflow.com/q/48035634
tags question: http://stackoverflow.com/q/48134865
tags question: http://stackoverflow.com/q/48134055
tags question: http://stackoverflow.com/q/48104886
tags question: http://stackoverflow.com/q/48165235
tags question: http://stackoverflow.com/q/48118508
tags question: http://stackoverflow.com/q/48134314
tags question: http://stackoverflow.com/q/48029204
tags question: http://stackoverflow.com/q/48138479
tags question: http://stackoverflow.com/q/48149218
tags question: http://stackoverflow.com/q/48064530
tags question: http://stackoverflow.com/q/48070296
tags question: http://stackoverflow.com/q/48030287

http://stackoverflow.com/q/48090935
has title: Wagtail - getting routablepageurl of page category in other page
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
downvote count: 0
score: 1
type: Question
tagged with: wagtail
has answer: http://stackoverflow.com/a/48092737
has body: I have filter of category on mydomain.com/gallery/album/2017 class Gallery(RoutablePageMixin,Page): short_description = models.CharField(max_length=300,blank=True) content_panels = Page.content_panels + [ FieldPanel('short_description'), InlinePanel('image_gallery', label="image gallery"), ] def get_posts(self): return AlbumImageGallery.objects.all() @route(r'^albums/(?P&lt;album&gt;[-\w]+)/$') def post_by_category(self, request, album, *args, **kwargs): self.get_posts = self.get_posts().filter(album__slug=album) return Page.serve(self, request, *args, **kwargs) def get_context(self, request, *args, **kwargs): context = super(Gallery, self).get_context(request, *args, **kwargs) context['albums'] = Album.objects.all() context['album_image'] = AlbumImageGallery.objects.all() context['get_posts'] = self.get_posts context['gallery'] = self return context In my HTML &lt;a href="{% routablepageurl gallery "post_by_category" each.slug %}"&gt; {{each.album_name}}&lt;/a&gt; Now i want to get mydomain.com/gallery/album/2017 from my other page class MymodelPage(Page): ... get_context(): context['gallery_images'] = Image.objects.all() context['gallery'] = Gallery.objects.get() MymodelPage.html Error NoReverseMatch at /media-corner/ Reverse for 'post_by_category' with arguments '('',)' not found. 1 pattern(s) tried: [u'albums/(?P&lt;album&gt;[-\\w]+)/$'] I want to get gallery url/slug on my Modal RoutablePageMixin i tried to pass url page its gives me error

http://stackoverflow.com/q/48126560
has body: I am trying to establish a TCP/IP connection between SIMULINK (client) and PYTHON (server). I tried sending the value of a variable in a loop. But the value I receive in SIMULINK is some random values(like 2.5e-09 or something) which hasno relation with the value I sent. I have tried changing the data type on the SIMULINK side.But no luck. Following is the code in PYTHON: import socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind(('localhost',30001)) serversocket.listen(5) (clientsocket, address) = serversocket.accept() for i in range(0,50): msg1='%0.1f\n' %(float(1.1+i)) clientsocket.send(msg1.encode('utf-8')) clientsocket.close() Following is my simulink block and the block parameter settings: Can somebody please help?
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83230304
has comment: http://stackoverflow.com/comment/83229946
favorite count: 0
accepted answer: http://stackoverflow.com/a/48126670
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: tcp
tagged with: simulink
type: Question
has answer: http://stackoverflow.com/a/48126670
has title: TCP/IP between SIMULINK and PYTHON

http://stackoverflow.com/q/48091874
downvote count: 0
has comment: http://stackoverflow.com/comment/83158117
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/75699555
has comment: http://stackoverflow.com/comment/108803118
tagged with: python
has body: Is there a way to concurrently download S3 files using boto3 in Python3? I am aware of the aiobotocore library, but I would like to know if there is a way to do it using the standard boto3 library.
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 17
type: Question
has title: Downloading multiple S3 objects in parallel in Python
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/57445139
tagged with: boto3
score: 17
tagged with: botocore
has answer: http://stackoverflow.com/a/63505251

http://stackoverflow.com/comment/83220002
type: Comment
comment on: http://stackoverflow.com/a/48121615
has text: @Windstorm1981: see the links in my answer. `is_month_end` won't work if you want _business_ month end though.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48161116
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/48179872
has comment: http://stackoverflow.com/comment/83304990
has body: I have the following message 'Tensor' object is not iterable." when trying to run my code, can someone tell me where is my mistake? All the problem started because I need to normalize the the data that I am feeding. Therefore the problems comes from this part of my code: for epoch in range(training_epochs): avg_cost = 0. total_batch = int(total_len / batch_size) # Loop over all batches for i in range(total_batch): batch_x = tf.train.batch(X_train_norm, batch_size) batch_y = tf.train.batch(Y_train, batch_size) # Run optimization op (backprop) and cost op (to get loss value) _, c, p = sess.run([optimizer, cost, pred], feed_dict={x: batch_x, y: batch_y}) # Compute average loss avg_cost += c / total_batch # sample prediction label_value = batch_y estimate = p err = label_value - estimate print("num batch:", total_batch) Here is my whole code: import tensorflow as tf import numpy as np X_train = np.genfromtxt('data/train500X.csv', delimiter=',', dtype=float) Y_train = np.genfromtxt('/data/train500Y.csv', delimiter=',', dtype=float) X_test = np.genfromtxt('data/test100X.csv', delimiter=',', dtype=float,usecols=(14, 7, 33, 13, 32, 60, 16, 50, 18, 61, 17, 34, 26, 59, 85, 53)) Y_test = np.genfromtxt('data/test100Y.csv', delimiter=',', dtype=float) X_train_norm = tf.nn.l2_normalize(X_train, 0, epsilon=1e-12) # Parameters learning_rate = 0.001 training_epochs = 5000 batch_size = 50 display_step = 1 # Network Parameters n_hidden_1 = 100 # 1st layer number of features n_hidden_2 = 200 # 2nd layer number of features n_hidden_3 = 200 # 3rd layer number of features n_hidden_4 = 256 # 4th layer number of features n_out = 1 n_input = X_train.shape[1] total_len = X_train.shape[0] # tf Graph input x = tf.placeholder("float", [None, n_input]) y = tf.placeholder("float", [None]) # Create model def multilayer_perceptron(x, weights, biases): # Hidden layer with RELU activation layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) # Hidden layer with RELU…
score: 0
answer count: 1
type: UnansweredQuestion
has title: Tensor' object is not iterable
tagged with: python
tagged with: linear-regression
tagged with: machine-learning

http://stackoverflow.com/comment/83287481
score: 0
type: Comment
has text: I agree with @user333700, leaving out the C() does not do the trick if the variable is continuous (which was the case in both, Bill's and my example). Maybe the solution is to simply redefine the variable as a string and then leave out the C().
type: AnswerComment
comment on: http://stackoverflow.com/a/48104568

http://stackoverflow.com/a/48569654
type: Answer
answers question: http://stackoverflow.com/q/48032834
score: 0
has body: I solved this by changing the data type to 'python.array', seem Keras can not handle numpy.array input args through model loading.

http://stackoverflow.com/comment/83182128
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48100657
has text: why do you install VC++?
score: 0

http://stackoverflow.com/comment/83266803
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48144281
has text: `4(n-(n-i))` looks like you're trying to call a function named `4`.
score: 0

http://stackoverflow.com/comment/83206787
type: AnswerComment
score: 0
type: Comment
has text: Yes i was indeed using the wrong directory, I am running it on Windows not Linux. Thanks for this, I made some small modifications to print the line instead of the file name. Would you also be able to help me add a current directory function? so it can tell me what the current directory is that it is searching in? just so i know how close it is to ending. other than that thank you!
comment on: http://stackoverflow.com/a/48112121

http://stackoverflow.com/comment/83054912
type: Comment
comment on: http://stackoverflow.com/a/48042095
score: 0
type: AnswerComment
has text: This is what Paul Panzer put in the comments and Peter Wood had a similar idea with zip (earlier in the comments).

http://stackoverflow.com/q/48159125
answer count: 2
upvote count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48159448
has title: When using python 3.x, how do I take outputs from a "for" command and add them to a list or string?
has body: How would I take the results from the following code and assign a variable to it? for I in word: print (I + 117) For example, if the results came out to be 100,101,102,103 how would I get a variable set to "100,101,102,103" without manually entering every number into a variable. Also, I know that it says "your encrypted string is" and I know that that's not really encrypted, but I just got into this so I was just playing around. word = eval(input("What would you like to say")) print (word) encrypt = 117 print ("Your encrypted string is:") for I in word: print (I + 117) assuming I have ASCII codes set to their appropriate values Thanks to many people (most notably yukashima huksay and ZYYYY) I have my final code here: word = eval(input("What would you like to say")) print (word) changedword = (', '.join(str(I + 15) for I in word)) print ("Your encrypted string is:" + changedword) Assuming all ASCII codes set as variables.
favorite count: 0
has comment: http://stackoverflow.com/comment/83297856
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48159150
possible better answer: http://stackoverflow.com/a/48159448
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83297874
score: 1
has answer: http://stackoverflow.com/a/48159150
type: Question

http://stackoverflow.com/comment/83022811
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48026079
has text: Hi Simon, the problem I face is that, using the frozen script, I can read the content of the file but not write on it. If you say that it works for you, I guess the problem may be somewhere else. As I was now curious I tried to install it on another machine and it doesn't work either. So the problem, probably, is not in the way the script is written but in the freezing process. Any suggestion?

http://stackoverflow.com/comment/83214289
comment on: http://stackoverflow.com/q/48118436
score: 0
type: Comment
type: QuestionComment
has text: Look at the code for `np.size`. It isn't a `ufunc`. It either returns `x.size` or `x.shape(axis)`. It's in the `fromnumeric.py` file, which suggests that it is legacy code - from the old `numeric` package. There are a lot of `numpy` functions that delegate the action to array methods.

http://stackoverflow.com/q/48117126
score: 16
upvote count: 16
type: Question
has title: When using tweepy cursor, what is the best practice for catching over capacity errors?
has answer: http://stackoverflow.com/a/48186077
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48186077
has body: I'm gathering information on a large number of users using Python's Tweepy library. I've the API initialized as follows api = tweepy.API(auth,wait_on_rate_limit=True, wait_on_rate_limit_notify=True) where auth contains my tokens. This code responds well to rate limit errors, but doesn't work for some other errors. For example, I sometimes see the following exception. tweepy.error.TweepError: [{'message': 'Over capacity', 'code': 130}] I can handle this exception using a try except, but I was wondering if there is a way to handle this exception within the cursor like I'm handling rate limit exceptions. I see parameters like retry_count, but I'm not sure if they will work for this case as they seem designed for HTTP errors.
tagged with: python
tagged with: tweepy
type: AnsweredQuestion

http://stackoverflow.com/q/48032756
favorite count: 0
tagged with: jenkins
has comment: http://stackoverflow.com/comment/83037395
type: UnansweredQuestion
has title: Building a Python Web application in jenkins
has comment: http://stackoverflow.com/comment/83051511
tagged with: python
tagged with: build
score: 3
upvote count: 3
has body: I want to build an existing Python web application in jenkins, just like building a java application using Maven. Is it possible or not? if possible, please help me with necessary configurations to build and Continuous Deployment of the same application.
type: Question
tagged with: continuous-deployment
has answer: http://stackoverflow.com/a/48034085
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/83102068
score: 0
has text: Oh, is it that `otherentity` has a value of "none"?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48064451

http://stackoverflow.com/comment/83179206
comment on: http://stackoverflow.com/q/48101933
type: QuestionComment
score: 0
has text: @WillemVanOnsem ohhh. it is even worse formatted than I thought.
type: Comment

http://stackoverflow.com/comment/83311205
has text: @schwobaseggl Yes. Like `class Superclass(object)`.
type: AnswerComment
comment on: http://stackoverflow.com/a/48165920
score: 0
type: Comment

http://stackoverflow.com/comment/83071439
has text: Is this what you're doing? `for x, y in itertools.product(df1.Name, df2.name): f(x, y)` Why doesn't it work?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48049690
score: 0

http://stackoverflow.com/q/48083405
type: Question
linked to: http://stackoverflow.com/q/64089691
accepted answer: http://stackoverflow.com/a/48097717
answer count: 3
tagged with: pandas
has body: Both are columnar (disk-)storage formats for use in data analysis systems. Both are integrated within Apache Arrow (pyarrow package for python) and are designed to correspond with Arrow as a columnar in-memory analytics layer. How do both formats differ? Should you always prefer feather when working with pandas when possible? What are the use cases where feather is more suitable than parquet and the other way round? Appendix I found some hints here https://github.com/wesm/feather/issues/188, but given the young age of this project, it's possibly a bit out of date. Not a serious speed test because I'm just dumping and loading a whole Dataframe but to give you some impression if you never heard of the formats before: # IPython import numpy as np import pandas as pd import pyarrow as pa import pyarrow.feather as feather import pyarrow.parquet as pq import fastparquet as fp df = pd.DataFrame({'one': [-1, np.nan, 2.5], 'two': ['foo', 'bar', 'baz'], 'three': [True, False, True]}) print("pandas df to disk ####################################################") print('example_feather:') %timeit feather.write_feather(df, 'example_feather') # 2.62 ms ± 35.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) print('example_parquet:') %timeit pq.write_table(pa.Table.from_pandas(df), 'example.parquet') # 3.19 ms ± 51 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) print() print("for comparison:") print('example_pickle:') %timeit df.to_pickle('example_pickle') # 2.75 ms ± 18.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) print('example_fp_parquet:') %timeit fp.write('example_fp_parquet', df) # 7.06 ms ± 205 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) print('example_hdf:') %timeit df.to_hdf('example_hdf', 'key_to_store', mode='w', table=True) # 24.6 ms ± 4.45 ms per loop (mean ± std. dev. of 7 runs, 100 loops each) print() print("pandas df from disk ##################################################") print('example_feather:') %timeit feather.re…
has answer: http://stackoverflow.com/a/78703032
downvote count: 0
linked to: http://stackoverflow.com/q/67910612
favorite count: 0
has title: What are the differences between feather and parquet?
has answer: http://stackoverflow.com/a/48097717
tagged with: python
possible better answer: http://stackoverflow.com/a/72406099
score: 217
has answer: http://stackoverflow.com/a/72406099
type: AnsweredQuestion
upvote count: 217
tagged with: feather
tagged with: parquet
tagged with: pyarrow

http://stackoverflow.com/a/48148052
type: Answer
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48147971
has body: You want to replace 'Y' for True and 'N' for False then do a groupby with any. Finally, clean it up by reversing the replace. df.replace(dict(Y=True, N=False)) \ .groupby('id').any() \ .replace({True: 'Y', False: 'N'}) col1 col2 col3 id ENE80R Y N Y Alternatively, you could use pd.DataFrame.any with the level parameter. df.set_index('id').eq('Y').any(level=0).replace({True: 'Y', False: 'N'}) col1 col2 col3 id ENE80R Y N Y
accepted answer of: http://stackoverflow.com/q/48147971

http://stackoverflow.com/comment/83196654
has text: use the list flattening scheme `[x for y in my_list for x in y]`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48110641

http://stackoverflow.com/comment/83374411
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48168675
has text: You're correct. I should have said "repartition(n)". The parameter 'n' will need to be selected according to your available cores (I find 4-6x typically works well). Regardless of whether you have an RDD or a dataframe, reading from a single file yields a single partition.

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

http://stackoverflow.com/a/48135997
has comment: http://stackoverflow.com/comment/83250226
has comment: http://stackoverflow.com/comment/83249993
has body: A better approach is to use to_pickle: train.to_pickle('C:/Users/Documents/Tesfile_Preprocessed.pickle') Too many indices' means you've given too many index values. You've given 2 values as you're expecting data to be a 2D array. Numpy is complaining because data is not 2D (it's either 1D or None). I recommend you to check the array dimensions before accessing it. self.values.shape or len(self.values) This is NOT related to your Pandas, you are trying to access an not existing index on your array. Please try to change the sep during the export. train.to_csv('C:/Users/Documents/Tesfile_Preprocessed.csv', sep='\t')
has comment: http://stackoverflow.com/comment/83250657
has comment: http://stackoverflow.com/comment/83249922
has comment: http://stackoverflow.com/comment/83250566
has comment: http://stackoverflow.com/comment/83249956
has comment: http://stackoverflow.com/comment/83249611
accepted answer of: http://stackoverflow.com/q/48135848
has comment: http://stackoverflow.com/comment/83250091
has comment: http://stackoverflow.com/comment/83249860
upvote count: 1
has comment: http://stackoverflow.com/comment/83250094
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48135848
has comment: http://stackoverflow.com/comment/83250058
has comment: http://stackoverflow.com/comment/83250209
has comment: http://stackoverflow.com/comment/83249788
has comment: http://stackoverflow.com/comment/83249745
has comment: http://stackoverflow.com/comment/83250428
has comment: http://stackoverflow.com/comment/83250001
has comment: http://stackoverflow.com/comment/83250820
type: Answer
downvote count: 0
score: 1

odata
tag name: odata
tags question: http://stackoverflow.com/q/48145966
type: Tag

http://stackoverflow.com/q/48164841
upvote count: 2
has comment: http://stackoverflow.com/comment/83312236
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83312013
has comment: http://stackoverflow.com/comment/83312282
tagged with: menu
has comment: http://stackoverflow.com/comment/83312218
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has body: I've been trying to learn Tkinter and i've stumbled upon the below code while looking up Menu widget. from tkinter import * import tkinter.messagebox top = Tk() mb= Menubutton ( top, text="condiments", relief=RAISED ) mb.grid() mb.menu = Menu ( mb, tearoff = 0) mb["menu"] = mb.menu mayoVar = IntVar() ketchVar = IntVar() mb.menu.add_checkbutton ( label="mayo", variable=mayoVar ) mb.menu.add_checkbutton ( label="ketchup", variable=ketchVar ) mb.pack() top.mainloop() Now i undertand the purpose of code but am having a hard time figuring out what the below line of code is for. mb["menu"] = mb.menu
has comment: http://stackoverflow.com/comment/83312203
tagged with: widget
score: 1
has answer: http://stackoverflow.com/a/48166688
type: Question
has comment: http://stackoverflow.com/comment/83312103
has comment: http://stackoverflow.com/comment/83312240
has title: Python Tkinter Menu widget:

http://stackoverflow.com/q/48071662
has body: Suppose I have a pandas dataframe with following columns: A , B , C , D , E , F , G , H I want to select all the columns with a specific interval, say n.For example if n=2 and I start from A, I would select : A,B,E,F (select the first two,drop the next two and so on) If I start from the end, I would select: H,G,D,C I can even start from any random column in between.What would be an efficient way of doing so?
has title: Select multiple columns with an interval in pandas dataframe
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48071845
has answer: http://stackoverflow.com/a/48071850
type: Question
possible better answer: http://stackoverflow.com/a/48071850
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48071845
tagged with: python

http://stackoverflow.com/q/48090240
answer count: 1
score: 0
upvote count: 1
downvote count: 1
tagged with: python
favorite count: 0
type: UnansweredQuestion
tagged with: tensorflow
has title: Could not find a version that satisfies the requirement tensorflow==1.0.1?
has answer: http://stackoverflow.com/a/48090241
has body: I was battling this issue for the last 6 hours, so I decided to post a question and answer my own question, in case anyone else has this same issue. Why does the following line: pip install -r requirements.txt cause the following errors? The directory '/Users/ruchirbaronia/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. and Could not find a version that satisfies the requirement tensorflow==1.0.1 (from -r requirements.txt (line 16)) (from versions: 0.12.1, 1.0.0, 1.1.0rc0, 1.1.0rc1, 1.1.0rc2, 1.1.0, 1.2.0rc0, 1.2.0rc1, 1.2.0rc2, 1.2.0, 1.2.1, 1.3.0rc0, 1.3.0rc1, 1.3.0rc2, 1.3.0, 1.4.0rc0, 1.4.0rc1, 1.4.0, 1.4.1, 1.5.0rc0) No matching distribution found for tensorflow==1.0.1 (from -r requirements.txt (line 16)) I have tried upgrading Tensorflow, reinstalling pip, my version of python is 3.6 (which is supported), and even reinstalled tensorflow with pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.1.0-py2-none-any.whl using multiple versions from the official link from google. Why is midi-rnn still not working?
type: Question

http://stackoverflow.com/comment/83183829
comment on: http://stackoverflow.com/a/48104052
score: 0
type: AnswerComment
type: Comment
has text: Can you explain it in more details?

http://stackoverflow.com/q/48087647
tagged with: block
has comment: http://stackoverflow.com/comment/83150581
has title: how can i fix expected indented block on cmd
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48087659
score: -3
tagged with: python
accepted answer: http://stackoverflow.com/a/48087659
type: AnsweredQuestion
downvote count: 3
type: Question
has body: I'm trying to run hello.py under CMD but when I run the flask I get this error below, how can I fix it? enter image description here
upvote count: 0

http://stackoverflow.com/comment/83055206
type: Comment
comment on: http://stackoverflow.com/a/48042242
score: 1
has text: @MojtabaArvin: There are 26 letters in the alphabet, `a` to `z`, plus an underscore. That makes 27. The assumption is that you don't also want spaces, other punctuation, or upper-/lowercase distinctions.
type: AnswerComment

http://stackoverflow.com/comment/83579472
has text: just try removing it from include_files and add it as `includes=[... "execute"]`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48143566

http://stackoverflow.com/comment/83191367
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48106134
type: Comment
has text: This does not seem to work for me. ` df.set_index('col1')['col0'].fillna(w_frame.set_index('col1').col0).reset_index() col1 col0 0 b 0.057199 1 a 0.729004 2 d 0.217821 3 c 0.251979 4 a -2.486781 5 b 0.913252 6 NaN NaN 7 NaN NaN 8 NaN NaN 9 b -0.429894 ` I tried to understand what's going on but I think I will have to look at it with a fresh head. And with the transform method, I get a value error: `ValueError: Length mismatch: Expected axis has 79 elements, new values have 100 elements` -SM PS: I can't seem to get the format right in the comment. My apologies..

http://stackoverflow.com/a/48029730
type: Answer
has body: A keyword argument is when you pass the argument to a function like this: print_text(text='hello') Then, text is called the keyword and 'hello' is the argument. In the code you show, you pass an argument "Evento" this way, but the keyword ventanita.text is not correct, as it is an expression (having the dot) and not a valid keyword. So, you need to check the documentation of the Button function and see what is the correct keyword (probably just text).
answers question: http://stackoverflow.com/q/48029683
has comment: http://stackoverflow.com/comment/83029682
score: 0

http://stackoverflow.com/q/48084747
has title: Write row in google sheet using a dict
answer count: 1
score: 0
tagged with: python
tagged with: gspread
has body: The documentation on inserting a row using gspread indicates it needs a list: sheet.insert_row(row, index) where row is a list, and index is the sheet row number. But you can read a google spreadsheet into a list of dicts using get_all_records(). Is it possible to write to the sheet using a dict?
tagged with: google-api
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48084792
type: Question

http://stackoverflow.com/comment/83362661
comment on: http://stackoverflow.com/q/48158601
score: 0
type: Comment
type: QuestionComment
has text: Any help will be greatly appreciated?

http://stackoverflow.com/comment/83200904
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48096294
has text: If that's the case, I'd do it asynchronously using a queue like SQS. Making the script be a consumer of the queue. And the flask application just adding a message to the queue when receiving a request. But that has nothing to do with kubernetes or docker.
score: 0

http://stackoverflow.com/a/48043395
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48043329
answers question: http://stackoverflow.com/q/48043329
type: Answer
upvote count: 1
has body: Your code: df['Money Out'].replace('-', '', inplace=True) is using Series.replace which is a different thing (replaces an exact match of the column or a regex with a value) than the Series.str.replace function (more traditional replace a substring present anywhere with another), you can use: df['Money Out'] = df['Money Out'].str.replace('-', '') to remove any hyphens from your text.

http://stackoverflow.com/comment/83231855
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48125125
score: 0
has text: Have you tried to reinstall it ?

http://stackoverflow.com/q/48060769
tagged with: python
has comment: http://stackoverflow.com/comment/83094032
has title: python : cannot import tensorflow-gpu
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/48060803
tagged with: tensorflow
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/83094634
has comment: http://stackoverflow.com/comment/83094566
accepted answer: http://stackoverflow.com/a/48060803
downvote count: 0
has body: I successfully created my tensorflow environment with Anaconda3 on my machine with the steps introduced on this link. But when I try to try to do : &gt;&gt;&gt; import tensorflow as tf I get the following error messages : OSError and ImportError. Traceback (most recent call last): File "C:\Users\Froilan\Anaconda3\envs\tensorflow\lib\site- packages\tensorflow\python\platform\self_check.py", line 75, in preload_check ctypes.WinDLL(build_info.cudart_dll_name) File "C:\Users\Froilan\Anaconda3\envs\tensorflow\lib\ctypes\__init__.py", line 351, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 126] This specified module could not be found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\Froilan\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "C:\Users\Froilan\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "C:\Users\Froilan\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 30, in &lt;module&gt; self_check.preload_check() File "C:\Users\Froilan\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\platform\self_check.py", line 82, in preload_check % (build_info.cudart_dll_name, build_info.cuda_version_number)) ImportError: Could not find 'cudart64_80.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Download and install CUDA 8.0 from this URL: https://developer.nvidia.com/cuda-toolkit Could it be something to do with my cpu? I use Ryzen 1700. + GPU : GTX 1050 Ti - A bit inferior to 1080 ti or so.. but I've heard that GPU's would still be way better than CPU's.
favorite count: 0
has comment: http://stackoverflow.com/comment/83094060

http://stackoverflow.com/comment/83371934
comment on: http://stackoverflow.com/q/48160827
type: Comment
type: QuestionComment
has text: You can also speed up template matching quite a bit; once you have found your location on the full map, then you know that the next time you search it should be in an area near the last found location. See [this project](https://youtu.be/m99H6oH46E8) I gave a talk about last year; Mario's head is the template, but the white box around Mario's head is the search area. You can reduce to only look in the ROI around your last template location so that you don't get positive matches elsewhere. You can view the code from the demo [here](https://github.com/alkasm/track-mario-desertpy).
score: 1

http://stackoverflow.com/a/48133126
score: -1
has comment: http://stackoverflow.com/comment/83243508
answers question: http://stackoverflow.com/q/48133102
has comment: http://stackoverflow.com/comment/83243529
has comment: http://stackoverflow.com/comment/83243538
has comment: http://stackoverflow.com/comment/83243468
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83243564
has comment: http://stackoverflow.com/comment/83243686
downvote count: 2
has body: Solution for your problem: from get_functions import get_item class Shopping_list(): ... def get(): return get_item() Why does this work? It's because it imports get_item from get_functions, so you could import the module. However, if you try to attempt from get_functions import get_item again, it might not work. Ways to import the same function name in the script: from get_functions import get_item import models models.get_item # From a model get_item #Turns native, Because now it's on a new script If you want to rename it: from get_functions import get_item as get_functionsfromget_item get_functionsfromget_item #Turns native, Because now it's on a new script
has comment: http://stackoverflow.com/comment/83243628
has comment: http://stackoverflow.com/comment/83243562
has comment: http://stackoverflow.com/comment/83243599
has comment: http://stackoverflow.com/comment/83243590
has comment: http://stackoverflow.com/comment/83243520

http://stackoverflow.com/comment/85835161
comment on: http://stackoverflow.com/a/49301092
score: 1
type: AnswerComment
has text: ECH will do, sorry for the delay, but I haven't actually had time to try implementing this yet. I won't forget the question and will mark it as accepted once I've tried this!
type: Comment

http://stackoverflow.com/q/48062717
has comment: http://stackoverflow.com/comment/83099537
answer count: 1
has comment: http://stackoverflow.com/comment/83100039
has comment: http://stackoverflow.com/comment/83100783
has comment: http://stackoverflow.com/comment/83100351
favorite count: 0
has title: How to set my screen boundaries on a turtle drawing
has comment: http://stackoverflow.com/comment/83106493
tagged with: python
has comment: http://stackoverflow.com/comment/83099948
has body: I have a set code here that I use to generate a unique image each time the code is run; how do I set it to only draw within the boundaries of my tkinter screen? Here is the code: import random import turtle maker=turtle.Turtle() maker.getscreen().delay(0) maker.getscreen().tracer(0) n=random.randint(1,360) m=random.randint(0,100) r=random.randint(0,50) d=random.randint(1,2) maker2=maker.clone() maker3=maker.clone() maker4=maker.clone() maker.goto(0,0) maker2.goto(0,0) maker3.goto(0,0) maker4.goto(0,0) #top right maker.goto(50, 50) #bottom right maker2.goto(50, -50) #bottom left maker3.goto(-50, -50) #top left maker4.goto(-50, 50) while r&lt;50: for i in range (0,m): maker.forward(m) maker2.forward(m) maker3.backward(m) maker4.backward(m) for i in range (0,r): if d == 1: maker.right(n) maker2.right(n*-1) maker3.left(n*-1) maker4.left(n) elif d == 2: maker.left(n) maker2.left(n*-1) maker3.right(n*-1) maker4.right(n) maker.forward(m) maker2.forward(m) maker3.backward(m) maker4.backward(m) n=n+1 r = r + 1 n=random.randint(0,359) maker.goto(0,0) maker2.goto(0,0) maker3.goto(0,0) maker4.goto(0,0) turtle.exitonclick()
has comment: http://stackoverflow.com/comment/83099629
tagged with: tkinter
downvote count: 0
tagged with: turtle-graphics
score: 1
has comment: http://stackoverflow.com/comment/83100009
has comment: http://stackoverflow.com/comment/83106287
accepted answer: http://stackoverflow.com/a/48065163
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48065163
has comment: http://stackoverflow.com/comment/83100901
upvote count: 1
has comment: http://stackoverflow.com/comment/83105229
has comment: http://stackoverflow.com/comment/83100197

php
tags question: http://stackoverflow.com/q/48061766
tags question: http://stackoverflow.com/q/48088470
tags question: http://stackoverflow.com/q/48103435
tags question: http://stackoverflow.com/q/48122975
tag name: php
tags question: http://stackoverflow.com/q/48083608
tags question: http://stackoverflow.com/q/48031283
tags question: http://stackoverflow.com/q/48161770
tags question: http://stackoverflow.com/q/48159538
tags question: http://stackoverflow.com/q/48134258
tags question: http://stackoverflow.com/q/48058968
tags question: http://stackoverflow.com/q/48069491
type: Tag

http://stackoverflow.com/comment/83336709
score: 0
type: AnswerComment
has text: thanks Ron. I end up finding the data from the script. I just use json to extract that
type: Comment
comment on: http://stackoverflow.com/a/48160711

http://stackoverflow.com/comment/83079664
comment on: http://stackoverflow.com/q/48053527
type: QuestionComment
has text: Thanks for the quick responses. Looks like I need to dig deeper into LC to understand how GTZ can be implemented. Will do further reading for that. Thanks
score: 0
type: Comment

http://stackoverflow.com/comment/83232187
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48124381
has text: first i tried with anaconda

http://stackoverflow.com/comment/83414470
type: Comment
has text: You are very welcome. :-)
comment on: http://stackoverflow.com/a/48122597
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83305152
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48162880
has text: That's the one! Thank you so much for your assistance. The missing dot was all the difference.
type: Comment

http://stackoverflow.com/comment/83244684
has text: Thanks!!!, I need the output which is matched and which is not matched.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48129189
type: AnswerComment

http://stackoverflow.com/q/48046057
type: Question
has body: I'm currenty trying to figure out how to send packets to youtube with login credentials. I have cloned a git repository to my kali linux machine. It 'visits' a web page with different proxy IP's. Those proxies come from the TorBrowser. It can visit a page, but it only counts as a view if logged into youtube. Is there any way i can possibly do this? Thanks in advance. NOTE: The script works via packages. The browser isn't actively open.
tagged with: python
tagged with: youtube
has comment: http://stackoverflow.com/comment/83063439
score: 0
tagged with: git
type: UnansweredQuestion
has title: Send login packets to youtube
has comment: http://stackoverflow.com/comment/83063429
answer count: 0
tagged with: github
tagged with: linux

http://stackoverflow.com/a/58839235
downvote count: 0
has body: The options should be a list of Tuple[str, Any]. Below I add a a bit more complete server example. Though the question is mainly about the structure of the gRPC options to be passed (which was answered before already), the answers are linking to examples of client implementations (and therefore the channel calls might be a bit confusing). import grpc from concurrent import futures ... MAX_MESSAGE_LENGTH = 1024 * 1024 * 32 ... _server = grpc.server( futures.ThreadPoolExecutor(max_workers=4), options=[("grpc.max_receive_message_length", MAX_MESSAGE_LENGTH)], ) ... # add services to server _server.add_insecure_port("[::]:50051") _server.start() Client side sets options when creating a channel (grpc.insecure_channel, grpc.secure_channel). Server side sets options when creating a server (grpc.server).
upvote count: 2
answers question: http://stackoverflow.com/q/48170761
type: Answer
score: 2

http://stackoverflow.com/q/48017317
has title: Can ruamel.yaml encode an enum?
downvote count: 0
possible better answer: http://stackoverflow.com/a/48017484
favorite count: 0
has answer: http://stackoverflow.com/a/48017484
accepted answer: http://stackoverflow.com/a/48019045
tagged with: python
tagged with: ruamel.yaml
type: AnsweredQuestion
tagged with: enums
upvote count: 5
type: Question
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/48019045
has body: The following is not working for me, with Python 3.4.7, ruamel.yaml version 0.15.35: import sys import enum import ruamel.yaml from ruamel.yaml import yaml_object yaml = ruamel.yaml.YAML() @yaml_object(yaml) class Speed(enum.IntEnum): Reverse = 0 Neutral = 1 Low = 2 Drive = 3 Park = 999 print("Neutral:", repr(Speed.Neutral)) yaml.dump(Speed.Neutral, sys.stdout) I get a totally reasonable repr: Neutral: &lt;Speed.Neutral: 1&gt; but the .dump() raises: ruamel.yaml.representer.RepresenterError: cannot represent an object: &lt;enum 'Speed'&gt; If enum's are not supported, is there something I can do to extend the enum class I am using (or the subclass enum.IntEnum I have created), e.g. a dunder method?

http://stackoverflow.com/comment/83122984
has text: @juanpa.arrivillaga Ah, I see. Somewhat misunderstood the question initially. Your answer covers this specific problem quite well. I guess you could say my answer addresses the general question of accessing the previous and next element from an arbitrary list.
type: Comment
comment on: http://stackoverflow.com/a/48074653
score: 0
type: AnswerComment

http://stackoverflow.com/q/48018363
tagged with: python
has body: I am writing a function to speed up/down a given GIF (or .gifv) file, and save the resulting animation as an .mp4 file. I'm using the python imageio package (and its ffmpeg plugin) to do this - download the raw binary data from the gif, write each frame to an mp4, and set the fps of the mp4 to whatever. My code is - def changespeed(vid, mult): vid = vid.replace('.gifv', '.gif') data = urllib2.urlopen(vid).read() reader = imageio.get_reader(data, 'gif') dur = (float(reader.get_meta_data()['duration'])) oldfps = 1000.0 / (10 if dur == 0 else dur) writer = imageio.get_writer('output.mp4', fps=(oldfps*mult), quality=8.0) for frame in reader: writer.append_data(frame) writer.close() The problem is, at times the output colors will be heavily corrupted, and there doesn't seem to be any predictability. This happens with some gifs and doesn't happen with others. I have tried setting a high quality parameter in the writer but this doesn't help. Here is an example of a problematic GIF - Input: https://i.imgur.com/xFezNYK.gif Output: https://giant.gfycat.com/MelodicShimmeringBarb.mp4 I can see this issue locally in output.mp4, so the issue isn't with uploading to Gfycat. Is there anything I can do to avoid this behavior? Thanks.
has title: Imageio python converts GIF to MP4 incorrectly
has answer: http://stackoverflow.com/a/48041271
has comment: http://stackoverflow.com/comment/83006970
accepted answer: http://stackoverflow.com/a/48041271
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83014462
score: 0
answer count: 1
tagged with: python-imageio
tagged with: ffmpeg

http://stackoverflow.com/q/48092634
tagged with: python
score: -1
downvote count: 1
type: Question
upvote count: 0
answer count: 1
has body: i have got an array that i have got from vcenter using python pyVmomi module the array name is clustr_group_info ,you as seen below &gt;&gt;&gt; type(clustr_group_info) &lt;class 'pyVmomi.VmomiSupport.vim.cluster.GroupInfo[]'&gt; the content of the array look as below: print(clustr_group_info) (vim.cluster.GroupInfo) [ (vim.cluster.VmGroup) { dynamicType = &lt;unset&gt;, dynamicProperty = (vmodl.DynamicProperty) [], name = 'group1', userCreated = &lt;unset&gt;, uniqueID = &lt;unset&gt;, vm = (vim.VirtualMachine) [] }, (vim.cluster.HostGroup) { dynamicType = &lt;unset&gt;, dynamicProperty = (vmodl.DynamicProperty) [], name = 'group2', userCreated = &lt;unset&gt;, uniqueID = &lt;unset&gt;, host = (vim.HostSystem) [ 'vim.HostSystem:host-631607', 'vim.HostSystem:host-631791' ] }, i need to create a new dictionary for each iteration with "name" as key and "host" as a value i was not able to iterate over the array , in the regular way &gt;&gt;&gt; for i in clustr_group_info[0]: ... print(i) Traceback (most recent call last): File "", line 1, in TypeError: 'vim.cluster.VmGroup' object is not iterable
favorite count: 0
has title: iterating over array and creating new dictionary
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48092732

http://stackoverflow.com/q/48081968
has title: django: list transfer to template and to JS
tagged with: jquery
has answer: http://stackoverflow.com/a/48082392
answer count: 2
tagged with: http://stackoverflow.com/tag/html
possible better answer: http://stackoverflow.com/a/48082139
has answer: http://stackoverflow.com/a/48082139
tagged with: django
accepted answer: http://stackoverflow.com/a/48082392
tagged with: python
type: AnsweredQuestion
score: 0
has body: In Views.py i create a list variable - mortgages_counter.append(MonthlyPaymentAmount) it is transferred to .html template as: &lt;input id ='mortgages_counter' name='mortgages_counter' type='hidden' value='{{mortgages_counter}}'&gt; in JQuery (separate file i have to check if each element of this list is used). value is transferred to .js file as: var mortgages_counter = $('#mortgages_counter').val(); but according to console it was transferred as a string to Jquery - like ['1234','125'] and its length is 1 because of some reason, also check like access to index [0] gives - ' and [1] - 1 etc. how to operate with this list as with LIST and NOT a string?
type: Question

http://stackoverflow.com/q/48072971
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/48073121
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83119830
has body: I'm currently doing an assignment where I have to make an Apartment Registering program. I saved the apartment info like this in a textfile: ['B01','3','Master: TP_1','TP_2','TP_3'] ['B02','2','Master: TP_1','TP_2','TP_3'] ['B03','1','Master: TP_1','TP_2','TP_3'] ['B04','0','Master: TP_1','TP_2','TP_3'] ['B05','1','Master: TP_1','TP_2','TP_3'] ['B06','2','Master: TP_1','TP_2','TP_3'] ['B07','3','Master: TP_1','TP_2','TP_3'] ['B08','2','Master: TP_1','TP_2','TP_3'] ['B09','1','Master: TP_1','TP_2','TP_3'] ['B10','0','Master: TP_1','TP_2','TP_3'] Now, whenever a new student register to the apartment, I would like to add 1 to the number of occupants, which is the second value in the list. I would also like to replace the TP with student ID number. def apartmentRegister(): #REGISTERING APARTMENT AorB=input("Would you like to register into Apartment A or B? (A/B)") if AorB==("A") or AorB==("a"): room=input("Insert room number: ") f=open("Apartment_A.txt", "r") for line in f.readlines(): if not line or line =="\n": continue A_register=literal_eval(line) if A_register[-5]==(room): if A_register[-3]==("TP_1"): f=open("Apartment_A.txt", "a") TPagain=input("Please input your TP number: ") new=line.replace("TP_1",TPagain) f.write(new+"\n") print("You're all set") f.close() elif AorB==("B") or AorB==("b"): room=input("Insert room number: ") g=open("Apartment_B.txt", "r") for line in g.readlines(): if not line or line =="\n": continue B_register=literal_eval(line) if B_register[-5]==(room): if B_register[-3]==("Master: TP_1"): g=open("Apartment_B.txt", "a") TPagain=input("Please input your TP number: ") new=line.replace("TP_1",TPagain) g.write(new+"\n") print("You're all set") g.close() The whole code works... just the fact that I couldn't replace the values/text that I want to replace... Instead it adds a new line in the text file instead.
has comment: http://stackoverflow.com/comment/83119742
has comment: http://stackoverflow.com/comment/83119703
type: Question
has comment: http://stackoverflow.com/comment/83119634
score: 0
has answer: http://stackoverflow.com/a/48073121
answer count: 1
has title: Replacing a text in list within textfile
has comment: http://stackoverflow.com/comment/83119716

http://stackoverflow.com/comment/83292882
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48156643
has text: @n00b.exe , I don't want that you should accept my answer , please remove accept mark from there.
score: 0

http://stackoverflow.com/comment/83139881
comment on: http://stackoverflow.com/q/48082709
score: 0
type: Comment
type: QuestionComment
has text: @catbadger I hope the expected answer is "Define sentence. Define reverse."

http://stackoverflow.com/comment/83226101
comment on: http://stackoverflow.com/q/48110186
has text: This issue is off-topic for StackOverflow as it is about system administration more than about writing code. I suggest posting to https://mail.python.org/mailman/listinfo/python-list (mirrored as newsgroup gmane.comp.python.general at news.gmane.org). Subscription not required.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48046639
has comment: http://stackoverflow.com/comment/83064726
favorite count: 0
has comment: http://stackoverflow.com/comment/83068898
type: UnansweredQuestion
tagged with: sockets
has answer: http://stackoverflow.com/a/48065401
tagged with: python
tagged with: raw-ethernet
upvote count: 0
type: Question
tagged with: network-programming
linked to: http://stackoverflow.com/q/12177708
has title: Coding an Ethernet bridge from scratch
score: -1
tagged with: http://stackoverflow.com/tag/c
linked to: http://stackoverflow.com/q/9337545
has body: Question: How to I create a two-threaded bridge in code (not using brctl addbr br0 or some similar networking method, but writing the code) with one that takes Ethernet frames from ETH1 and puts them on ETH2, while the other takes them from ETH2 and puts them on ETH1 in a way that the two processes don't continuously read each other's Ethernet Frames? Details: I am trying to create a device that secures a connection between to systems (for a quite a few legacy systems that we cannot update) and in order to do that, we need to stick this device on the Ethernet port of the legacy system with another Ethernet port that is network facing. Basically a hardware man-in-the-middle. I can do almost everything I need with a standard Ethernet bridge and some fancy IPTables pre and post routing rules, but I wanted to try to implement some code that did this. I have tried this in C and in Python, and I just end up creating an infinite loop of Ethernet frames. For example in C, I can open a socket to ETH1 for reading in promiscuous mode: int open_eth_read_socket(char *interface_name) { int socket_fd; struct ifreq if_options; struct timeval timeout; timeout.tv_sec = 10; timeout.tv_usec = 0; // Get socket socket_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); if(socket_fd &lt; 0) exit(EXIT_ERROR); // Zero ifreq memset(&amp;if_options, 0, sizeof(struct ifreq)); // Put interface_name in strcpy(if_options.ifr_name, interface_name); // Set timout int ret = setsockopt(socket_fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&amp;timeout,sizeof(timeout)); if(ret &lt; 0) exit(EXIT_ERROR); // Bind this socket to the specified interface. ret = setsockopt(socket_fd, SOL_SOCKET, SO_BINDTODEVICE, interface_name, strlen(interface_name)); if(ret &lt; 0) exit(EXIT_ERROR); // Get flags if(ioctl(socket_fd, SIOCGIFFLAGS, &amp;ifopts) &lt; 0) exit(EXIT_ERROR); // Add promisc flag ifopts.ifr_flags |= IFF_PROMISC; // Set flags if(ioctl(socket_fd, SIOCSIFFLAGS, &amp;ifopts) &lt; 0) exit(EXIT_ERROR); return socke…
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/83162574
has text: I guess it returns `"nope"`? Do you know for sure `hand` contains that string? Have you tried: `if '5545' in hand: #do stuff` ?
comment on: http://stackoverflow.com/q/48093968
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48145249
accepted answer: http://stackoverflow.com/a/48146825
tagged with: opencv
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83270013
tagged with: pynput
tagged with: color-detection
type: Question
has comment: http://stackoverflow.com/comment/83268907
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83270336
has body: I am trying to work with a pen having green cap tip to navigate mouse cursor using webcam but how can I get the coordinates of cap image on screen so that I can give it as input to pyinput library move function. Thanks in advance. # Python program for Detection of a # specific color(green here) using OpenCV with Python import cv2 import numpy as np import time cap = cv2.VideoCapture(0) while (1): # Captures the live stream frame-by-frame _, frame = cap.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) lower_red = np.array([75, 50, 50]) upper_red = np.array([100, 255, 255]) mask = cv2.inRange(hsv, lower_red, upper_red) res = cv2.bitwise_and(frame, frame, mask=mask) cv2.imshow('frame', frame) cv2.imshow('mask', mask) cv2.imshow('res', res) **#code to output coordinates of green pen tip** k = cv2.waitKey(5) &amp; 0xff if k == 27: break cv2.destroyAllWindows() cap.release()
has comment: http://stackoverflow.com/comment/83270153
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83269848
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48146825
has title: How to get screen coordinates from color detection resultant area obtained from openCV with python?
upvote count: 2
has comment: http://stackoverflow.com/comment/83270813

http://stackoverflow.com/q/48051365
has answer: http://stackoverflow.com/a/48051419
accepted answer: http://stackoverflow.com/a/48051419
tagged with: python-3.x
upvote count: 0
has answer: http://stackoverflow.com/a/48052017
tagged with: selenium
tagged with: python
downvote count: 1
has title: selenium.common.exceptions.WebDriverException: Message: unknown error: Element ...is not clickable at point (x, y)
tagged with: selenium-webdriver
type: AnsweredQuestion
score: -1
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48052017
has body: I am trying to use Selenium to click on the search box. Here is my code: from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options import time chrome_options = Options() chrome_options.add_argument("--disable-infobars") chrome_options.add_argument("disable-infobars") chrome_options.add_argument("--kiosk") driver = webdriver.Chrome(executable_path="/mypath/chromedriver", chrome_options=chrome_options) thing_url = "https://www.target.com/" driver.get(thing_url) time.sleep(10) searchbox = driver.find_element_by_id("search") element_position = searchbox.location["y"] driver.execute_script("window.scroll(0, {})".format(element_position)) time.sleep(10) searchbox.click() I did a lot of Google search and applied the suggestion such as making the chrome browser full page before the click, or adding a delay before the click etc but none is working. Here is the full error message that I get: selenium.common.exceptions.WebDriverException: Message: unknown error: Element &lt;input id="search" name="searchTerm" class="form--control js-searchTerm" type="search" autocorrect="off" autocapitalize="off" autocomplete="off" aria-labelledby="searchLabel"&gt; is not clickable at point (955, 20). Other element would receive the click: &lt;label id="searchLabel" for="search" data-text="search" aria-hidden="true"&gt;...&lt;/label&gt; (Session info: chrome=63.0.3239.84) (Driver info: chromedriver=2.33.506106 (8a06c39c4582fbfbab6966dbb1c38a9173bfb1a2),platform=Mac OS X 10.12.6 x86_64) I am using Python 3.6 on a Mac. After the WebDriver opens Chrome I see a page like this: Please see the black bar on top of the search bar, but after a few seconds the black bar disappears and looks like search bar location moves. Please see below image:
tagged with: click
favorite count: 0

http://stackoverflow.com/comment/83295542
type: Comment
has text: @phd I see. I actually found that my Pipfile.lock had incorrect formatting. I changed it from `Django==2.0` to `Django = "==2.0"` and that seems to have fixed that problem. Now the error that I'm getting is `remote: Your Pipfile.lock (af8c37) is out of date. Expected: (3ca3d5)` Any idea how I'm supposed to update this?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48157475

http://stackoverflow.com/comment/83026553
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48028022
has text: @mcchucklezz Yeah the Fn keys and Ive seen some keyboards with dedicated ones like the corsair k70(although I don't know if they're just macros to press the keys).
score: 0

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

http://stackoverflow.com/q/48106707
duplicate of: http://stackoverflow.com/q/6294179
has body: Let's say I have a list list = [1,2,1,3,4,5] How do I find the index of both the 1 from the list using .index() function in python(or any other methods)?
favorite count: 0
accepted answer: http://stackoverflow.com/a/48106731
type: Question
tagged with: python
score: -1
has title: .index() show index of both similar elements from a list
downvote count: 1
answer count: 1
tagged with: indexing
has answer: http://stackoverflow.com/a/48106731
linked to: http://stackoverflow.com/q/6294179
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/comment/83214792
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48119142
has text: `class IIR2Filter` defines a class. You need to call filter on an instance of the class.
score: 0

http://stackoverflow.com/a/48072033
accepted answer of: http://stackoverflow.com/q/48071858
answers question: http://stackoverflow.com/q/48071858
type: AcceptedAnswer
downvote count: 0
has body: Try the below code: def oddTuples(aTup): out=() for i in range(len(aTup)): if i%2==0: out = out + (aTup[i],) return out aTup=(1,"hi",2,"hello",5) print oddTuples(aTup) Output when I ran the above code: (1, 2, 5)
type: Answer
has comment: http://stackoverflow.com/comment/83117756
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83117818

http://stackoverflow.com/comment/83283351
type: Comment
type: QuestionComment
has text: If it shows a response it certainly ran it. Why do you say it didn't? What do you expect to happen? Also, if the problem is with your python script, you should really show a relevant section of it.
comment on: http://stackoverflow.com/q/48152431
score: 0

http://stackoverflow.com/comment/83255301
score: 0
type: Comment
has text: Yes, because nested values. But if it working with samples and with real data not, then it is problem in data :(
type: AnswerComment
comment on: http://stackoverflow.com/a/48136273

http://stackoverflow.com/a/48017647
type: Answer
score: 2
has body: In my opinion for larger datasets, stack() becomes inefficient, let's use np.where to return index positions: i,j = np.where(df.values == df.values.max()) list((df.index[i].values.tolist()[0],df.columns[j].values.tolist()[0])) Output: [0, 'A'] Timings for larger datafames: df = pd.DataFrame(data=np.arange(10000).reshape(-1,5), columns=list('ABCDE')) np.where method &gt; %%timeit i,j = np.where(df.values == df.values.max()) &gt; list((df.index[i].values.tolist()[0],df.columns[j].values.tolist()[0])) 1000 loops, best of 3: 364 µs per loop Other stack methods &gt; %timeit df.mask(~(df==df.max().max())).stack().index.tolist() 100 loops, best of 3: 7.68 ms per loop &gt; %timeit df.stack().index[np.argmax(df.values)`] 10 loops, best of 3: 50.5 ms per loop &gt; %timeit list(df.stack().idxmax()) 1000 loops, best of 3: 1.58 ms per loop Even larger dataframe: df = pd.DataFrame(data=np.arange(100000).reshape(-1,5), columns=list('ABCDE')) Respectively: 1000 loops, best of 3: 1.62 ms per loop 10 loops, best of 3: 18.2 ms per loop 100 loops, best of 3: 5.69 ms per loop 100 loops, best of 3: 6.64 ms per loop
downvote count: 0
answers question: http://stackoverflow.com/q/48016629
upvote count: 2

http://stackoverflow.com/comment/83166654
has text: `Does in for a range really behave as in a list (O(n))?` In Python 3 definitely not. It is `O(1)`. In Python 2 it is `O(n)` since `range` returns a list.. I need to find a source for this though.
comment on: http://stackoverflow.com/q/48095978
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83149726
comment on: http://stackoverflow.com/q/48087010
score: 1
has text: comment on your current code - given that you know there is only one path, you probably want the code to stop calculating once it finds a path. Try `shortest_path` rather than `all_simple_paths`.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/55742461
upvote count: 2
answers question: http://stackoverflow.com/q/48018162
type: Answer
score: 2
downvote count: 0
has body: To work properly Sikuli need UI. This means the user should be logged in. Below are the steps on how to achieve that: Use Autologon Download and use Sysinternals Autologon You should redirect the Console in order to have UI anytime Create New Task in Task Scheduler Next in General tab check "Run with highest privileges" Next in Triggers tab add New trigger Next in New Trigger dialog select "On disconnect from user session" from "Begin the task" dropdown the press OK with default settings or with the users you will login usually Create a switch-ui.bat file with the following content in a folder switch-ui on Desktop echo ################################################### &gt;&gt; %USERPROFILE%\Desktop\rdc_switch_log.log date /t &gt;&gt; %USERPROFILE%\Desktop\rdc_switch_log.log time /t &gt;&gt; %USERPROFILE%\Desktop\rdc_switch_log.log timeout 3 query session &gt;&gt; %USERPROFILE%\Desktop\rdc_switch_log.log query session &gt; %localappdata%\log.txt findstr "rdp" %localappdata%\log.txt| findstr "Active" if %errorlevel%==0 ( echo You are in RDP session. Do nothing! &gt;&gt;%localappdata%\log.txt ) else ( tscon 1 /dest:console tscon 2 /dest:console tscon 3 /dest:console tscon 4 /dest:console ) Next in Actions tab Action Next in New Action dialog select "Start a program" from Action dropdown In Settings Program/script add the full path to your file "C:\Users\%yourUsers%\Desktop\switch-ui\switch-ui.bat" In Start in (optional) add path to your folder with your script "C:\Users\%yourUsers%\Desktop\switch-ui" Press OK and finish the Task Important: In order to test that it works. Get a video recorder Login on the machine from Remote Desktop Connection (RDC) Start video Close RDC Wait 2 mins Connect Again Stop Video Watch the video You should have a black video recorded only when you Close RDC and when you connect back with RDC for a few seconds it depends on how fast is your machine.

http://stackoverflow.com/q/48037799
upvote count: 5
downvote count: 0
linked to: http://stackoverflow.com/q/23915275
has answer: http://stackoverflow.com/a/50246619
tagged with: python
has title: Bokeh datetime axis, control of minor ticks
type: AnsweredQuestion
tagged with: bokeh
type: Question
answer count: 2
score: 5
possible better answer: http://stackoverflow.com/a/50246619
accepted answer: http://stackoverflow.com/a/48045458
has body: I have a web app that serves Bokeh plots (uses Bokeh v0.12.7). The x-axis is datetime, displaying a user-defined number of days (the date range defaults to 31 days). Without defining any tick parameters in Bokeh, the number of major ticks defaults to 5, as shown on the live web app here: https://btac-web-plots.herokuapp.com/avyview?style=snowpacktracker I want to display minor ticks for every day between the major ticks. I tried the following, which allows for any date range length, and specifies a major tick every 5th day (start and end are Pandas Datetime indices): num_days = ((end - start) / np.timedelta64(1, 'D')).astype(int) fig.xaxis.ticker = DaysTicker( days = np.arange(1, num_days, 5), num_minor_ticks = 4 ) This correctly displays major ticks every 5th day, but minor ticks are not displayed. Another potential solution might be to plot major ticks every day, and then set tick labels to invisible for days except every 5th day (unsure how to implement this...). What is the best method to display daily minor ticks on these plots? Here is a section of my plotting code (including DaysTicker), using the first panel as an example: fig = figure( title="New Snow, SWE, Snow Depth, and Settlement", name="newsnow_extra_fig", x_axis_type="datetime", y_axis_label='HN24 / SWE (in)', width=width, height=height2, tools=tools, toolbar_sticky=False, logo=None ) fig.y_range = Range1d(-12, 30) fig.extra_y_ranges = {"Depth": Range1d(start=-72, end=180)} fig.add_layout(LinearAxis(y_range_name="Depth", axis_label='HS (in)' ), 'right') fig.yaxis.axis_label_standoff = 5 num_days = ((end - start) / np.timedelta64(1, 'D')).astype(int) fig.xaxis.ticker = DaysTicker( days=np.arange(1,num_days,5), num_minor_ticks=4 ) newcds, newcds_sums = create_newsnow_extra_cds(df, 'mid', start, end) dline = fig.line(source=newcds, x='Date', y='depth', line_color="blue", line_width=2, line_alpha=0.5, legend="snow depth (HS)", name="depthline", y_range_name='Depth', ) nsbars = fig.vbar(source=newcds, x='n…
tagged with: datetime
favorite count: 0
has answer: http://stackoverflow.com/a/48045458

http://stackoverflow.com/q/48156059
has title: Finding duplicate rows in Pandas, where order of column values don't matter
upvote count: 3
tagged with: python
has answer: http://stackoverflow.com/a/48156130
type: AnsweredQuestion
score: 3
type: Question
tagged with: numpy
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48156130
favorite count: 0
has answer: http://stackoverflow.com/a/48156111
accepted answer: http://stackoverflow.com/a/48156111
linked to: http://stackoverflow.com/q/44998223
tagged with: pandas
has body: Sample dataframe: import pandas as pd data = data = { 'num1': [1,2,3,4,5], 'num2': [1,1,2,3,1], 'num3': [5,4,3,2,1]} df = pd.DataFrame(data) print(df.head()) &gt;&gt;&gt; df.head() num1 num2 num3 0 1 1 5 #dups with row 4 1 2 1 4 2 3 2 3 3 4 3 2 4 5 1 1 #dups with row 1 In this sample dataframe, I'm trying to extract the first row and last row, as their contents are duplicates of each other (1,1,5) The code below will only find duplicated rows if order of values are the same (It seems): dups =df[df.duplicated(subset=None, keep='first')] thus is resulting in a empty dataset. Thank you.

http://stackoverflow.com/q/48159911
has body: I'm in a bit over my head here and have never worked with dll's before so hopefully my question makes sense. I'm trying to use a C# dll that has a bunch of different classes in it. I've read other questions on here that show example code such as: import ctypes lib = ctypes.cdll.LoadLibary('pathToDLL') lib.foo() I understand that much. I haven't been able to figure out how to use methods that are in the classes in the dll if that makes sense. So if the dll contains a class called "Foo" with a method "bar" how do I call bar using ctypes? Also is ctypes the best way to try to access this dll or should I be using something else?
upvote count: 2
tagged with: python.net
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83299445
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/48500900
downvote count: 0
has title: How to access methods from C# dll using ctypes?
type: Question
tagged with: c#
tagged with: dll
tagged with: .net

http://stackoverflow.com/comment/94419799
has text: This is a cool solution. I feel like there has to be a more legitimate way to do it though
comment on: http://stackoverflow.com/a/48199502
type: Comment
score: 1
type: AnswerComment

paramiko
tags question: http://stackoverflow.com/q/48068133
tag name: paramiko
tags question: http://stackoverflow.com/q/48061346
tags question: http://stackoverflow.com/q/48166826
type: Tag
tags question: http://stackoverflow.com/q/48037305
tags question: http://stackoverflow.com/q/48170735
tags question: http://stackoverflow.com/q/48112246
tags question: http://stackoverflow.com/q/48133559

http://stackoverflow.com/comment/83059916
has text: And going back further in time, https://stackoverflow.com/questions/16496017/typeerror-when-using-matplotlibs-strpdate2num-with-python-3-2
comment on: http://stackoverflow.com/q/48042923
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83077387
comment on: http://stackoverflow.com/q/48052487
type: Comment
has text: Well, potentially a super-quick change is to make `adjs` a `set()` before the check for `in`, if possible.
type: QuestionComment
score: 0

http://stackoverflow.com/q/48129155
downvote count: 0
has comment: http://stackoverflow.com/comment/83810051
has body: I have a Django project that allows users to create their own Projects and add multiple Skills to each Project. I am trying to write a view that will allow me to display the name of each Skill as well as the Count of that Skill for all of that particular user Profile's Projects that are published. For example, if a user has three projects where they've added the Skill "HTML" I'd like to show HTML (3) on their Profile, and so on. Below is my current code which mostly works however it displays the count for that Skill from ALL user projects and not the specific user whose profile is being viewed. Models: #accounts/models.py class Profile(models.Model): #... skills = models.ManyToManyField('skills.skill') #projects/models.py class Project(models.Model): user = models.ForeignKey(User) #... published = models.BooleanField(default=False) skills = models.ManyToManyField('skills.skill') #... #skills/models.py class Skill(models.Model): name = models.CharField(max_length=100) Views: #accounts/views.py def profile(request, username): user = get_object_or_404(User, username=username) skill_counts = Skill.objects.annotate(num_projects=Count('project')).filter(project__user_id=user.id).order_by('-num_projects')[:10] return render(request, 'accounts/profile.html', { 'user': user, 'skill_counts': skill_counts, }) Template: #accounts/templates/accounts/profile.html {% for skill in skill_counts %} &lt;div class="skill-container"&gt; &lt;div class="label-skill"&gt;{{ skill.name }}&lt;/div&gt; &lt;div class="label-skill-count"&gt; {{skill.project_set.count}}&lt;/div&gt; &lt;/div&gt; {% endfor %} Any help here would be much appreciated. Thanks in advance.
has title: Django aggregation multiple filters
has comment: http://stackoverflow.com/comment/83235546
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48129409
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/33775011
accepted answer: http://stackoverflow.com/a/48129409
type: Question

http://stackoverflow.com/comment/134739396
score: 0
type: AnswerComment
has text: Can you elaborate? What is a "broken import"?
comment on: http://stackoverflow.com/a/76396232
type: Comment

http://stackoverflow.com/q/48148531
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83275297
has comment: http://stackoverflow.com/comment/83275268
has comment: http://stackoverflow.com/comment/83290650
tagged with: argparse
has body: Is it possible to add an argument to another one using argparse? If so, how would one implement this. The following example shows what I'm actually looking for: --plt &lt;some_file&gt; -opt &lt;some_number&gt; Here, --plt is an argument with several options. -opt is hence depending on --plt. So if a user provides --plt as argument, he/she has to provide -opt, too. -opt alone is also not a valid argument to the script. parser = argparse.ArgumentParser() parser.add_argument('--test', '-test', help='performs classification test') parser.add_argument('--plt','-plt', help='plots loss function') parser.add_argument('--version', '-version&gt;', action='version', version='%(prog)s 0.1')
has comment: http://stackoverflow.com/comment/83275319
type: Question
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/83275666
has title: Python: Adding Arguments to Arguments using Argparse
has comment: http://stackoverflow.com/comment/83275541
answer count: 0

http://stackoverflow.com/comment/83186260
type: Comment
has text: What about the response body of the request?
comment on: http://stackoverflow.com/a/48102717
score: 0
type: AnswerComment

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/48064058
tags question: http://stackoverflow.com/q/48056574
type: Tag
tags question: http://stackoverflow.com/q/48065020
tags question: http://stackoverflow.com/q/48051100
tags question: http://stackoverflow.com/q/48172640
tags question: http://stackoverflow.com/q/48123648
tags question: http://stackoverflow.com/q/48054053
tags question: http://stackoverflow.com/q/48022826
tags question: http://stackoverflow.com/q/48017143
tags question: http://stackoverflow.com/q/48130844
tags question: http://stackoverflow.com/q/48046391
tags question: http://stackoverflow.com/q/48065772
tags question: http://stackoverflow.com/q/48075861
tags question: http://stackoverflow.com/q/48035785
tags question: http://stackoverflow.com/q/48110167
tags question: http://stackoverflow.com/q/48057309
tags question: http://stackoverflow.com/q/48100159
tag name: csv
tags question: http://stackoverflow.com/q/48089167
tags question: http://stackoverflow.com/q/48162287
tags question: http://stackoverflow.com/q/48161293
tags question: http://stackoverflow.com/q/48042483
tags question: http://stackoverflow.com/q/48069000
tags question: http://stackoverflow.com/q/48057296
tags question: http://stackoverflow.com/q/48151137
tags question: http://stackoverflow.com/q/48116380
tags question: http://stackoverflow.com/q/48079783
tags question: http://stackoverflow.com/q/48067514
tags question: http://stackoverflow.com/q/48115455
tags question: http://stackoverflow.com/q/48055372
tags question: http://stackoverflow.com/q/48047935
tags question: http://stackoverflow.com/q/48038838
tags question: http://stackoverflow.com/q/48066971
tags question: http://stackoverflow.com/q/48027076
tags question: http://stackoverflow.com/q/48043313
tags question: http://stackoverflow.com/q/48065797
tags question: http://stackoverflow.com/q/48136981
tags question: http://stackoverflow.com/q/48103485
tags question: http://stackoverflow.com/q/48144067
tags question: http://stackoverflow.com/q/48135246
tags question: http://stackoverflow.com/q/48047024
tags question: http://stackoverflow.com/q/48145981
tags question: http://stackoverflow.com/q/48160623
tags question: http://stackoverflow.com/q/48125961
tags question: http://stackoverflow.com/q/48021280
tags question: http://stackoverflow.com/q/48052647
tags question: http://stackoverflow.com/q/48064446
tags question: http://stackoverflow.com/q/48077401
tags question: http://stackoverflow.com/q/48158474
tags question: http://stackoverflow.com/q/48047719
tags question: http://stackoverflow.com/q/48054030
tags question: http://stackoverflow.com/q/48019381
tags question: http://stackoverflow.com/q/48116067
tags question: http://stackoverflow.com/q/48158534
tags question: http://stackoverflow.com/q/48152058
tags question: http://stackoverflow.com/q/48170960
tags question: http://stackoverflow.com/q/48037627
tags question: http://stackoverflow.com/q/48123819
tags question: http://stackoverflow.com/q/48061554
tags question: http://stackoverflow.com/q/48056394
tags question: http://stackoverflow.com/q/48159149
tags question: http://stackoverflow.com/q/48106827
tags question: http://stackoverflow.com/q/48069497
tags question: http://stackoverflow.com/q/48024559
tags question: http://stackoverflow.com/q/48017105
tags question: http://stackoverflow.com/q/48154787
tags question: http://stackoverflow.com/q/48111034
tags question: http://stackoverflow.com/q/48025530
tags question: http://stackoverflow.com/q/48055337
tags question: http://stackoverflow.com/q/48069555
tags question: http://stackoverflow.com/q/48126332
tags question: http://stackoverflow.com/q/48085319
tags question: http://stackoverflow.com/q/48160819
tags question: http://stackoverflow.com/q/48099095
tags question: http://stackoverflow.com/q/48090535
tags question: http://stackoverflow.com/q/48090213
tags question: http://stackoverflow.com/q/48025614
tags question: http://stackoverflow.com/q/48135525
tags question: http://stackoverflow.com/q/48030556

http://stackoverflow.com/comment/83079956
comment on: http://stackoverflow.com/a/48053531
type: AnswerComment
has text: What a silly mistake of me, thanks! Changing to: for i in month_no: month_no = MonthDict[month_no] results in "TypeError: unhashable type: 'numpy.ndarray'"
score: 0
type: Comment

http://stackoverflow.com/q/48163020
type: UnansweredQuestion
tagged with: python
has body: I make use of uwsgi, django and django-rest-framework to develop one application. I introduced one class variable in renderer class, this variable will be fill as one part of response. the problem seems likes as following: class xxxRenderer(xxxBase) response_pb_msg = obj # it's one instance of protobuf message def render(): if True: self.response_pb_msg.items = [] else: self.response_pb_msg.retCode = 100 self.response_pb_msg.otherXXXX = xxxx In django logger handler, I access this class variable again like following: xxxRenderer.response_pb_msg.ParseFromString(body) after the first response, this class variable 'response_pb_msg' only has one property "retCode" but the second response, it has three properties "retCode", "otherXXXX " and "items " it's strange, the second response contain all content which was exist in the first response. after a time, I re-wrote this class like following: class xxxBaserender(xxRender) def __init__(): if self.response_pb_msg_cls is not None and isinstance(self.response_pb_msg_cls, GeneratedProtocolMessageType): self.response_pb_message = self.response_pb_msg_cls() class xxxRenderer(xxxBaserender) response_pb_msg_cls = msgName # the class of protobuf message theoretically, the second class is ok. I tested, didn't duplicate that question. Let's return to where we started Every request finisehd, all resoure should be clean. but I'm very puzzled with that problem, it seems that class variable not been released in uwsgi progress after response return. I read “PEP 3333”， didn't get any valuable information. I think I didn't fully understand class variaable, wsgi and web processing flow in python. anyone can help me to understand this problem? thanks vey much.
tagged with: uwsgi
type: Question
has comment: http://stackoverflow.com/comment/83315486
tagged with: django-rest-framework
linked to: http://stackoverflow.com/q/31937746
has title: class variable was caches in next request when use django-rest-framework renderer
has comment: http://stackoverflow.com/comment/83339942
score: 0
answer count: 0

http://stackoverflow.com/comment/83327427
has text: yes, if you only want to get the IP, that how socket works, the server has to know the address of the client to transmit data back.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48164343

http://stackoverflow.com/q/48156164
has comment: http://stackoverflow.com/comment/83291478
accepted answer: http://stackoverflow.com/a/48156413
has comment: http://stackoverflow.com/comment/83291850
score: 0
has answer: http://stackoverflow.com/a/48156407
answer count: 3
has body: I have managed to compile two lists of IP addresses. used and unused ips as such unused_ips = ['172.16.100.0/32', '172.16.100.1/32', '172.16.100.2/32', '172.16.100.3/32', '172.16.100.4/32', '172.16.100.5/32', '172.16.100.6/32', '172.16.100.7/32', '172.16.100.8/32', '172.16.100.9/32'...] used_ips = ['172.16.100.1/32','172.16.100.33/32'] what I want to be able to do now is compare these lists and return the next free IP. in the above example the next ip would be 172.16.100.2/32, until it handed out all of those from 1 to 32 then it would hand out 34. im not sure where to begin with this, I can convert these to IPv4Network objects if there is something built in for this but I couldn't find anything in documentation Thanks
has comment: http://stackoverflow.com/comment/83291419
has title: Python compare two lists of IPs and return the lowest to 0 IP entry in list?
possible better answer: http://stackoverflow.com/a/48156584
has answer: http://stackoverflow.com/a/48156413
has answer: http://stackoverflow.com/a/48156584
tagged with: python
tagged with: ip-address
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83291547
type: Question

http://stackoverflow.com/q/48150950
has body: I have a complex piece of F# client code which successfully accesses some webservices. The specification of the project has now changed and I wish to manipulate the data extracted from the webservices in python, instead of wasting time and energy on writing a python client I would like to access the F# code from python. I know that this is possible if the client code was written in C# or c, but how do I do this with F#? I cant find any reference of anyone doing this on the internet. Anyone have any ideas?
score: 1
has comment: http://stackoverflow.com/comment/83280893
type: Question
has comment: http://stackoverflow.com/comment/83280963
favorite count: 0
has comment: http://stackoverflow.com/comment/83925305
tagged with: python
linked to: http://stackoverflow.com/q/11371448
has comment: http://stackoverflow.com/comment/83281290
tagged with: client
has title: Calling F# from python
has comment: http://stackoverflow.com/comment/83283376
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/83281506
tagged with: f#
has comment: http://stackoverflow.com/comment/83366041
has comment: http://stackoverflow.com/comment/83283471

plotly
tags question: http://stackoverflow.com/q/48159844
tags question: http://stackoverflow.com/q/48082826
type: Tag
tags question: http://stackoverflow.com/q/48082138
tags question: http://stackoverflow.com/q/48109418
tags question: http://stackoverflow.com/q/48091492
tags question: http://stackoverflow.com/q/48085374
tags question: http://stackoverflow.com/q/48024068
tag name: plotly
tags question: http://stackoverflow.com/q/48098331
tags question: http://stackoverflow.com/q/48136811
tags question: http://stackoverflow.com/q/48064631
tags question: http://stackoverflow.com/q/48037284
tags question: http://stackoverflow.com/q/48131484

http://stackoverflow.com/q/48053470
type: Question
accepted answer: http://stackoverflow.com/a/48053613
downvote count: 0
answer count: 3
has title: Why don't these two table join in Python?
tagged with: pandas
score: 2
has body: I'm using the below code to import these sample Kaggle data sets for Python pratice): # importing everything import pandas as pd df_events = pd.DataFrame() df_ginf = pd.DataFrame() df_events = pd.read_csv('./events.csv') df_ginf = pd.read_csv('./ginf.csv') # creating a match table eventsList = pd.Series(['On Target', 'Off Target', 'Blocked', 'Hit the Bar']) eventListKey = pd.Series(['1', '2', '3', '4']) eventsMatchTable = pd.concat([eventListKey, eventsList], axis = 1) eventsMatchTable.columns = ['eventKey', 'eventName'] eventsMatchTable['eventKey'] = eventsMatchTable['eventKey'].astype(int) # trimming the initial dataframe down to something more manageable df_eventsPlayer = pd.DataFrame() df_eventsPlayer = df_events'player', 'event_team', 'opponent', 'shot_place', 'shot_outcome', 'is_goal' df_eventsPlayer = df_eventsPlayer.dropna() df_eventsPlayer['shot_outcome'] = df_eventsPlayer['shot_outcome'].astype(int) # attempting the 'merge', here is where the error occurs df_eventPlayerFinal = pd.DataFrame() df_eventPlayerFinal = pd.merge(df_eventsPlayer, eventsMatchTable, how = 'left', on = ['shot_outcome','eventKey']) df_eventPlayerFinal The error says, roughly: KeyError: 'shot_outcome' # validate the merge keys dtypes. We may need to coerce Because the columns I want to merge on are both int, this error does not make sense to me. What am I missing?
favorite count: 0
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/48053613
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48053953
possible better answer: http://stackoverflow.com/a/48053694
has answer: http://stackoverflow.com/a/48053694

http://stackoverflow.com/comment/83043109
type: QuestionComment
has text: Yes, and put all the code that reproduces the window, I need you to provide a [mcve]
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48036069

http://stackoverflow.com/a/48038185
has body: Thanks to ayhan's help I have already got the answer I needed. The equivalent in Pandas to this R data.table code: df[, new_column := column2/(1:.N), by=(column1)] is: df["new_column"] = (df['column2']) / (df.groupby('column1')['column2'].cumcount()+1)
answers question: http://stackoverflow.com/q/48037945
score: 0
type: Answer

http://stackoverflow.com/comment/83265067
has text: ah. in that case, the root is simplesocial.
comment on: http://stackoverflow.com/q/48142723
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48058185
type: AnsweredQuestion
tagged with: amazon-product-api
has body: The same method works; if I get rid of a specific value of a key. I have a field called 'Feature' which helps me get items descriptions from amazon; I've made sure it works correctly by printing. It's a plain string; I've made sure and double checked it. Using type() This is how I'm setting flask session dictionary: app = Flask(__name__) app.config['SECRET_KEY'] = 'yo' @app.route('/', methods=['GET','POST']) def index(): authenticated_url = authenticate(Availability='Available',Operation='ItemSearch',Keywords=str(query),SearchIndex='Electronics', ResponseGroup='ItemAttributes') product = authenticated_url['ItemSearchResponse']['Items']['Item'] arr = [] for items in product: main_dictionary = {} sub_dictionary = {} sub_dictionary['price'] = items['ItemAttributes']['FormattedPrice'] featureLists = items['ItemAttributes']['Feature'] emptyFeatureStr = ' ' for items in featureLists: emptyFeatureStr += items sub_dictionary['Feature']=emptyFeatureStr main_dictionary[items['ASIN']]=sub_dictionary # I construct a dictionary whose key is ASIN number and values arr.append(main_dictionary) #I append my new dictionary into an array. session['searchResults']=arr print session['searchResults'] #Here I try to set the flask session dictionary key to searchResults # Verfied/made sure that this is set correct; up until here everything works; my dictionary is set as expected. ISSUE: @app.route('/profile/&lt;asin&gt;', methods=['GET','POST']) def profilePage(asin): return str(session.get('searchResults') When I do that it gives me null. The moment I get rid of feature it seems to be working as expected... like the price is displayed and amazon calls; and flask session is set properly. I have no idea the momment I set feature key/value it stops working. This is an example of what is being passed into feature TRUVIEW 0.45x WIDE ANGLE LENS - CAPTURE 45% MORE PICTURE WITH EVERY SNAP: Shoot stunning photos of people, pets, travel scenery, landscapes, architecture, selfies and more. NO DARK C…
accepted answer: http://stackoverflow.com/a/48067919
type: Question
has answer: http://stackoverflow.com/a/48067919
tagged with: flask
score: 0
answer count: 1
has title: Flask session dictionary get reset
tagged with: python

http://stackoverflow.com/q/48151137
score: 1
has comment: http://stackoverflow.com/comment/83280959
tagged with: mysql
upvote count: 1
has title: URL List Comparison for Redirection
type: Question
has comment: http://stackoverflow.com/comment/83280675
has comment: http://stackoverflow.com/comment/83283410
has comment: http://stackoverflow.com/comment/83283060
has comment: http://stackoverflow.com/comment/83282310
tagged with: bash
has answer: http://stackoverflow.com/a/48152653
has comment: http://stackoverflow.com/comment/83281057
answer count: 1
downvote count: 0
tagged with: .htaccess
favorite count: 0
has body: I was given 2 CSV files, with upwards of 3000+ URL's contained in each. What I am tasked with is to create a .htaccess "redirection" chunk from "old site" to "new site", and rather than go through and manually compare them, I thought I could simply either try a bash/python script, or import them into MySQL to do the comparisons. So, in Bash I tried the following code: #!/bin/bash awk 'BEGIN{FS=OFS="/"} {gsub(/\/$/, ""); $NF=tolower($NF)} NR==FNR{a[$NF]=$0; next} $NF in a {print a[$NF] " " $0 &gt; "combined.csv"}' oldsite.csv newsite.csv However, it returns me an empty "combined.csv", so I thought maybe "Python"... but alas, I know very little about Python, so then I thought MySQL... if I just import each CSV into a new table, I could run a comparison SQL statement and dump the results out to a 2 column new table... alas again, I am not really sure where to begin with the comparison, figuring on a LIKE comparison statement, but what I am wondering here is what would the "best" (meaning most accurate comparison) method be... and if Python, how? CSV SAMPLES NEW URLS "new-url" "/product/dangle-hoop-earrings-for-girls-with-cz-and-heart-dangle-in-14k-gold/" "/product/dangle-hoop-earrings-for-girls-with-cz-and-butterfly-dangle-in-14k-gold/" "/product/petite-lever-back-earrings-for-little-girls-in-14k-yellow-gold-with-blue-topaz-high-end-childrens-earrings/" OLD URLS "old-url" "/product/0903-HUGGIEGK/Dangle-Hoop-Earrings-for-Girls-with-CZ-and-Heart-Dangle-in-14K-Gold/" "/product/0954-HUGGIEGK/Dangle-Hoop-Earrings-for-Girls-with-CZ-and-Butterfly-Dangle-in-14K-Gold/" "/product/10049Y4JBT/Petite-Lever-Back-Earrings-for-Little-Girls-in-14K-Yellow-Gold-with-Blue-Topaz---High-End-Childrens-Earrings/" EXPECTED COMBINED "old-url", "new-url" "/product/0903-HUGGIEGK/Dangle-Hoop-Earrings-for-Girls-with-CZ-and-Heart-Dangle-in-14K-Gold/", "/product/dangle-hoop-earrings-for-girls-with-cz-and-heart-dangle-in-14k-gold/" "/product/0954-HUGGIEGK/Dangle-Hoop-Earrings-for-Girls-with-CZ-and-But…
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/83281096
accepted answer: http://stackoverflow.com/a/48152653
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83280674

http://stackoverflow.com/comment/83131266
type: QuestionComment
score: 0
has text: The code will be consistent. My list is already populated with a number of classes (different from the template above), and I would like to populate this list with classes rather than the values of `property`
comment on: http://stackoverflow.com/q/48078656
type: Comment

http://stackoverflow.com/comment/83098770
comment on: http://stackoverflow.com/q/48062487
has text: See [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time).
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48136684
type: Answer
has body: There's nothing wrong with your installation. There is a problem in the tests, which surfaced recently (see https://github.com/lballabio/QuantLib-SWIG/issues/89). The problem was fixed (https://github.com/lballabio/QuantLib-SWIG/pull/90) but the fix still hasn't made into a release, hence the errors you're seeing. You can go ahead and install the module you built.
answers question: http://stackoverflow.com/q/48127708
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/83252659
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48127708

http://stackoverflow.com/comment/83329934
type: QuestionComment
has text: What kind of data is in the array? Small integers, big integers, floating point or other? Also what is the usual shape of the array?
comment on: http://stackoverflow.com/q/48173041
score: 0
type: Comment

http://stackoverflow.com/q/48107155
favorite count: 0
has title: turtle.textinput giving "AttributeError" instead of opening "turtle graphics"
tagged with: turtle-graphics
has comment: http://stackoverflow.com/comment/83191007
type: Question
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48121884
has comment: http://stackoverflow.com/comment/107891527
score: 0
has comment: http://stackoverflow.com/comment/83190762
linked to: http://stackoverflow.com/q/1250103
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83190680
has body: I am not so new to Python that this is going to be a syntax error. I have never actually messed with turtle graphics that much though, so this was totally new to me. Anyway I was trying to make a turtle graphic spiral that would take input from a user(strings, numbers etc.) and turn it into a neat spiral. anyway I got this error message when ran I the code. Please note I am using Python 3. Traceback (most recent call last): File "spiral_my_name.py", line 6, in &lt;module&gt; your_name = turtle.textinput("Enter your name", "What is your mame?") AttributeError: 'module' object has no attribute 'textinput' that was the error message I got from this syntax: import turtle t = turtle.Pen() turtle.bgcolor('black') colors = ['purple', 'pink', 'green', 'blue'] your_name = turtle.textinput("Enter your name", "What is your name?") for x in range(100): t.pencolor(colors[x%4]) t.penup() t.forward(x*4) t.pendown() t.write(your_name, font = ("Arial", int ( (x+4) / 4), "bold") ) t.left(92) Now I don't personally use Python for this a whole lot, so I was just going to let this go, but this is an Attribute error. I sort of want to know why this is happening.
has comment: http://stackoverflow.com/comment/83190888
has comment: http://stackoverflow.com/comment/83190215
has comment: http://stackoverflow.com/comment/83190707
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/60972649
linked to: http://stackoverflow.com/q/41674910

http://stackoverflow.com/a/48120505
answers question: http://stackoverflow.com/q/48120361
score: 0
type: Answer
has body: The most basic solution would be something like while True: send_message() time.sleep(60) If send_message() takes a while and you want more accurate timing, you could do something like while True: start_time = time.time() send_message() elapsed_time = time.time() - start_time time.sleep(60 - elapsed_time) That version tries to actually run it every 60 seconds by subtracting the execution time of send_message() from the sleep, so that it starts executing every 60 seconds. If you want very accurate timing, you're going to need a more advanced technique.

parsing
tags question: http://stackoverflow.com/q/48027655
tags question: http://stackoverflow.com/q/48127309
tags question: http://stackoverflow.com/q/48024964
tags question: http://stackoverflow.com/q/48080899
tags question: http://stackoverflow.com/q/48037716
tags question: http://stackoverflow.com/q/48153907
tags question: http://stackoverflow.com/q/48131072
tags question: http://stackoverflow.com/q/48116316
tag name: parsing
tags question: http://stackoverflow.com/q/48164539
tags question: http://stackoverflow.com/q/48028758
tags question: http://stackoverflow.com/q/48168885
type: Tag
tags question: http://stackoverflow.com/q/48065611
tags question: http://stackoverflow.com/q/48143542
tags question: http://stackoverflow.com/q/48111602
tags question: http://stackoverflow.com/q/48034656
tags question: http://stackoverflow.com/q/48068107
tags question: http://stackoverflow.com/q/48086330
tags question: http://stackoverflow.com/q/48136101
tags question: http://stackoverflow.com/q/48095517
tags question: http://stackoverflow.com/q/48125988
tags question: http://stackoverflow.com/q/48030583

http://stackoverflow.com/q/48035341
type: AnsweredQuestion
tagged with: client-library
score: 1
possible better answer: http://stackoverflow.com/a/48035957
upvote count: 1
has comment: http://stackoverflow.com/comment/83104575
has answer: http://stackoverflow.com/a/48035957
type: Question
has comment: http://stackoverflow.com/comment/83099410
tagged with: firebird
tagged with: dll
tagged with: firebird-embedded
answer count: 2
has answer: http://stackoverflow.com/a/48207096
has comment: http://stackoverflow.com/comment/83041197
downvote count: 0
has title: Firebird embedded installation issue: library could not be determined
has comment: http://stackoverflow.com/comment/83277703
has comment: http://stackoverflow.com/comment/83277585
favorite count: 0
has comment: http://stackoverflow.com/comment/83098875
has body: I've been writing a small Python application that opens a Firebird database. To achieve this goal I'm using Firebird embedded 2.5.7.27050, 64 bit. Although, whenever I try to connect to the DB file with Python, I get the following error: Traceback (most recent call last): File "C:\Matteo\CMakeR\initApp.py", line 36, in &lt;module&gt; connection = connectToDB(path) File "C:\Matteo\CMakeR\initApp.py", line 10, in connectToDB charset='WIN1252' File "C:\Program Files\Python36\lib\site-packages\fdb\fbcore.py", line 682, in connect load_api(fb_library_name) File "C:\Program Files\Python36\lib\site-packages\fdb\fbcore.py", line 181, in load_api setattr(sys.modules[__name__],'api',fbclient_API(fb_library_name)) File "C:\Program Files\Python36\lib\site-packages\fdb\ibase.py", line 1398, in __init__ raise Exception("The location of Firebird Client Library could not be determined.") Exception: The location of Firebird Client Library could not be determined. &gt;&gt;&gt; It seems that the FB Client is not installed properly. However I followed very carefully the installation guide inside the doc folder. Here's my app folder: 04/01/2018 15:11 &lt;DIR&gt; . 04/01/2018 15:11 &lt;DIR&gt; .. 04/01/2018 14:57 133 aliases.conf 03/01/2018 14:20 0 CMakeR.conf 02/01/2018 13:40 2.480 DB in chiaro.odb 04/01/2018 14:57 &lt;DIR&gt; doc 30/12/2017 17:32 191 editXLS.py 30/12/2017 17:24 23.032 Export.xlsx 04/01/2018 14:57 5.664.256 fbclient.dll 04/01/2018 14:57 5.664.256 fbembed.dll 04/01/2018 14:46 5.199.849 Firebird-2.5.7.27050-0_x64_embed.zip 04/01/2018 14:57 27.661 firebird.conf 04/01/2018 14:57 149.440 firebird.msg 04/01/2018 14:57 5.664.256 gds32.dll 04/01/2018 14:57 8.192 ib_util.dll 04/01/2018 14:57 1.558.016 icudt30.dll 04/01/2018 14:57 575.488 icuin30.dll 04/01/2018 14:57 935.936 icuuc30.dll 04/01/2018 14:57 26.023 IDPLicense.txt 04/01/2018 15:09 1.583 initApp.py 04/01/2018 14:57 &lt;DIR&gt; intl 04/01/2018 14:57 24.301 IPLicense.txt 04/01/2018 14:57 524 Microsoft.VC80.CRT.manifest 30…
tagged with: python
accepted answer: http://stackoverflow.com/a/48207096

http://stackoverflow.com/comment/83196772
type: Comment
has text: to make code more readable put ALL imports at start, later ALL functions and finally `root = Tk()` and rest.
comment on: http://stackoverflow.com/q/48108305
score: 0
type: QuestionComment

http://stackoverflow.com/q/48089366
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83153246
answer count: 0
has body: I am trying to create multiple dataframes from the existing dictionaries. But after the loop finishes, the dataframes are not saved/made. L1 = ['A','B','C',] D1 = {'A':[1,2,3],'B':[4,5,6],'C':[7,8,9]} D2 = {'A':['aa','bb','cc'],'B':['dd','ee','ff'],'C':['gg','hh','ii']} D3 = {'A':['100','101','102'],'B':['103','104','105'],'C':['106','107','108']} for each in L1: each = pd.DataFrame({(each+'1'):D1[each],(each+'2'):D2[each]},index=D3[each]) print (A) Error message NameError: name 'A' is not defined I know the dataframe is once created since if I print/show the dataframe within the loop then it's ok. But I want all dataframes to be saved so I can use later. Appreciate the help!
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
tagged with: loops
has title: Python _ Create multiple dataframe by loop
duplicate of: http://stackoverflow.com/q/1373164
tagged with: dataframe
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83153243
has comment: http://stackoverflow.com/comment/83155804
tagged with: python

http://stackoverflow.com/q/48025612
answer count: 1
has answer: http://stackoverflow.com/a/56987588
tagged with: linear-algebra
upvote count: 1
has body: I would like to evaluate the shape of a tensor at runtime. I am calculating the intersection between two sets. The number of intersections is the dimension of a tensor x. While defining the graph, the shape of the tensor is set to [Dimension(None)]. Thus, the usual x.get_shape() method will just return None. Is there a way to evaluate the shape None at run time? I could do sess.run(x) and get the shape of the numpy array, but I would like this to be a compiled op so that only the shape is returned. Thanks!
favorite count: 0
downvote count: 0
type: UnansweredQuestion
has title: How to get tensorflow to evaluate shape at runtime?
tagged with: python
score: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/83021092
tagged with: tensorflow-xla
has comment: http://stackoverflow.com/comment/83022108

http://stackoverflow.com/comment/83224387
type: Comment
has text: `urlopen()` has a `timeout` arg.
comment on: http://stackoverflow.com/q/48123538
score: 0
type: QuestionComment

http://stackoverflow.com/q/48134759
tagged with: ascii
answer count: 2
possible better answer: http://stackoverflow.com/a/48134875
accepted answer: http://stackoverflow.com/a/48134821
has answer: http://stackoverflow.com/a/48134875
has comment: http://stackoverflow.com/comment/83246893
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83246824
has body: I'm trying to write a python program that takes a character as input which is going to be an uppercase character; the output should be the next character in the alphabet. But if the input is 'Z', then the output should be 'A'. The following is my code but when I input Y it outputs 'Z' and 'Y': ino = ord(input()) if ino != 90: ino += 1 print(chr(ino)) if ino == 90: print(chr(65))
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83246888
has answer: http://stackoverflow.com/a/48134821
type: Question
has title: Using an if statement to go through uppercase char
has comment: http://stackoverflow.com/comment/83246833

http://stackoverflow.com/a/48122065
has body: You can choose whatever row to use for the column header: Files.append(pd.read_excel(path+s), header=2); for example, this reads the headers from the 3rd row See documentation: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48121909
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48121909
type: AcceptedAnswer
downvote count: 0

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

http://stackoverflow.com/q/48111138
has comment: http://stackoverflow.com/comment/83227553
has title: use google APIs with python make folders and create sheets
tagged with: google-api
tagged with: python
has comment: http://stackoverflow.com/comment/83226353
has comment: http://stackoverflow.com/comment/83226806
score: 0
has body: I am trying to learn google APIs with python. While I can create a google sheet and write data on it, I have no idea on how making folders and create a google sheet in a specified folder (using google APIs). Can you show me how to create a folder and how to create a sheet in it ?
tagged with: google-api-client
answer count: 0
has comment: http://stackoverflow.com/comment/83202935
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48125395
type: Question

http://stackoverflow.com/q/48089135
tagged with: python
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/83152791
has comment: http://stackoverflow.com/comment/83153139
has answer: http://stackoverflow.com/a/48089203
has comment: http://stackoverflow.com/comment/83152879
score: 0
tagged with: bash
answer count: 1
has body: I have a bash script which changes the path on my command line, This one, #!/usr/bin/env python cd /mnt/vvc/username/deployment/ I have a python script which i wish to run after the path changes to the desired path, The script, #!/usr/bin/env python import subprocess import os subprocess.call(['/home/username/new_file.sh']) for folder in os.listdir(''): print ('deploy_predict'+' '+folder) I get this File "/home/username/new_file.sh", line 2 cd /mnt/vvc/username/deployment/ ^ SyntaxError: invalid syntax Any suggestions on how can i fix this?thanks in advance
has title: running bash script from python file
has comment: http://stackoverflow.com/comment/83152846
has comment: http://stackoverflow.com/comment/83152960
accepted answer: http://stackoverflow.com/a/48089203
has comment: http://stackoverflow.com/comment/83152913

http://stackoverflow.com/q/48050769
downvote count: 0
favorite count: 0
duplicate of: http://stackoverflow.com/q/35555383
tagged with: python
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
upvote count: 10
linked to: http://stackoverflow.com/q/35555383
type: Question
score: 10
tagged with: flask
has answer: http://stackoverflow.com/a/48051288
has body: I try to output a pandas dataframe in a flask template. My idea was to transform it to json and then loop through the table I tested this jsonfiles = df.to_json(orient='records') return render_template('index.html', ctrsuccess=jsonfiles) In the template I try to output like this: {%if ctrsuccess %} {%for ctrrow in ctrsuccess %} {{ ctrrow['positionint'] }} {%endfor%} {%endif%} In the template i get a proper looking json if i just draw ctrsuccess. But the table is empty [{"positionint":1.0,"clicks":1138.0,"impressions":4768.0,"ctr":0.2386744966,"clickCtr10p":1251.8,"clickCtr50p":1707.0,"clickCtr100p":2276.0},{"positionint":2.0,"clicks":3160.0,"impressions":49899.0,"ctr":0.0633279224,"clickCtr10p":3476.0,"clickCtr50p":4740.0,"clickCtr100p":6320.0},{"positionint":3.0,"clicks":1255.0,"impressions":50020.0,"ctr":0.025089964,"clickCtr10p":1380.5,"clickCtr50p":1882.5,"clickCtr100p":2510.0},{"positionint":4.0,"clicks":363.0,"impressions":39077.0,"ctr":0.0092893518,"clickCtr10p":399.3,"clickCtr50p":544.5,"clickCtr100p":726.0},{"positionint":5.0,"clicks":216.0,"impressions":18419.0,"ctr":0.011727021,"clickCtr10p":237.6,"clickCtr50p":324.0,"clickCtr100p":432.0},{"positionint":6.0,"clicks":307.0,"impressions":15447.0,"ctr":0.0198744093,"clickCtr10p":337.7,"clickCtr50p":460.5,"clickCtr100p":614.0},{"positionint":7.0,"clicks":248.0,"impressions":24709.0,"ctr":0.0100368287,"clickCtr10p":272.8,"clickCtr50p":372.0,"clickCtr100p":496.0},{"positionint":8.0,"clicks":236.0,"impressions":26853.0,"ctr":0.0087885897,"clickCtr10p":259.6,"clickCtr50p":354.0,"clickCtr100p":472.0},{"positionint":9.0,"clicks":139.0,"impressions":26577.0,"ctr":0.0052300862,"clickCtr10p":152.9,"clickCtr50p":208.5,"clickCtr100p":278.0},{"positionint":10.0,"clicks":23.0,"impressions":2046.0,"ctr":0.0112414467,"clickCtr10p":25.3,"clickCtr50p":34.5,"clickCtr100p":46.0},{"positionint":null,"clicks":7085.0,"impressions":257815.0,"ctr":null,"clickCtr10p":7793.5,"clickCtr50p":10627.5,"clickCtr100p":14170.0},{"positionint"…
accepted answer: http://stackoverflow.com/a/48051288
tagged with: pandas
has title: Pandas dataframe to flask template as a json
answer count: 1

http://stackoverflow.com/comment/83099024
type: AnswerComment
has text: Thank you very much! solved my problem there. (yeah, the missing brackets was a typo from copying my code over) Happy new year!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48062889

http://stackoverflow.com/a/48085151
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/48084971
answers question: http://stackoverflow.com/q/48084971
type: AcceptedAnswer
downvote count: 0
has body: You should read through Pandas - Working with Text Data specifically the section on strings that match or contain a pattern. Unfortunately you cannot search a DataFrame with the string methods common to core Python. Instead you would use a StringMethod, like so: out = False for col in df.columns: if df[col].str.contains('@').any(): out = 'True' break print(out) Also, I don't believe it is necessary to use open when using pd.read_excel. E.g df = pd.read_excel(open('test.xlsx','rb'), sheetname=0) Can be rewritten: df = pd.read_excel('test.xlsx', sheetname=0) As far as iterating over files in a folder take a look at the builtin module glob.

http://stackoverflow.com/q/48168011
has comment: http://stackoverflow.com/comment/83315426
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83315091
score: -4
upvote count: 1
type: Question
downvote count: 5
has answer: http://stackoverflow.com/a/48168533
tagged with: list-comprehension
has body: I have this for loop def isPrime(n): for i in range(2, n): if n % i == 0: return False return True I tried to rewrite it with list comprehension following the general syntax of list comprehension, but I always get an error. eventually it has to print a list of prime numbers with this command: print([x for x in range(2, 100) if isPrime(x)])
has comment: http://stackoverflow.com/comment/83315082
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83315201
has comment: http://stackoverflow.com/comment/83316290
answer count: 1
has comment: http://stackoverflow.com/comment/83315207
favorite count: 0
has title: How to convert a for loop in list comprehension in Python?
accepted answer: http://stackoverflow.com/a/48168533

http://stackoverflow.com/q/48026559
upvote count: 3
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48026723
has body: How i can set my own user in request.user or request.session.user my own models: class User(Document): id = fields.IntField(primary_key=True) username = fields.StringField(required=True) email = fields.EmailField() .... @property def is_authenticated(self): return False I set this in my view user = User.objects.get(email=email) request.session.user = user but didn't work.
score: 3
has comment: http://stackoverflow.com/comment/83023099
accepted answer: http://stackoverflow.com/a/48026836
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48026836
possible better answer: http://stackoverflow.com/a/48026723
tagged with: django
tagged with: python
has title: How to set User in request.user in Django using MongoDB

http://stackoverflow.com/q/48074166
answer count: 1
downvote count: 0
tagged with: numpy-einsum
has title: Python Pandas SUMPRODUCT and L Matrix caluclation
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48074222
has comment: http://stackoverflow.com/comment/83121962
has body: i have to columns in a pandas dataframe format and want the output in the C D column as below A B C D 1 2 1*2 1*2 3 4 (1+3)*4 (1*2)+(3*4) 5 6 (1+3+5)*6 (1*2)+(3*4)+(5*6) 7 8 (1+3+5+7)*8 (1*2)+(3*4)+(5*6)+(7*8) 9 10 .... ..... Here i am trying to code excel formula in a python way ,Can someone throw code for this a) python code for top to bottom calculation Excel Formulas for the final outcome: C1=IFERROR($B2*SUM(A2:$A$2)-SUMPRODUCT($B2:B$2,$A2:A$2),0) C2=IFERROR($B3*SUM(A$2:$A3)-SUMPRODUCT($B$2:B3,$A$2:A3),0) ..... .... C14=IFERROR($B14*SUM(A$2:$A14)-SUMPRODUCT($B$2:B14,$A$2:A14),0) b) python code for bottom to top calculation from bottom e1==IFERROR(SUMPRODUCT($B2:B$14,$C2:C$14)-$B2*SUM($C2:C$14),0) E2=IFERROR(SUMPRODUCT($B3:B$14,$C3:C$14)-$B3*SUM($C3:C$14),0) e4=IFERROR(SUMPRODUCT($B4:B$14,$C4:C$14)-$B4*SUM($C4:C$14),0) ..... ..... ..... e14=IFERROR(SUMPRODUCT($B14:B$14,$C14:C$14)-$B14*SUM($C14:C$14),0)
tagged with: python
has comment: http://stackoverflow.com/comment/83126430
type: AnsweredQuestion
upvote count: 1
tagged with: excel
type: Question
has answer: http://stackoverflow.com/a/48074222
tagged with: pandas

http://stackoverflow.com/comment/83166271
comment on: http://stackoverflow.com/q/48095713
score: 0
type: Comment
type: QuestionComment
has text: I am creating a REST API modeling tradingview.com - you make a GET request asking for charts related to a stock's price. If you want a regression line drawn over the stock price data, you mention it in the "class" variable like so: 'class=regr'. Say you also wanted the MACD - a type of analysis tool like regression - then you would also pass in 'class=macd'. The GET Request would thus become: http://localhost:5000/item/analysis=true&class=macd&class=regr/

http://stackoverflow.com/a/48152565
downvote count: 0
has comment: http://stackoverflow.com/comment/83284763
answers question: http://stackoverflow.com/q/48152403
type: Answer
has comment: http://stackoverflow.com/comment/83284194
score: 5
has body: You can do that conversion with the ord and format functions in a list comprehension. import base64 data = 'aW0ganVzdCBhIGJhc2UgNjQgZmlsZQ==' print [format(ord(c), '08b') for c in base64.b64decode(data)] output ['01101001', '01101101', '00100000', '01101010', '01110101', '01110011', '01110100', '00100000', '01100001', '00100000', '01100010', '01100001', '01110011', '01100101', '00100000', '00110110', '00110100', '00100000', '01100110', '01101001', '01101100', '01100101'] If you want that as a single string, just .join it: ''.join([format(ord(c), '08b') for c in base64.b64decode(data)])
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48152403
type: AcceptedAnswer

http://stackoverflow.com/a/48164310
answers question: http://stackoverflow.com/q/48145992
type: Answer
downvote count: 0
score: 14
has body: I changed the bodyHeightAdmin class as follows: class BodyHeightAdmin(admin.ModelAdmin): search_fields = ('name', ) list_display = ('id', 'name', 'key', 'url', ) list_display_links = ('id', 'name', 'key', ) def url(self, instance): data = json.loads(instance.data) return data["url"] And it worked.
upvote count: 14
has comment: http://stackoverflow.com/comment/109333766
accepted answer of: http://stackoverflow.com/q/48145992
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/132811242

http://stackoverflow.com/q/48138390
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/83255606
tagged with: label
upvote count: 1
answer count: 1
tagged with: frame
favorite count: 0
has body: I have x labels, these are created using rand = random.randint(1,100000) local()[f'self.m{rand}'] = Label(self.frame, text='test') local()[f'self.m{rand}'].pack() Furthermore I have a frame, I want to set a label next to another one following this scheme Label 1 Label 2 Label 3 Label 4 Label 5 Label 6 Label **y** Label **x** Does anyone have any ideas on how I could proceed?
has title: Align different labels in a Tkinter frame
has answer: http://stackoverflow.com/a/48139178
accepted answer: http://stackoverflow.com/a/48139178
has comment: http://stackoverflow.com/comment/83255588

http://stackoverflow.com/a/69323468
score: -2
answers question: http://stackoverflow.com/q/48094854
has body: Eg, For Converting $40,000.00 object to 40000 int or float32 Follow this step by step : $40,000.00 ---(**1**. remove $)---> 40,000.00 ---(**2**. remove , comma)---> 40000.00 ---(**3**. remove . dot)---> 4000000 ---(**4**. remove empty space)---> 4000000 ---(**5**. Remove NA Values)---> 4000000 ---(**6**. now this is object type so, convert to int using .astype(int) )---> 4000000 ---(**7**. divide by 100)---> 40000 Implementing code In Pandas table1["Price"] = table1["Price"].str.replace('$','') table1["Price"] = table1["Price"].str.replace(',','') table1["Price"] = table1["Price"].str.replace('.','') table1["Price"] = table1["Price"].str.replace(' ','') table1 = table1.dropna() table1["Price"] = table1["Price"].astype(int) table1["Price"] = table1["Price"] / 100 Finally it's done
has comment: http://stackoverflow.com/comment/122528420
type: Answer
downvote count: 3
upvote count: 1

http://stackoverflow.com/q/48139886
tagged with: ssl
answer count: 2
downvote count: 0
score: 1
favorite count: 0
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/48140185
possible better answer: http://stackoverflow.com/a/48141273
has answer: http://stackoverflow.com/a/48141273
type: AnsweredQuestion
upvote count: 1
has title: Receive raw TLS packet in Python
type: Question
has body: I am writing a simple SSL socket server and client in Python 2.7. I am trying to send a byte array from the client and read the same byte array from the server. Here's the code : server import socket import ssl import threading class SocketServer(object): def __init__(self, host, port): self.context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) self.context.load_cert_chain(certfile="D:\plugnplay\openssl\cert.pem") self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind((self.host, self.port)) def listen(self): self.sock.listen(5) while True: sslsoc = None try: client, address = self.sock.accept() sslsoc = self.context.wrap_socket(client, server_side=True) threading.Thread(target = self.listenToClient,args = (client,address)).start() except Exception,ex: print (('Connection error : client - {0}, error - {1}').format(address, ex)) try: if sslsoc != None: sslsoc.close() else: client.close() except: pass def listenToClient(self, sslsoc, address): sslsoc.settimeout(60) size = 1024 full_data = [] while True: try: data = sslsoc.recv(size) byte_data = bytearray() byte_data.extend(data) if data: for d in byte_data: full_data.append(int(d)) else: raise Exception('Client disconnected') except Exception,ex: sslsoc.close() print full_data return if __name__ == "__main__": port_num = 7656 SocketServer('',port_num).listen() client import socket, ssl import time port = 7656 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) context.load_cert_chain(certfile="D:\plugnplay\openssl\cert.pem") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = context.wrap_socket(s, server_side = False) ssl_sock.connect(('127.0.0.1', port)) data = bytearray() data.append(1) data.append(2) data.append(3) data.append(4) ssl_sock.write(data) ssl_sock.close() The problem is, I am getting the following array as the output from the server - [23, 3, 3, 0, 28, 83, 69, 220, 108, 217, 65, 85, 25…
accepted answer: http://stackoverflow.com/a/48140185

http://stackoverflow.com/comment/83289016
comment on: http://stackoverflow.com/q/48154938
type: Comment
type: QuestionComment
has text: instead of `re.finditer`, use `re.sub` with a function (eventually a lambda function) as replacement. See this question: https://stackoverflow.com/questions/33791279/incrementing-the-digit-by-1-in-python-using-isdigit
score: 1

http://stackoverflow.com/q/48085285
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has body: I need a list of strings representing binary values, with a fixed length, thus with leading zeros. for example: my_list = ["00", "01", "10", "11"] I want to be able to generate the list given the number of bits. I've come up with a code, but I'm not sure if this is the best way to do it and wonder if it's possible to do the same with a one-liner? bits = 2 my_list = [] for i in range(2**bits): my_list.append(format(i, '0b').zfill(bits))
has answer: http://stackoverflow.com/a/48085326
has title: create a list of strings representing binary values, with a fixed length
has answer: http://stackoverflow.com/a/48085327
downvote count: 0
accepted answer: http://stackoverflow.com/a/48085327
has answer: http://stackoverflow.com/a/48085387
favorite count: 0
possible better answer: http://stackoverflow.com/a/48085321
has answer: http://stackoverflow.com/a/48085321

http://stackoverflow.com/comment/83031055
comment on: http://stackoverflow.com/q/48030027
has text: check the following code, I think the delegate is not necessary. https://gist.github.com/eyllanesc/a4caf9b474d8e0c21df3a7d3c2a54a2c
score: 0
type: Comment
type: QuestionComment

cpython
tags question: http://stackoverflow.com/q/48152535
type: Tag
tag name: cpython

http://stackoverflow.com/a/48114929
score: 0
type: Answer
has body: May be helpful to you: Each account is an instance of the BankAccount class you created, and each of the account's information corresponds to each of the properties in the BankAccount class. You can initialize each instance via the init method after reading the account information from the file.
answers question: http://stackoverflow.com/q/48111119

http://stackoverflow.com/comment/83069614
has text: Added some more explanation.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48048773

http://stackoverflow.com/comment/83081666
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48054633
has text: Although then you get 1.66 for `TestWithSwitch`.

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

http://stackoverflow.com/comment/83211513
type: Comment
type: QuestionComment
score: 0
has text: @Georgy your comment and your downvote doesn't bring me anything. i saw the link which your provided already. its not the same case. i don't have two dictionnaries.
comment on: http://stackoverflow.com/q/48116337

http://stackoverflow.com/q/48028782
type: Question
answer count: 1
has body: I'm running ChromeDriver 2.34.522940 and Selenium 3.8.0 on Windows 7 and Python 3.6. I'm trying this code: def foo(url, login, password): from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get(url) And it gave the error message: DevTools listening on ws://127.0.0.1:12355/devtools/browser/ed317bfa-b264-4fd7-bc5d-aeab717fdb58 [1229/152519.688:ERROR:gl_surface_egl.cc(772)] eglInitialize D3D11 failed with error EGL_NOT_INITIALIZED, trying next display type Kept running the following code: u = driver.find_element_by_name('login') u.send_keys(login) p = driver.find_element_by_name('password') p.send_keys(password) p.send_keys(Keys.RETURN) And it gave an new error message: [9152:11284:1229/152703.260:ERROR:service_manager.cc(157)] Connection InterfaceProviderSpec prevented service: content_renderer from binding inter face: blink::mojom::ReportingServiceProxy exposed by: content_browser And a few seconds later: [9152:11284:1229/152720.000:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED [9152:11284:1229/152720.000:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED [9152:11284:1229/152720.000:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED [9152:11284:1229/152720.000:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED I ran the same code yesterday and it didn't give these error messages. What caused these, and how to suppress these error messages?
has title: Python Selenium ChromeDriver error message: EGL_NOT_INITIALIZED
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48453823
accepted answer: http://stackoverflow.com/a/48453823
score: 2
tagged with: selenium-chromedriver
type: AnsweredQuestion
upvote count: 3
tagged with: selenium
tagged with: web-scraping
downvote count: 1

http://stackoverflow.com/comment/83203838
has text: @Netwave Do you mind describing the last part (*"Dont forget to push as many stop flags as processes you have"*) in a bit more detail?
score: 0
comment on: http://stackoverflow.com/q/48113927
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83283776
score: 0
type: AnswerComment
type: Comment
has text: @Whiteneon What does? Which version are you using?
comment on: http://stackoverflow.com/a/48152293

http://stackoverflow.com/comment/83036001
score: 0
has text: if you do `self.p3 = PyDataTest1(self).grid()` then you get `None` in `self.p3` because `grid()` returns `None`. If you need `self.p3` then you have to do it in two lines `self.p3 = PyDataTest1(self)` and `self.p3.grid()`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48032488

http://stackoverflow.com/a/48165718
upvote count: 2
downvote count: 0
has body: What you here want to do is reference another field as value in the queryset. You can do this by constructing an F-expression: one_better = childs_of_me.filter(score_1__gt=F('score_2')) Without doing this, Python interprets this as an identifier. Here we use a string, and wrap it around an F-object, to indicate that we want to refer to a field.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48165672

http://stackoverflow.com/comment/133829261
comment on: http://stackoverflow.com/q/48063176
type: Comment
type: QuestionComment
has text: @funilrys I had a go at using your library and it told me a domain was not expired despite me knowing very well that it is
score: 0

http://stackoverflow.com/comment/83377872
comment on: http://stackoverflow.com/a/48101579
has text: Figured out the problem! Thanks
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/86425073
type: Comment
type: QuestionComment
has text: PaulCO have you got any solution?
score: 0
comment on: http://stackoverflow.com/q/48136491

http://stackoverflow.com/comment/83101980
has text: Itertating over the lines with the ability to call `tell()` within the loop can be done like this: `for line in iter(f.readline, ''):`
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48055409
type: QuestionComment

ode
tags question: http://stackoverflow.com/q/48148720
tags question: http://stackoverflow.com/q/48088890
tags question: http://stackoverflow.com/q/48096655
type: Tag
tag name: ode

http://stackoverflow.com/q/48059721
tagged with: python
accepted answer: http://stackoverflow.com/a/48065549
has body: I'm using BigQuery API client library for Python from Google Compute Engine. While making query it throws network unreachable error. [INFO:2018-01-02 16:16:04,887:oauth2client.transport] Attempting refresh to obtain initial access_token [INFO:2018-01-02 16:16:04,924:oauth2client.client] Refreshing access_token Traceback (most recent call last): File "/test/data/reports/ga_bigquery.py", line 130, in ga_table_string if bq_dataset.table("ga_sessions_{}".format(str_date)).exists(): File "/test/data/reports/.venv/lib/python2.7/site-packages/gcloud/bigquery/table.py", line 472, in exists query_params={'fields': 'id'}) File "/test/data/reports/.venv/lib/python2.7/site-packages/gcloud/connection.py", line 343, in api_request target_object=_target_object) File "/test/data/reports/.venv/lib/python2.7/site-packages/gcloud/connection.py", line 241, in _make_request return self._do_request(method, url, headers, data, target_object) File "/test/data/reports/.venv/lib/python2.7/site-packages/gcloud/connection.py", line 270, in _do_request body=data) File "/test/data/reports/.venv/lib/python2.7/site-packages/oauth2client/transport.py", line 153, in new_request credentials._refresh(orig_request_method) File "/test/data/reports/.venv/lib/python2.7/site-packages/oauth2client/client.py", line 765, in _refresh self._do_refresh_request(http_request) File "/test/data/reports/.venv/lib/python2.7/site-packages/oauth2client/client.py", line 797, in _do_refresh_request self.token_uri, method='POST', body=body, headers=headers) File "/test/data/reports/.venv/lib/python2.7/site-packages/httplib2/__init__.py", line 1609, in request (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) File "/test/data/reports/.venv/lib/python2.7/site-packages/httplib2/__init__.py", line 1351, in _request (response, content) = self._conn_request(conn, request_uri, method, body, headers) File "/test/data/reports/.venv/lib/python2.7/site-packages/httpl…
type: AnsweredQuestion
score: 0
type: Question
has title: Network is unreachable while using BigQuery API client library for Python
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/83091842
answer count: 1
has answer: http://stackoverflow.com/a/48065549
has comment: http://stackoverflow.com/comment/83095626
tagged with: google-compute-engine

http://stackoverflow.com/q/48032100
has comment: http://stackoverflow.com/comment/83034385
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83039425
downvote count: 6
tagged with: recursion
score: -5
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48032607
has answer: http://stackoverflow.com/a/48032300
upvote count: 1
has comment: http://stackoverflow.com/comment/83034440
has body: How should i convert the following into a recursive function so that the output will also be [1, 2, 6, 24, 120]? def factorial(n): l = [] value = 1 for x in range(1, n+1): value = value * x l.append(value) print(l) factorial(5) The following is my recursion code. I am not sure on how i should use append in the function to create the list, any suggestions? def factorial(n): if n == 1: L.append(1) return 1 else: return n * factorial(n-1) x = int(input("Enter value of n: ")) L = [] print(factorial(x)) print(L)
favorite count: 0
has title: Convert the following into a recursive function

http://stackoverflow.com/comment/83091555
comment on: http://stackoverflow.com/a/48059259
type: Comment
has text: @jonrsharpe the point of a question on Stack Overflow is asking for a single problem. OP asked how you can count a given amount of references, not how to match the amount of input Strings with placeholders in a String.
score: 1
type: AnswerComment

http://stackoverflow.com/a/48048028
answers question: http://stackoverflow.com/q/48045399
score: 0
has body: As already answered, try a log scale with plt.semilogy()
type: Answer

http://stackoverflow.com/q/48137324
type: Question
has answer: http://stackoverflow.com/a/48137386
has title: Pandas randomly select n groups from a larger dataset
score: 0
accepted answer: http://stackoverflow.com/a/48137386
tagged with: pandas
has body: If I have a dataframe with groups like so val label x A x A x B x B x C x C x D x D how can I randomly pick out n groups without replacement?
answer count: 1
favorite count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83251883
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83253058

http://stackoverflow.com/comment/83094275
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48060354
has text: db version v1.8.2
type: Comment

http://stackoverflow.com/q/48065453
has comment: http://stackoverflow.com/comment/83104089
score: 0
has comment: http://stackoverflow.com/comment/83104177
answer count: 0
has body: I have a zip file (data.zip) with structure like, config/ config.json src/ util.py When I import this zip like, I face below error, import sys sys.path.append('./data.zip') import src.util IOError: [Errno 2] No such file or directory: '../config/config.json' reason behind this is, util.py has a method which accesses config.json in config directory of zip. I am not sure why this is failing and util.py is failing to read/access config/config.json. Can anybody help me understand this behavior and solution to solve this?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83104388
tagged with: python
has title: access path in zip file in import module
has comment: http://stackoverflow.com/comment/83104589
type: Question
tagged with: pyspark

http://stackoverflow.com/comment/83240239
type: Comment
score: 3
has text: Probably better to test e.response['Error']['Code'] than e.message.
comment on: http://stackoverflow.com/a/48124319
type: AnswerComment

http://stackoverflow.com/q/48079133
has answer: http://stackoverflow.com/a/48079394
tagged with: pandas
downvote count: 0
answer count: 1
has body: I'm currently using Bat (https://github.com/Kitware/bat) to read in Bro (https://www.bro.org/) log files and convert them into Pandas dataframes. One of the things I'm working on is some frequency analysis of DNS lookups. This output shows the size of an hours worth of Bro dns data from one of my hosts, so you might get an idea of the amount of data I'm working with. bro_df.info() &lt;class 'bat.log_to_dataframe.LogToDataFrame'&gt; DatetimeIndex: 1013219 entries, 2018-01-03 08:59:53.250328 to 2018-01-03 09:59:51.672011 Data columns (total 23 columns): AA 1013219 non-null bool RA 1013219 non-null bool RD 1013219 non-null bool TC 1013219 non-null bool TTLs 1013219 non-null object Z 1013219 non-null int64 answers 1013219 non-null object id.orig_h 1013219 non-null object id.orig_p 1013219 non-null int64 id.resp_h 1013219 non-null object id.resp_p 1013219 non-null int64 proto 1013219 non-null object qclass 1013219 non-null int64 qclass_name 1013219 non-null object qtype 1013219 non-null int64 qtype_name 1013219 non-null object query 1013219 non-null object rcode 1013219 non-null int64 rcode_name 1013219 non-null object rejected 1013219 non-null bool rtt 1013219 non-null timedelta64[ns] trans_id 1013219 non-null int64 uid 1013219 non-null object dtypes: bool(5), int64(7), object(10), timedelta64[ns](1) memory usage: 151.7+ MB I do some quick and easy stuff like dropping unnecessary columns and such but this is still quite a large dataframe to work with. In order to do proper frequency analysis of the lookups I'm also trying to remove 'known good', or whitelisted domains, from the dataframe and this is where things get really slow. Since I'm fairly new to Pandas I fear that I might be doing this in a less than ideal way, to put it politely. My approach is as follows for the removal of the whitelisted stuff - I've removed some internal DNS info to protect the innocent: whitelist = ['-', '(empty)', 'in-addr.arpa', '.google.com', '.akamai.net', '.akamaiedge.net', '.apple.com'…
favorite count: 0
tagged with: python
tagged with: jupyter-notebook
accepted answer: http://stackoverflow.com/a/48079394
score: 2
type: AnsweredQuestion
upvote count: 2
tagged with: loops
has title: Is there a quicker way of iterating through and removing specific rows in a Pandas dataframe?
type: Question
tagged with: dataframe

http://stackoverflow.com/comment/95016798
comment on: http://stackoverflow.com/q/48128075
score: 0
type: Comment
type: QuestionComment
has text: Tibor can you have a look at my answer below. If you managed to solve your problem another way, please share.

http://stackoverflow.com/q/48138978
tagged with: python-3.x
tagged with: list
has body: I have a list l containing multiples dictionaries l = [ d1, d2, ...., d100], where each dictionary is defined with keys 'id', 'address', 'price'. Now, I want to take all dictionaries d from the list l for which value of key 'price' is equal 50. Is there a faster way to do this than using a for loop? This processing is already encapsualted within other for loop function, so I would prefer to not have two for loop if possible. The skeleton of the function looks right now as: for ... (external for loop): results = [] for d in l: if d['price'] == 50: results.append(d)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48138994
type: Question
score: 0
has answer: http://stackoverflow.com/a/48139067
accepted answer: http://stackoverflow.com/a/48139067
has comment: http://stackoverflow.com/comment/83255548
has comment: http://stackoverflow.com/comment/83255473
answer count: 3
has answer: http://stackoverflow.com/a/48140460
tagged with: python
tagged with: dictionary
has title: Searching for a key value in the list of dictionaries
possible better answer: http://stackoverflow.com/a/48138994

http://stackoverflow.com/a/48155505
score: 1
answers question: http://stackoverflow.com/q/48153891
downvote count: 0
type: Answer
upvote count: 1
has body: You're getting this error because you're using shell redirection instead of just passing an argument ../python/pythonScript.py &lt; hi tells your shell to read input from a file called hi in the current directory, rather than using it as an argument. What you mean to do is my $ret = `../python/pythonScript.py hi`; Which correctly executes your python script with the hi argument, and returns the result to the variable $ret.

http://stackoverflow.com/q/48031445
upvote count: 3
tagged with: pandasql
answer count: 1
has body: Hello trying to merge two data frames and sum visit counts by date and upc. Transaction data (date,upc,sales) 200k rows x 3 columns Visits counts(date, upc, visit count) 2 million+ rows x 3 columns I’ve tried this df3 = pandas.merge(df1,df2, on = ['upc','date'], how = 'left') Result: merge executes but it does not sum up by date or upc I also tried df3 = pandas.merge(df1,df2, left_on = ['date'], right_on ['upc'] how = 'left') and that didn’t work. df3 = pandas.merge(df1,df2, left_on = ['date','upc'], right_on ['date','upc'] how = 'left') and that didn’t work. I also tried df3 = pandas.merge(df1,df2, on = ['date'], how = 'left') and I kept returning an error message. Based on the error message it looked like I needed to convert one of the dates in the data frames to pandas dtype. I made that change and returned the same results as my first try. The merge worked but it did not sum up the results. I tried converting both dates in both data frames to astype(str) and that didn’t work. I learned if both dates have the same date format dtype or astype(str) I return a memory error message. Merge would fail. I was successful with merging using the upc only but this creates an issue in my data, I return duplicate visit numbers because a upc is repeated in the transaction due to the date column. End of the day what I need is something similar to a sumif function in excel. I need to combine the two data sets by summarizing the total visits by each upc for each day and keeping transaction data unchanged or left join in terms of sql Sample data df1 Date upc sales 0 09/01/2016 A01234 1000 1 09/02/2016 A01234 500 2 09/10/2016 A56789 1200 df2 Date upc visits 0 09/01/2016 A01234 10 1 09/02/2016 A01234 25 2 09/05/2016 A56789 26 3 09/10/2016 A56789 32 df3 Date upc sales visits 0 09/01/2016 A01234 1000 10 1 09/02/2016 A01234 500 25 2 09/10/2016 A56789 1200 32 Wondering if pandasql package is what I need to use. Any help is appreciated
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83034874
tagged with: pandas
score: 3
downvote count: 0
favorite count: 0
type: Question
tagged with: python
has title: Pandas merge on two columns using date and another column
has answer: http://stackoverflow.com/a/48031611

http://stackoverflow.com/comment/83180714
score: 1
comment on: http://stackoverflow.com/q/48102604
type: Comment
type: QuestionComment
has text: Check out the requests module if you haven't, might make your life a bit easier.

http://stackoverflow.com/a/48090884
has body: Try something like this: In my case i added two varibles and boolean category_only In try section im checking if there is int in first arg (count = int(args[0])) If not, in "except ValueError" i set category_only to true and handle this case. I think you should try parse second arg, and use additional variable if there is only one parameter. @run_async def cats_command(self, bot, update, args): logging.info(str(update.message.from_user) + ' /cats') count, category = 3, '' category_only = False try: if int(args[0]) &gt; 20: raise TooMuchCountError('too much') if int(args[0]) &lt; 1: raise TooSmallCountError('too small') count = int(args[0]) except TooMuchCountError: update.message.reply_text( TextMessages.too_much_count_error_message.format(count)) except TooSmallCountError: update.message.reply_text( TextMessages.too_small_count_error_message.format(args[0])) except IndexError: update.message.reply_text( TextMessages.index_error_message.format(count)) except ValueError: category_only = True try: if category_only: category = str(args[0]) else: category = str(args[1]) l = map(lambda x: x.name, self.categories) if category not in l: raise WrongCategoryError('not in list') except WrongCategoryError: update.message.reply_text( TextMessages.worng_category_error_message) category = '' except IndexError: pass logging.info(' catting for user {}'.format(update.message.from_user.first_name)) images = Parser.get_images('xml', count, category) So, your code: args = text.split(" ") category_only = False; page, category = 0,0 try: category = int(args[0]) except ValueError: print('there is no good params at all!') /* catch this and return*/ try: page = int(args[1]) except ValueError: category_only = True You can also avoid boolean variable using page=-1 or another value, and then check it like "if page > -1"
downvote count: 0
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48088104

http://stackoverflow.com/q/48092411
has title: Creating pandas dataframes from nested json file that has lista
accepted answer: http://stackoverflow.com/a/48092456
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48092456
tagged with: dataframe
has body: a picture on how the data look like So, I have a json file with data, the file is really nested, I want to take only the words and create a new dataframe for each post id. Can anyone help with this?
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48170753
has comment: http://stackoverflow.com/comment/83321926
has body: the following sourcecode produces a memoryerror on my machine: import numpy as np x = np.random.random([100,100,100]) y = np.random.random([100,100,100]) c_sort = np.argsort(x, axis = 2) f = y[c_sort] Do you have a nice and easy idea how to avoid the memory error? The other way to do this is x = np.random.random([100,100,100]) y = np.random.random([100,100,100]) f = np.zeros([100,100,100]) for i in range(100): for j in range(100): f[i,j,:] = y[i,j, np.argsort(x[i,j,:])] But I wonder why the solutions above does not lead to the same result?
type: Question
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/83322378
has answer: http://stackoverflow.com/a/48171693
accepted answer: http://stackoverflow.com/a/48171693
has comment: http://stackoverflow.com/comment/83321287
linked to: http://stackoverflow.com/q/46103044
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83321516
has title: Avoiding memory error when using numpy's argsort
tagged with: python
has comment: http://stackoverflow.com/comment/83322063
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83322511
downvote count: 0
has comment: http://stackoverflow.com/comment/83321837
has comment: http://stackoverflow.com/comment/83322154
linked to: http://stackoverflow.com/q/47044792

http://stackoverflow.com/a/48114830
has body: I can not reproduce your Problem, this works for me (Python 2.7.5) import StringIO import pandas as pd import pandasql as pdsql df = pd.read_csv(StringIO( """CUSTOMER_ID,City 21397845,Birmingham 26396841,Anchorage 52396841,Bullhead 67896841,Flagstaff""")) def Cust(city_value): city='"'+city_value+'"' print("city="+city) str2='select * from df where City='+ city pysql = lambda q: pdsql.sqldf(q, globals()) df1 = pysql(str2) return df1 Cust('Birmingham') Returns: CUSTOMER_ID City 0 21397845 Birmingham [Note: I removed the white spaces in the df data compared to your post (my edit, sry another time... :-/)
type: Answer
answers question: http://stackoverflow.com/q/48113689
accepted answer of: http://stackoverflow.com/q/48113689
has comment: http://stackoverflow.com/comment/83205540
has comment: http://stackoverflow.com/comment/83206213
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83207024
score: 0
has comment: http://stackoverflow.com/comment/83206757

http://stackoverflow.com/q/48033044
answer count: 1
has title: Am I correct in concluding that it is not possible to implement a 'deep dream' in cntk?
tagged with: python
type: AnsweredQuestion
tagged with: cntk
accepted answer: http://stackoverflow.com/a/48291398
type: Question
has answer: http://stackoverflow.com/a/48291398
score: 0
has body: I want to implement a deep dream on some image data I have. I decided to give cntk a go and started out using the MNIST hand writing data to develop against. Typically, when training a neural network, you have some fixed set of input images and you have some variable weights to learn. Deep dreaming sort of flips these around and you have a variable image to learn, given some fixed weights in the network. So I have trained a network to recognize the images quite consistently using a convolutional network. Now I want it to dream up some images, so I need to do a convolution with a variable input image. Apparently cntk does not allow this. The following code demonstrates the error I am getting. def doConstantConv(inputX, W, b, redRank): kernel = C.constant(value = W) bias = C.constant(value = b) conv = C.convolution(kernel, inputX, strides = (2,2), reduction_rank = redRank) + bias return C.relu(conv) W1 = np.reshape(np.arange(200.0, dtype = np.float32), (8,1,5,5)) b1 = np.reshape(np.arange(8.0, dtype = np.float32), (8,1,1)) someInput = C.parameter((1,28,28)) layer1 = doConstantConv(someInput, W1, b1, 1) The error I am getting is "Convolution currently requires the main operand to have dynamic axes". But as far as I can tell, learn-able parameters cannot have dynamic axes. That wouldn't make sense, would it? So is it fair to conclude that cntk cannot be used for deep dreaming? Is there a way to hack it?
tagged with: deep-learning

http://stackoverflow.com/comment/83077804
type: Comment
has text: I think you need `m = df.duplicated(subset='Name', keep='last')` only
comment on: http://stackoverflow.com/a/48052588
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83151259
comment on: http://stackoverflow.com/q/48088206
score: 0
type: Comment
type: QuestionComment
has text: I don't see how it's working at all. It should be `teams['EventDetails']['Properties']['HomeTeamShort']`

http://stackoverflow.com/comment/83108780
has text: Also, is this Python 2 or 3? The answer is *very* important, since the `csv` module is broken for non-ASCII on Python 2.
score: 4
type: Comment
comment on: http://stackoverflow.com/q/48067514
type: QuestionComment

http://stackoverflow.com/a/48066255
has body: Let's try this: df.filter(like='GR').sum() Output: GR_1 0 GR_2 0 GR_3 0 GR_4 0 GR_5 0 GR_6 42 GR_7 61 GR_8 46 UNGR_ELM 0 GR_9 0 GR_10 0 GR_11 0 GR_12 0 UNGR_SEC 0
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83111612
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48065943
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48065943

python-internals
tags question: http://stackoverflow.com/q/48144150
tags question: http://stackoverflow.com/q/48018680
tag name: python-internals
type: Tag
tags question: http://stackoverflow.com/q/48066220
tags question: http://stackoverflow.com/q/48104449

http://stackoverflow.com/a/48050824
has comment: http://stackoverflow.com/comment/83098347
has comment: http://stackoverflow.com/comment/83075349
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/48050639
downvote count: 2
has body: You will want to insert the data into a database (such as sqlite or mysql), and then repeat your idea in SQL select * from your_table where id in (1, 14, 1700, ...) You can also read up how to select a random sample from this excellent tutorial http://jan.kneschke.de/projects/mysql/order-by-rand/ and There is no way devise a shell script that would run significantly faster, as your code ultimately relies on the way filesystems fundamentally work. That is, for good performance you want to access the disk sequentially and in chunks. Databases are designed to solve this issue by storing how the data is laid out in the harddrive in a separate file called the index. It works much in the same way as an index of a book. This is a rich topic and requires some learning. If you're new to database programming, 40 gb dataset is a good starting point, though.
score: 0

http://stackoverflow.com/comment/83318958
has text: @prabhu what do you mean with 'when online'? Surely you have your .h5 model trained for which you are calling `predict()` ... well you can refit *that* model "on the fly" while online after you get new data and labels, doing as explained in my answer. Does that work for you, if not, mind explaining a bit more?
type: AnswerComment
comment on: http://stackoverflow.com/a/48158554
type: Comment
score: 0

sorting
tags question: http://stackoverflow.com/q/48105979
tags question: http://stackoverflow.com/q/48133283
tags question: http://stackoverflow.com/q/48084878
tags question: http://stackoverflow.com/q/48156752
tags question: http://stackoverflow.com/q/48080245
tags question: http://stackoverflow.com/q/48089167
tags question: http://stackoverflow.com/q/48156839
tags question: http://stackoverflow.com/q/48106143
tags question: http://stackoverflow.com/q/48108787
tags question: http://stackoverflow.com/q/48157533
tags question: http://stackoverflow.com/q/48083885
type: Tag
tags question: http://stackoverflow.com/q/48099555
tags question: http://stackoverflow.com/q/48147185
tags question: http://stackoverflow.com/q/48118831
tags question: http://stackoverflow.com/q/48045316
tags question: http://stackoverflow.com/q/48171666
tags question: http://stackoverflow.com/q/48162419
tags question: http://stackoverflow.com/q/48156392
tags question: http://stackoverflow.com/q/48065753
tags question: http://stackoverflow.com/q/48064468
tag name: sorting
tags question: http://stackoverflow.com/q/48061766
tags question: http://stackoverflow.com/q/48122930
tags question: http://stackoverflow.com/q/48116533
tags question: http://stackoverflow.com/q/48039359
tags question: http://stackoverflow.com/q/48023356
tags question: http://stackoverflow.com/q/48017422
tags question: http://stackoverflow.com/q/48072007
tags question: http://stackoverflow.com/q/48102142
tags question: http://stackoverflow.com/q/48084262
tags question: http://stackoverflow.com/q/48042915

http://stackoverflow.com/q/48079856
upvote count: 2
score: 1
has title: Binary operation in numpy
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48079944
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/48079947
has body: I Have an array which looks like this, array([[[-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], ..., [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024]], [[-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], ..., [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024]], [[-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], ..., [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024]], ..., [[-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], [-1024, -1024, -1024, ..., -1024, -1024, -1024], Its a lengthy array with many unique elements, how do i do an operation where if the value is greater than 100 make the value 1 else make all values 0. I tried resulted = np.array([0 if x &lt; 100 else 1 for x in new_one]) But i get, ValueError Traceback (most recent call last) in () ----> 1 resulted = np.array([0 if x &lt; 100 else 1 for x in new_one]) &lt;ipython-input-72-77697094b8bd&gt; in &lt;listcomp&gt;(.0) ----&gt; 1 resulted = np.array([0 if x &lt; 100 else 1 for x in new_one]) ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Any ideas on how i can take this forward?Thanks in advance.
has answer: http://stackoverflow.com/a/48079947
favorite count: 0
has comment: http://stackoverflow.com/comment/83133686
accepted answer: http://stackoverflow.com/a/48079944
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48025964
has answer: http://stackoverflow.com/a/48026138
has answer: http://stackoverflow.com/a/48026141
downvote count: 0
possible better answer: http://stackoverflow.com/a/48026138
has comment: http://stackoverflow.com/comment/83021457
favorite count: 0
has comment: http://stackoverflow.com/comment/83021874
has body: I want to add all co-ordinates of line as shown below coordinates = [] for line in lines: for x1,y1,x2,y2 in line: coordinates.extend((x1,y1),(x2,y2)) To retrieve x and y co-ordinates later for further calculation x,y = zip(*coordinates) I get error TypeError: extend() takes exactly one argument (2 given). How can I achieve above without calling extend twice coordinates.extend((x1,y1)) coordinates.extend((x2,y2))
tagged with: python
has comment: http://stackoverflow.com/comment/83021744
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83021870
has answer: http://stackoverflow.com/a/48026097
upvote count: 1
has answer: http://stackoverflow.com/a/48026162
type: Question
accepted answer: http://stackoverflow.com/a/48026097
score: 1
has title: Adding multiple tuples to a list

http://stackoverflow.com/comment/83286529
has text: FYI, as you can see in [the reference](https://docs.python.org/2/reference/simple_stmts.html#the-import-statement), `__all__` need not be a list, but must be a "*a sequence of strings*".
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48153804

queue
tags question: http://stackoverflow.com/q/48015117
type: Tag
tags question: http://stackoverflow.com/q/48015613
tag name: queue
tags question: http://stackoverflow.com/q/48024167
tags question: http://stackoverflow.com/q/48072477

mysql-python
tags question: http://stackoverflow.com/q/48024806
tags question: http://stackoverflow.com/q/48065353
type: Tag
tags question: http://stackoverflow.com/q/48149893
tags question: http://stackoverflow.com/q/48025907
tags question: http://stackoverflow.com/q/48118224
tags question: http://stackoverflow.com/q/48051206
tags question: http://stackoverflow.com/q/48050323
tag name: mysql-python

http://stackoverflow.com/q/48037903
tagged with: python
score: -2
has title: Categorise data: if value is x then y
type: AnsweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/48037933
type: Question
tagged with: conditional-statements
upvote count: 0
accepted answer: http://stackoverflow.com/a/48037933
answer count: 1
favorite count: 0
has body: I have a column of values like this in a dataframe: 0 0 1.047297 1 1.038211 2 1.035080 3 1.005149 and I would like to create a new column where if the value in one 'cell' of the column is greater than x then it will return 1 and if not, then 0. Essentially I'm trying to mimic an excel function: if(cell &gt; x,1,0) It's a blindingly simple task, but I just can't find a simple answer - help would be appreciated!

http://stackoverflow.com/q/48110641
answer count: 2
has title: how to split two words into single word in a list in a easy way in python
has comment: http://stackoverflow.com/comment/83199366
tagged with: python
has answer: http://stackoverflow.com/a/48110725
has comment: http://stackoverflow.com/comment/83196654
favorite count: 0
has body: I have a list like this, my_list = ["one two","three two"] I want to convert it to, out_list=["one","two","three","two"] I am getting the output by doing, out_list=[item.split() for item in my_list] out_list=sum(out_list,[]) I am looking for the easiest way to do the same in a single line, but I hope there is a simple way to do this in python, Thanks in advance!
has answer: http://stackoverflow.com/a/48110674
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83196696
has comment: http://stackoverflow.com/comment/83197323
linked to: http://stackoverflow.com/q/29068413
possible better answer: http://stackoverflow.com/a/48110725
downvote count: 2
upvote count: 1
duplicate of: http://stackoverflow.com/q/29068413
has comment: http://stackoverflow.com/comment/83197671
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/83199004
has comment: http://stackoverflow.com/comment/83197381
score: -1
accepted answer: http://stackoverflow.com/a/48110674
type: Question

http://stackoverflow.com/comment/83077464
type: QuestionComment
comment on: http://stackoverflow.com/q/48052125
has text: @LPR btw , if you like other answers , you can upvote :-)
score: 0
type: Comment

http://stackoverflow.com/comment/83179665
has text: @HallgeirWilhelmsen I've added an ND version.
comment on: http://stackoverflow.com/a/48101532
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48158451
possible better answer: http://stackoverflow.com/a/48158585
downvote count: 0
has title: extract specific tags from html using python beautiful soup
favorite count: 0
tagged with: beautifulsoup
has body: From the following html html=' Born (1994-01-28) 28 January 1994 (age 23)[1] Medellín, Colombia ' I wanted to get ['Medellin','Colombia'] So far I've got the following code soup3=BeautifulSoup(html,'html.parser') spans=soup3.findAll('tr') [el.text for el in soup3.find_all('a')] Which produces ['[1]', 'Medellín', 'Colombia'] however the first item to sup class as well, and I don't want it. Could you provide clues? I don't want to reference the 2nd and 3rd positions of the list, since I don't if other htmls would have the 1st position ([1]0
accepted answer: http://stackoverflow.com/a/48158646
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: web-scraping
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48158585
has answer: http://stackoverflow.com/a/48158646
answer count: 2

http://stackoverflow.com/a/48056788
has comment: http://stackoverflow.com/comment/83086016
type: Answer
answers question: http://stackoverflow.com/q/48056360
has body: import re get_jsession = re.search(r'jsessionid=([A-Za-z0-9.]+)',script_) print(get_jsession.group(1)) &gt;&gt;&gt; '1D5QS4DA6C148DC4C14QS4CS5.1FDS5F4DSV1A64DA5DA'
score: 0

http://stackoverflow.com/q/48085929
has comment: http://stackoverflow.com/comment/83146788
answer count: 1
has body: For each of the 4 processes of my parallelized big-computation job, I would like to test if some number is member of a big 4GB set S. When using this method, the problem is that t = Process(target=somefunc,args=(S,)) passes the 4GB of data to each process, and this is too big for my computer (4*4 = 16 GB)! How to use S as a global variable in this multiprocessing job, instead of having to pass (and duplicate) S to each process? from multiprocessing import Process from random import randint def somefunc(S): a = randint(0, 100) # simplified example print a in S return def main(): S = set([1, 2, 7, 19, 13]) # here it's a 4 GB set in my real program for i in range(4): t = Process(target=somefunc,args=(S,)) t.start() t.join() if __name__ == '__main__': main() Note: I've already thought about using a database + client/server (or even just SQlite), but I really want to use the speed of set/dict lookup, which is faster (in order of magnitude) than database call.
type: UnansweredQuestion
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/83146954
linked to: http://stackoverflow.com/q/14124588
score: 0
has comment: http://stackoverflow.com/comment/83146906
has title: Test if a number is member of a 4GB set, in each process, without duplicating set
has comment: http://stackoverflow.com/comment/83147459
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/83146825
has comment: http://stackoverflow.com/comment/83146999
has answer: http://stackoverflow.com/a/48086147
has comment: http://stackoverflow.com/comment/83146798

http://stackoverflow.com/comment/83312689
has text: With your update, it shows, all 4 are part of multiindex, not columns, this isn't a complete dataframe.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48166581

http://stackoverflow.com/comment/83121122
comment on: http://stackoverflow.com/q/48072947
has text: *"..getaddrinfo failed.."* - your DNS cannot does not resolve the hostname you have given to an IP address. This might be a problem of your DNS setup or that you have given the wrong name. In both cases the problem is not the Python code.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83321100
score: 0
type: AnswerComment
has text: @Frederico: Yeah, for built-in numeric types, separating the steps will technically make it slower, but only trivially. If you can make the code more readable by breaking it up more, do it; outside of the hottest of hot code paths (which are cases where maybe avoiding Python would be worth it), the reduced maintenance effort is more than worth the "cost" of a few nanoseconds incurred by the additional store/load instructions.
type: Comment
comment on: http://stackoverflow.com/a/48170609

http://stackoverflow.com/comment/83089901
type: Comment
type: QuestionComment
has text: Please refomat your code input. If this is your full code: you never call the function. Also, did you understand the concept of a function? Some of your code looks really weird to me
comment on: http://stackoverflow.com/q/48058780
score: 0

http://stackoverflow.com/q/48030726
has body: I want to extract "SNG_TITLE" and "ART_NAME" values from the code in "script" tag using BeautifulSoup in Python. (the whole script is too long to paste) The idea of the code is to print out the user name, all song and artist names that can be found on the given page. import requests from bs4 import BeautifulSoup base_url = 'https://www.deezer.com/en/profile/1589856782/loved' r = requests.get(base_url) soup = BeautifulSoup(r.text, 'html.parser') user_name = soup.find(class_='user-name') print(user_name.text) This prints the user name. for script in soup.find_all('script'): print(script.contents) If I understand correctly, the script I need is a dictionary, so I just need to find it and get its contents. The problem is I don't know how to specifically find exactly this "script". It doesn't have any attributes or anything that makes it unique. So I tried a loop that finds all scripts on the page and prints out their contents, but not sure how to proceed further. How do I find only this particular "script" on the page? Can I access the values in a different way?
has answer: http://stackoverflow.com/a/48031142
type: Question
has comment: http://stackoverflow.com/comment/83032346
has title: Extracting data from script tag using BeautifulSoup in Python
score: 4
upvote count: 4
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83032263
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
tagged with: deezer
has comment: http://stackoverflow.com/comment/83032358
has answer: http://stackoverflow.com/a/48031183

http://stackoverflow.com/comment/83114419
comment on: http://stackoverflow.com/q/48058080
type: Comment
score: 0
has text: @MarkPlotnick thank you sir. One link that makes it absolutely clear as to what is going on ! **Awesome reply**
type: QuestionComment

http://stackoverflow.com/a/48089877
accepted answer of: http://stackoverflow.com/q/48089590
has body: You have access to self.request.user in the form_valid of the view. But in order to limit the choices in the form you have to customize the form before it is served initially. You best override the view's get_form and set the form field's queryset: class B_Create(CreateView): model = B fields = ['b_a','b_details'] def get_form(self, *args, **kwargs): form = super(B_Create, self).get_form(*args, **kwargs) form.fields['b_a'].queryset = self.request.user.a_set.all() # form.fields['b_a'].queryset = A.objects.filter(a_user=self.request.user) return form Generally, there are three places where you can influence the choices of a ModelChoiceField: If the choices need no runtime knowledge of your data, user, or form instance, and are the same in every context where a modelform might be used, you can set limit_choices_to on the ForeignKey field itself; as module level code, this is evaluated once at module import time. The according query will be built and executed every time a form is rendered. If the choices need no runtime knowledge, but might be different in different forms, you can use custom ModelForms and set the queryset in the field definition of the respective form field. If the queryset needs any runtime information, you can either override the __init__ of a custom form and pass it any information it needs to set the field's queryset or you just modify the queryset on the form after it is created which often is a quicker fix and django's default views provide nice hooks to do that (see the code above).
downvote count: 0
answers question: http://stackoverflow.com/q/48089590
upvote count: 6
type: AcceptedAnswer
score: 6
has comment: http://stackoverflow.com/comment/83154811
type: Answer

http://stackoverflow.com/q/48154042
favorite count: 0
type: Question
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/48154191
answer count: 1
has body: Hello, I have the following two dataframes (df1, df2) and if I merge them (inner join), I get the following dataframe: In [85]: df1 = pd.DataFrame({'value' : [10, 11, 14, 16]}, index=[1, 2, 3, 3]); df1 Out[85]: value 1 10 2 11 3 14 3 16 In [86]: df2 = pd.DataFrame({'value' : [11, 15, 16]}, index=[1, 3, 3]); df2 Out[86]: value 1 11 3 15 3 16 In [87]: pd.merge(df1, df2, how='inner', left_index=True, right_index=True) Out[87]: value_x value_y 1 10 11 3 14 15 3 14 16 3 16 15 3 16 16 Instead of this, I would like to have the following dataframe value_x value_y 1 10 11 3 14 15 3 16 16 Basically in case of duplicate rows, do not do m * n merging the way it it is currently happening.
tagged with: pandas
score: 2
type: AnsweredQuestion
has title: pandas merge with duplicate values in index
has answer: http://stackoverflow.com/a/48154191
downvote count: 0

http://stackoverflow.com/q/48088323
linked to: http://stackoverflow.com/q/1816958
type: Question
tagged with: locking
has comment: http://stackoverflow.com/comment/83151775
has body: I am trying to write a python class to read the a number of images in parallel using multiprocessing.Pool and threading.Lock. My approach is to create a pool of threads which each thread will read an image and append to a member variable with list type. It will also provide a function to obtain the list when it finished reading all the images. class ReadFilePool(object): # filenames contains a list of image absolute paths def __init__(self, filenames): self.filenames = filenames self.images = [] self.lock = threading.Lock() self.pool = Pool(processes=len(self.filenames)) self.pool.map(self.read_file, [filename for filename in self.filenames]) def read_file(self, filename): image = get_image(filename) self.lock.acquire() self.images.append(image) self.lock.release() def get_images(self): images = None self.lock.acquire() if len(self.filenames) == len(self.images): images = self.images self.lock.release() return images Then I will try to loop and check if get_images is not None and process the images, e.g. images = [] completed = False pool = ReadFilePool(filenames) while not completed: images = pool.get_images() completed = (None == images) # ...process the images I tried to use the following approaches but I still got the pickle errors like TypeError: can't pickle _thread.lock objects Approach 1: __setstate__ and __getstate__ Approach 2: __call__ Unfortunately I am not too familiar with python multithreading and Lock and encountered few pickle related errors. Please kindly suggest the correct way to use these classes.
has comment: http://stackoverflow.com/comment/83151727
has title: How to use multiprocessing.Pool and threading.Lock in a class
upvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/25382455
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83268282
tagged with: python
has comment: http://stackoverflow.com/comment/83151617
answer count: 0
downvote count: 0
score: 1
tagged with: multithreading

http://stackoverflow.com/q/48108909
answer count: 1
has title: How to create array with initial value and 'decay function'?
accepted answer: http://stackoverflow.com/a/48109068
linked to: http://stackoverflow.com/q/47427603
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83194014
has body: I'm looking for a more efficient way to compute this (searched for something similar to numpy's arange): R = 0 l1 = [] gamma = 0.99 x = 12 for i in range(0, 1000): R = x - (1-gamma) * R l1.append(R) the iteration and appending are too slow
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48109068
has comment: http://stackoverflow.com/comment/83220904
score: 0

http://stackoverflow.com/q/48126332
accepted answer: http://stackoverflow.com/a/48126415
upvote count: 2
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48126415
answer count: 1
has body: I have the data from several sensors stored in a CSV file. The time resolution is one minute. The daily average for each sensor was easily calculated. I need to calculate the hourly average of the data. CSV data set format: 5/27/2016 0:00:00 Temperature 39 25 5/27/2016 0:00:00 Pressure 12 39 5/27/2016 0:00:00 Humidity 19 79 . . . 5/27/2016 0:01:00 Temperature 39 25 First is date, second is time, third is parameter name, fourth is parameter code, and last one is value. Relevant part of my code: import pandas as pd import numpy as np df = pd.read_csv('2016-05-27.csv') Count_Row=df.shape[0] #gives number of row count print("The number of rows is", Count_Row) Parameter_code = 11201 timestamp= [] Par_value = [] n = 0 for rown in range(0,Count_Row): if df.iloc[rown,3] == Parameter_code: temp = df.iloc[rown, 4] if temp != 'nan': Par_value.append(float (temp)) timestamp.append(df.iloc[rown, 1]) n += 1 print("total sapmles", n) print (timestamp) daily_avg = np.average(Par_value) print("The daily average ", daily_avg) Question: Is there any method to this hourly averaging?
favorite count: 0
has title: How to calculate the hourly average of my data?
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
has comment: http://stackoverflow.com/comment/83229380

http://stackoverflow.com/q/48108582
type: Question
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/88537411
has comment: http://stackoverflow.com/comment/83192532
score: 15
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/58949265
has comment: http://stackoverflow.com/comment/83192682
has comment: http://stackoverflow.com/comment/83199395
has title: How to interpret scipy.stats.probplot results?
has answer: http://stackoverflow.com/a/58949265
favorite count: 0
tagged with: statistics
accepted answer: http://stackoverflow.com/a/55910735
has comment: http://stackoverflow.com/comment/83192909
tagged with: python
upvote count: 15
has comment: http://stackoverflow.com/comment/83212082
has body: I wanted to use scipy.stats.probplot() to perform some gaussianity test on mydata. from scipy import stats _,fit=stats.probplot(mydata, dist=stats.norm,plot=ax) goodness_fit="%.2f" %fit[2] The documentation says: Generates a probability plot of sample data against the quantiles of a specified theoretical distribution (the normal distribution by default). probplot optionally calculates a best-fit line for the data and plots the results using Matplotlib or a given plot function. probplot generates a probability plot, which should not be confused with a Q-Q or a P-P plot. Statsmodels has more extensive functionality of this type, see statsmodels.api.ProbPlot. But if google probability plot, it is a common name for P-P plot, while the documentation says not to confuse the two things. Now I am confused, what is this function doing?
has answer: http://stackoverflow.com/a/55910735
downvote count: 0
has comment: http://stackoverflow.com/comment/88462820
has comment: http://stackoverflow.com/comment/88420384
tagged with: plot

http://stackoverflow.com/a/48203440
score: 0
type: AcceptedAnswer
type: Answer
has body: If you execute the project in local, you would get that error(google.appengine.api error). Basically it has to be executed on a server. The server can be started using your terminal. 1) Go to the project path(root folder of all files in the project,eg: appengine) 2) start the server using $ dev_appserver.py app.yaml. It starts server at localhost port 8000 as the default one. 3) In the server start depends on the handler and its path specified (like '/' or '/testjob') try localhost:8000/ or localhost:8000/testjob 4) All the logs written in the program will be shown in the terminal. For logs try using 'logging' module , make sure to mention the logging level else basic level logs are not shown
accepted answer of: http://stackoverflow.com/q/48110614
answers question: http://stackoverflow.com/q/48110614

http://stackoverflow.com/comment/83207545
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48078162
has text: Welcome to Stackoverflow! "Thank you" comments are not needed (but I appreciate it of course); if an answer is useful for you, you should upvote it (upwards triangle next to the answer). If it solves your issue, you should accept it (check mark next to the answer).
score: 0

http://stackoverflow.com/comment/83135180
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48080345
has text: This solves the problem. But what if i couldn't modify the function hypotenuse as the function in the actual problem given to me is imported through a library.
type: AnswerComment

http://stackoverflow.com/comment/83098147
type: Comment
comment on: http://stackoverflow.com/a/48061531
score: 0
type: AnswerComment
has text: multiprocessing.map() is guaranteed to be "in order", also you're mentioning "threads" when multiprocessing works with processes

http://stackoverflow.com/comment/83095242
type: Comment
has text: I think I'm getting @A.Joly's point. I'll try to rectify it. :)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48061280

http://stackoverflow.com/q/48156310
score: -1
upvote count: 2
has comment: http://stackoverflow.com/comment/83292233
downvote count: 3
answer count: 1
tagged with: flask
has comment: http://stackoverflow.com/comment/83294224
has answer: http://stackoverflow.com/a/48157803
type: AnsweredQuestion
has body: I am a beginner programmer looking for some help with my code. This is my first attempt at this. I have only been programming for a little while now and have hit a rode block. Here is the flask for a button that I am trying to make work: from flask import Flask from flask import Flask, flash, redirect, render_template, request, session, abort, url_for import os app = Flask(__name__, static_url_path='/static') @app.route('/home', methods=['POST', 'GET']) def run_home(): if request.method == 'POST': if request.form['bob'] == 'home': pass return redirect('home', code=302, Response=None) elif request.method == 'GET': return render_template('home.html', form=form) Here is the html that is associated with the flask above. I need help making the buttons work and have gotten stuck. I am trying to use a table to arrange the buttons that link to the different pages. Can anyone help me with figuring out how to do this? Home Page List of Comics Books These are books containing collections of issues. Issues These are individual issues. Date/Time: Thanks for the help.
has title: Beginner Programmer trying to get flask buttons working from a form
favorite count: 0
has comment: http://stackoverflow.com/comment/83295003
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/48157803

http://stackoverflow.com/q/48083856
has body: I am working on a Python/Kivy application that is supposed to ask a user a series of math questions. My issue is that I don't know how to reset to another question, or get a list of questions. Here is a snippet of my main.py code: def answers(self): """Ask the specified number of questions, and return the number of correct answers""" self.correct_answers = [] self.incorrect_answers = [] self.ids.questions_easy.text = "2 + 2" def check_answer1(self): self.answers() self.answer1 = self.ids.answers.text score = 0 if self.answer1 == "4": self.correct_answers.append(self.answer1) self.ids.result_easy.text = 'Correct, Great Job!' score += 1 self.ids.score_easy.text = str(score) else: self.incorrect_answers.append(self.answer1) self.ids.result_easy.text = 'Incorrect, Better Luck Next Time!' score -= 1 self.ids.score_easy.text = '-1' As you can see it asks the question what 2+2 is. That answer is then stored in the list "self.correct_answers". If it is wrong it is stored in the list "self.incorrect_answers". My problem is that I don't know how to make a series of 20 questions or so. I have been trying to think of ways like a "for" loop, or something along those lines, but am not sure how i'd go about doing that. What complicates things is that my .kv file puts the question in a TextInput box, and the answer in another TextInput box, along with the result and score in two separate TextInput Boxes. That's a total of four boxes that are working together, so i'm not sure how to clear the question text input box and then generate a new question, while deleting the old question. For example, since 2+2 is my first question, I don't know how to change the TextInput box to ask what 3+3 is, or 9x9. Below is a snippet of my .kv code: &lt;Easy_Level&gt;: name: 'Easy_1' GridLayout: rows: 6 spacing: 10 padding: 10 Label: text: "Question" TextInput: id: questions_easy text: "" multiline: False readonly: True Label: text: 'Answer' TextInput: id: answers text: "" multiline: False Label: tex…
has answer: http://stackoverflow.com/a/48084714
answer count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83142803
tagged with: kivy
score: 0
has title: Kivy/Python Math Application
type: Question

http://stackoverflow.com/comment/83371542
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48164343
type: Comment
has text: and **Server-Side** `#-------------# getPORT_NUMBER = 8080 getSIZE = 1 gethostName = gethostbyname( '0.0.0.0' ) getSocket = socket( AF_INET, SOCK_DGRAM ) getSocket.bind( (gethostName, getPORT_NUMBER) ) print("Waiting for connection on port {0}\n".format(getPORT_NUMBER)) dataGet = '' while dataGet != 'A' : dataGet, clientAddr = getSocket.recvfrom(getSIZE) dataGet = dataGet.decode('utf-8') #-------------#`

http://stackoverflow.com/q/48133772
has title: setup.py installing package and script - NameError referencing package from script
type: Question
score: 0
has body: I'm struggling with my first Python package + script project using setuptools. Here's a skeleton of my setup.py: setuptools.setup( name=&lt;PROJECT&gt;, packages=[&lt;PACKAGE_NAME&gt;], scripts=['bin/&lt;PACKAGE_NAME&gt;.py'], python_requires='&gt;=3', ) My package is in package_name/ and my script, which has the same base name as the package, is in bin/package_name.py. The script does from package_name import *. There are no dependencies. When I run python3 setup.py install, it succeeds. Thereafter, when I do import package_name in a Python console, it succeeds. But when I run the script from the command line, it fails with a NameError on the first reference to a component from the package. I've reproduced the same error on Mac OS X and Linux. Why does it fail this way, but doesn't throw an ImportError? How can I fix my script or my setup.py?
answer count: 1
tagged with: setuptools
has answer: http://stackoverflow.com/a/48133822
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48133822
tagged with: python

http://stackoverflow.com/q/48029844
has answer: http://stackoverflow.com/a/48029933
accepted answer: http://stackoverflow.com/a/48029909
tagged with: python
has answer: http://stackoverflow.com/a/48046964
linked to: http://stackoverflow.com/q/952914
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48029907
downvote count: 1
type: Question
tagged with: split
score: 3
has title: Split a string and save them to a list with Python
has answer: http://stackoverflow.com/a/48029909
upvote count: 4
has answer: http://stackoverflow.com/a/48030270
has body: I have a string that I inserted a space into it in all different positions and saved them to a list. Now this list of strings with space in them, I want to split those strings and put the output in one list, when am doing this, it happens that am having multiple list inside: This is the code am working on: var ='sans' res = [var[:i]+' '+var[i:] for i in range(len(var))] // The previous line: AM adding a space to see maybe that would generate other words cor = [res[i].split() for i in range (len(res))] And this is the output am getting: &gt;&gt;&gt; cor [['sans'], ['s', 'ans'], ['sa', 'ns'], ['san', 's']] What am expecting: &gt;&gt;&gt; cor ['sans', 's', 'ans', 'sa', 'ns', 'san', 's'] Am new to python, I don't know what am missing. Thanks
tagged with: string
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48029933
answer count: 5

http://stackoverflow.com/comment/83236448
type: QuestionComment
has text: i want to applied this function to that file ..how?
comment on: http://stackoverflow.com/q/48129820
score: 0
type: Comment

http://stackoverflow.com/comment/83213735
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48105487
has text: So I can across something similar that says " 17.10 uses wayland by default, not x11; thus, there is not an .xauthority file. Also by default, root is not allowed access to your terminal; thus, can not run GUI programs." No sure if the that could be the problem. The "-H" command you suggested is supposed to work but I get the "no module named 'Xlib' " error . Hopefully that explains the x11 thing I'm having trouble understanding.

http://stackoverflow.com/q/48016665
has answer: http://stackoverflow.com/a/48017322
tagged with: python
has comment: http://stackoverflow.com/comment/83002696
has answer: http://stackoverflow.com/a/48016797
accepted answer: http://stackoverflow.com/a/48017322
tagged with: oop
has body: I have the following code: import time class output_letter(): def output_a(self): print('a') def output_b(self): print('b') def output_c(self): print('c') ............. def output_z(self): print('z') class wait_time(): def sleep_2(self): time.sleep(2) out = output_letter() out.output_a() I would like to tack the functionality of class wait_time.sleep_2 onto the beginning of class output_letter . As an example if I were to create a hypothetical class "combined" , I could do c=combined() c.output_a # would wait 2 seconds and then print 'a' The problem is that I don't want to rewrite all the functions of 'output_letter', I just want to add the same functionality to all of its functions. Its not clear to me how to do this , or if this is possible with inheritance or composition.
upvote count: 3
has comment: http://stackoverflow.com/comment/83002671
answer count: 5
has comment: http://stackoverflow.com/comment/83002673
has answer: http://stackoverflow.com/a/48017644
has comment: http://stackoverflow.com/comment/83002904
downvote count: 0
has answer: http://stackoverflow.com/a/48016724
linked to: http://stackoverflow.com/q/6307761
type: Question
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/23117717
favorite count: 0
possible better answer: http://stackoverflow.com/a/48016701
has title: combining functions from 2 classes in python
has comment: http://stackoverflow.com/comment/83003024
has answer: http://stackoverflow.com/a/48016701

http://stackoverflow.com/q/48074878
score: 3
accepted answer: http://stackoverflow.com/a/48075023
linked to: http://stackoverflow.com/q/47804682
answer count: 1
downvote count: 0
tagged with: amazon-web-services
favorite count: 0
tagged with: aws-lambda
has body: I am getting null response while my code is successfully working. I am not able to get response from dialogAction, i am import json import requests def getdata(intent_name, fulfillment_state, message): response = { 'dialogAction': { 'type': 'Close', 'intentName': intent_name, 'fulfillmentState': fulfillment_state, 'message': message } } return response def lambda_handler(event,context): payload = {'userId':4,'type':'PARENT'} r = requests.post("http://ec2-54-226-57-153.compute-1.amazonaws.com:8080/Tracking/rest/api", data=json.dumps(payload), headers = {'Content-Type': 'application/json','Accept': 'application/json'}) print(r.content) getdata( 'currentIntent', 'Fulfilled', { 'contentType': 'PlainText', 'content': 'message' } )
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48075023
upvote count: 3
tagged with: amazon-lex
has title: Null response from dialogAction(Python)
type: Question

http://stackoverflow.com/comment/127534974
type: Comment
comment on: http://stackoverflow.com/a/65118276
score: 0
type: AnswerComment
has text: As an alternative to repeat you an also use `np.kron(..., np.ones((2,2,1)))` (for a `HxWxC` image), but I'm not sure which one is faster.

http://stackoverflow.com/q/48161305
has body: This is the function: c = [] def badsort(l): v = 0 m = len(l) while v&lt;m: c.append(min(l)) l.remove(min(l)) v+=1 return c Although I realize that this is a very inefficient way to sort, I was wondering what the time complexity of such a function would be, as although it does not have nested loops, it repeats the loop multiple times.
tagged with: big-o
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/48161354
tagged with: python
possible better answer: http://stackoverflow.com/a/48161352
has answer: http://stackoverflow.com/a/48161352
type: AnsweredQuestion
tagged with: performance
linked to: http://stackoverflow.com/q/22188851
type: Question
has comment: http://stackoverflow.com/comment/83302035
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48161354
has answer: http://stackoverflow.com/a/48161349
has title: Understanding how to measure the time complexity of a function
answer count: 3

http://stackoverflow.com/comment/83088113
has text: @user2269232 The issue is that there are many widgets that can be added to QTableWidget, and each widget has its own signals and events, so making a generic code that maps all those fields is impossible, instead a QTableWidgetItem is a custom class to work with QTableWidget and therefore the methods and signals are known.
comment on: http://stackoverflow.com/a/48057869
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83062764
comment on: http://stackoverflow.com/q/48045772
score: 1
has text: In what ways do those solutions fail?
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48087798
has body: .lower() is a built-in method for the String object in Python. The reason you need the parenthesis is to execute the function on the string. Without the parenthesis, you are simply accessing the String.lower attribute, which is a function pointer. Therefore, without the parenthesis, you are setting response = String.lower, which will not pass the if statement.
answers question: http://stackoverflow.com/q/48087719
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/83178418
type: Comment
has text: I also don't understand why I got a -1 for this question. I feel like I posted all of the relevant information. Anyways, os.remove does work, so thank you. Unfortunately, there are other commands that I want to run that will need to be run via os.system (or some other variant). Any further ideas?
score: 0
comment on: http://stackoverflow.com/q/48098813
type: QuestionComment

http://stackoverflow.com/comment/83202718
score: 1
has text: Related: https://stackoverflow.com/q/28850070/3001761
comment on: http://stackoverflow.com/q/48113538
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83239659
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48131172
has text: Possible duplicate of [Does Python have a ternary conditional operator?](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator)
score: 0

http://stackoverflow.com/comment/83369007
score: 0
has text: @RafaelRuiz done that!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48158601

http://stackoverflow.com/a/48163796
has body: Try like this from bs4 import BeautifulSoup import requests page_size = 0 for page_no in range(1,1000): source = requests.get('example.com/users.php?page={}'.format(page_size)).text page_size += 20 soup = BeautifulSoup(source, 'lxml') for profile in soup.select("li h3 a"): print(profile.text)
accepted answer of: http://stackoverflow.com/q/48163642
score: 1
answers question: http://stackoverflow.com/q/48163642
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

string
tags question: http://stackoverflow.com/q/48101298
tags question: http://stackoverflow.com/q/48173141
tags question: http://stackoverflow.com/q/48022826
tags question: http://stackoverflow.com/q/48058173
tags question: http://stackoverflow.com/q/48142171
tags question: http://stackoverflow.com/q/48138209
tags question: http://stackoverflow.com/q/48079136
tags question: http://stackoverflow.com/q/48160240
tags question: http://stackoverflow.com/q/48078589
tags question: http://stackoverflow.com/q/48042187
tags question: http://stackoverflow.com/q/48102713
tags question: http://stackoverflow.com/q/48066106
tags question: http://stackoverflow.com/q/48089141
tags question: http://stackoverflow.com/q/48029844
tags question: http://stackoverflow.com/q/48051028
tags question: http://stackoverflow.com/q/48140773
tags question: http://stackoverflow.com/q/48024364
tags question: http://stackoverflow.com/q/48019434
tags question: http://stackoverflow.com/q/48159774
tags question: http://stackoverflow.com/q/48071936
tags question: http://stackoverflow.com/q/48075861
tags question: http://stackoverflow.com/q/48140997
tags question: http://stackoverflow.com/q/48038949
tags question: http://stackoverflow.com/q/48059490
tags question: http://stackoverflow.com/q/48014709
tags question: http://stackoverflow.com/q/48099923
tags question: http://stackoverflow.com/q/48080163
tags question: http://stackoverflow.com/q/48093977
tag name: string
tags question: http://stackoverflow.com/q/48073161
tags question: http://stackoverflow.com/q/48114426
tags question: http://stackoverflow.com/q/48135230
tags question: http://stackoverflow.com/q/48098250
tags question: http://stackoverflow.com/q/48035569
tags question: http://stackoverflow.com/q/48064939
tags question: http://stackoverflow.com/q/48101933
tags question: http://stackoverflow.com/q/48139438
tags question: http://stackoverflow.com/q/48050994
tags question: http://stackoverflow.com/q/48029355
tags question: http://stackoverflow.com/q/48018163
tags question: http://stackoverflow.com/q/48166197
tags question: http://stackoverflow.com/q/48083074
tags question: http://stackoverflow.com/q/48087091
tags question: http://stackoverflow.com/q/48024154
type: Tag
tags question: http://stackoverflow.com/q/48088460
tags question: http://stackoverflow.com/q/48069247
tags question: http://stackoverflow.com/q/48163799
tags question: http://stackoverflow.com/q/48134942
tags question: http://stackoverflow.com/q/48092816
tags question: http://stackoverflow.com/q/48082018
tags question: http://stackoverflow.com/q/48102372
tags question: http://stackoverflow.com/q/48124183
tags question: http://stackoverflow.com/q/48171985
tags question: http://stackoverflow.com/q/48049087
tags question: http://stackoverflow.com/q/48018096
tags question: http://stackoverflow.com/q/48040033
tags question: http://stackoverflow.com/q/48101624
tags question: http://stackoverflow.com/q/48157753
tags question: http://stackoverflow.com/q/48171953
tags question: http://stackoverflow.com/q/48031699
tags question: http://stackoverflow.com/q/48052657
tags question: http://stackoverflow.com/q/48039359
tags question: http://stackoverflow.com/q/48153907
tags question: http://stackoverflow.com/q/48130286
tags question: http://stackoverflow.com/q/48150638
tags question: http://stackoverflow.com/q/48137755
tags question: http://stackoverflow.com/q/48087117
tags question: http://stackoverflow.com/q/48102142
tags question: http://stackoverflow.com/q/48122170
tags question: http://stackoverflow.com/q/48117508
tags question: http://stackoverflow.com/q/48115430

http://stackoverflow.com/comment/83290172
has text: Thanks for the tip. I will test it soon
comment on: http://stackoverflow.com/q/48133636
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48161583
has title: How to extract Deployed OSB Source code from Environment or SB Console or Weblogic
answer count: 1
tagged with: osb
tagged with: scripting
tagged with: python
tagged with: unix
has answer: http://stackoverflow.com/a/48162391
type: UnansweredQuestion
type: Question
tagged with: weblogic
score: 0
has body: Could anyone please help me in getting a way to get the source code from Environment or SB Console or Weblogic. I created the python script whick exports the JAR, but I need the source code. Because if I unjar the jar, I do not get the exact source code, as file names are shorten and some code is added by itself in wsdls, xqueries etc. I don't want that. Here's my wlst Python/Jython Script: from java.io import FileInputStream from java.io import FileOutputStream from java.util import ArrayList from java.util import Collections from com.bea.wli.sb.util import EnvValueTypes from com.bea.wli.config.env import EnvValueQuery; from com.bea.wli.config import Ref from com.bea.wli.config.customization import Customization from com.bea.wli.config.customization import FindAndReplaceCustomization import sys #======================================================================================= # Utility function to load properties from a config file #======================================================================================= def exportAll(exportConfigFile): def exportAll(exportConfigFile): try: print "Loading export config from :", exportConfigFile exportConfigProp = loadProps(exportConfigFile) adminUrl = exportConfigProp.get("adminUrl") exportUser = exportConfigProp.get("exportUser") exportPasswd = exportConfigProp.get("exportPassword") exportJar = exportConfigProp.get("exportJar") customFile = exportConfigProp.get("customizationFile") passphrase = exportConfigProp.get("passphrase") project = sys.argv[2] if project == None : project = exportConfigProp.get("project") connectToServer(exportUser, exportPasswd, adminUrl) ALSBConfigurationMBean = findService("ALSBConfiguration", "com.bea.wli.sb.management.configuration.ALSBConfigurationMBean") print "ALSBConfiguration MBean found" print "Input project: ", project if project == None : ref = Ref.DOMAIN collection = Collections.singleton(ref) if passphrase == None : print "Export the config" theBytes = ALSBConfigurationMB…

tensorflow
tags question: http://stackoverflow.com/q/48029704
tags question: http://stackoverflow.com/q/48092772
tags question: http://stackoverflow.com/q/48065685
tags question: http://stackoverflow.com/q/48091693
tags question: http://stackoverflow.com/q/48084798
tags question: http://stackoverflow.com/q/48090546
tags question: http://stackoverflow.com/q/48119449
tags question: http://stackoverflow.com/q/48101576
tags question: http://stackoverflow.com/q/48144747
tags question: http://stackoverflow.com/q/48132740
tags question: http://stackoverflow.com/q/48115096
tags question: http://stackoverflow.com/q/48045708
tags question: http://stackoverflow.com/q/48161116
tags question: http://stackoverflow.com/q/48152124
tags question: http://stackoverflow.com/q/48157005
tags question: http://stackoverflow.com/q/48088038
tags question: http://stackoverflow.com/q/48158113
tags question: http://stackoverflow.com/q/48058198
tags question: http://stackoverflow.com/q/48065227
tags question: http://stackoverflow.com/q/48073274
tags question: http://stackoverflow.com/q/48159562
tags question: http://stackoverflow.com/q/48123840
tags question: http://stackoverflow.com/q/48054531
tags question: http://stackoverflow.com/q/48148135
tags question: http://stackoverflow.com/q/48112219
tags question: http://stackoverflow.com/q/48102364
tags question: http://stackoverflow.com/q/48106948
tags question: http://stackoverflow.com/q/48169759
tags question: http://stackoverflow.com/q/48070972
tags question: http://stackoverflow.com/q/48162440
tags question: http://stackoverflow.com/q/48133855
tags question: http://stackoverflow.com/q/48151888
tags question: http://stackoverflow.com/q/48101886
tags question: http://stackoverflow.com/q/48162322
tags question: http://stackoverflow.com/q/48154925
tags question: http://stackoverflow.com/q/48041560
tags question: http://stackoverflow.com/q/48027263
tags question: http://stackoverflow.com/q/48158547
tags question: http://stackoverflow.com/q/48034478
tags question: http://stackoverflow.com/q/48145877
tags question: http://stackoverflow.com/q/48119488
tags question: http://stackoverflow.com/q/48167838
tags question: http://stackoverflow.com/q/48144477
tags question: http://stackoverflow.com/q/48138837
tags question: http://stackoverflow.com/q/48133160
tags question: http://stackoverflow.com/q/48037418
tags question: http://stackoverflow.com/q/48115671
tags question: http://stackoverflow.com/q/48056795
tags question: http://stackoverflow.com/q/48131255
tags question: http://stackoverflow.com/q/48033687
tags question: http://stackoverflow.com/q/48056014
tags question: http://stackoverflow.com/q/48143753
tags question: http://stackoverflow.com/q/48158454
tags question: http://stackoverflow.com/q/48132420
tags question: http://stackoverflow.com/q/48166440
tags question: http://stackoverflow.com/q/48027801
tags question: http://stackoverflow.com/q/48140133
tags question: http://stackoverflow.com/q/48014769
tags question: http://stackoverflow.com/q/48058861
tags question: http://stackoverflow.com/q/48037343
tags question: http://stackoverflow.com/q/48169791
tags question: http://stackoverflow.com/q/48051192
tags question: http://stackoverflow.com/q/48097044
tag name: tensorflow
tags question: http://stackoverflow.com/q/48081743
tags question: http://stackoverflow.com/q/48042012
tags question: http://stackoverflow.com/q/48015770
tags question: http://stackoverflow.com/q/48072635
tags question: http://stackoverflow.com/q/48053907
tags question: http://stackoverflow.com/q/48160602
tags question: http://stackoverflow.com/q/48061976
tags question: http://stackoverflow.com/q/48014964
tags question: http://stackoverflow.com/q/48105997
tags question: http://stackoverflow.com/q/48150876
tags question: http://stackoverflow.com/q/48074158
tags question: http://stackoverflow.com/q/48111639
tags question: http://stackoverflow.com/q/48140989
tags question: http://stackoverflow.com/q/48077625
tags question: http://stackoverflow.com/q/48129814
tags question: http://stackoverflow.com/q/48027341

http://stackoverflow.com/q/48071828
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83117299
type: UnansweredQuestion
has body: please give the solution based on my code below, and also can you help me, so in order to enter the country name, user must see the country list first, i mean in first step user must input 'country' and then it gives response the 'c_list' like in the screenshot, and then user can input the country they choose, so it was like there was a step before you can input country name :) from nltk.tokenize import sent_tokenize, word_tokenize c_list = ['Australia', 'CHINA', 'Combodia', 'EUROPE', 'HONG KONG','INDIA', 'INDONESIA', 'JAPAN', 'KOREA', 'MALAYSIA', 'Myanmar', 'New Zealand', 'PHILIPPINES', 'Russia', 'senchilles', 'SINGAPORE', 'Sri Lanka', 'TAIWAN', 'TestCountry', 'THAILAND', 'UNITED KINGDOM', 'USA', 'Vietnam', 'XYTestCountry'] r = input(" user input : ") wt = (word_tokenize(r)) if any("country" in s for s in wt): reply = c_list else: reply = "Sorry I cant answer that right now." print(reply) the result above is from api response my question is, how can i add code that can check if the country exist in the 'c_list' list when user reply any country listed above. Then if its exist i want to pass the country code on this json if matched with user reply, then i want to pass the country code to another api request and so on "DATA": { "data":[ { "countryId": "26", "countryCode" : "AU", "name" : "Australia" }, { "countryId": "17", "countryCode" : "ID", "name" : "Indonesia" } ] }
tagged with: request
has answer: http://stackoverflow.com/a/48072309
tagged with: list
has comment: http://stackoverflow.com/comment/83117564
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/83117492
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/83117839
has comment: http://stackoverflow.com/comment/83117595
score: 0
has title: Python matched the value on json response based on user input, and pass the value to variable
tagged with: python

http://stackoverflow.com/a/48037032
type: Answer
score: 0
has body: Other than reshape and transpose, another similar solution: swapaxes in the Numpy library. The following line swaps the first axis with the 3rd one in an array im. im.swapaxes(0,2) if a is an ndarray, then a view of a is returned; otherwise a new array is created. --Quoted from numpy-1.13.0 Docs Reference How does numpy.swapaxes work?
answers question: http://stackoverflow.com/q/48036473

http://stackoverflow.com/q/48056160
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48056184
has title: Python List remove multiple items
tagged with: list
score: 0
has answer: http://stackoverflow.com/a/48056321
has answer: http://stackoverflow.com/a/48056273
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48063482
has comment: http://stackoverflow.com/comment/83084707
has body: I am trying to remove multiple occurrences of a value from a list.The output does not remove any of the desired items. def rem(a,li): try: while a in li == True: li.remove(a) print('Updated list: ',li) except ValueError: print(a,' is not located in the list ',li) Example to trying out function: L = [1,2,3,45,3,2,3,3,4,5] rem(2,L) Output: Updated list: [1, 2, 3, 45, 3, 2, 3, 3, 4, 5]
has answer: http://stackoverflow.com/a/48056409
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83084742

http://stackoverflow.com/comment/83123354
score: 0
type: QuestionComment
type: Comment
has text: Does the output _really_ need to be a list? IMHO, a tuple would be more appropriate here.
comment on: http://stackoverflow.com/q/48074511

http://stackoverflow.com/comment/83079587
type: QuestionComment
comment on: http://stackoverflow.com/q/48053654
has text: @PatrickHaugh the dataset is to big unfortunately. I tried to use this solution https://stackoverflow.com/a/15073977/8943781 and lets say from this solution I want to keep 1 5 7 columns
score: 0
type: Comment

http://stackoverflow.com/q/48124647
has comment: http://stackoverflow.com/comment/83226411
has answer: http://stackoverflow.com/a/48124785
has comment: http://stackoverflow.com/comment/83226264
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/48124785
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/83231326
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83226374
possible better answer: http://stackoverflow.com/a/48124783
score: 1
has answer: http://stackoverflow.com/a/48124783
has comment: http://stackoverflow.com/comment/83226354
has comment: http://stackoverflow.com/comment/83226352
downvote count: 1
type: Question
has title: How can I check if a line in a file has information or not in Python 3.6?
has answer: http://stackoverflow.com/a/48126624
has body: I am trying to create a memory set, saved in a separate text file stored in a different location. I have tried to use some of the suggestions on this site, but maybe my code is different. I am using Python 3.6. Here is my code: df = open("Memory.txt", 'r') askforfname = df.readlines() df.close() print (askforfname) if '\n' in open("Memory.txt", 'r').readlines(): df.close() name = input("What is your name?: \n") Bigname = name.title() df = open("Memory.txt", 'w') df.write(Bigname) df.close() else: df = open("Memory.txt", 'r') returning_name = df.readlines() print("Welcome back" + str(returning_name)) df.close() I am using print(askforfname) in the fourth line just to make sure the data is being read from the proper line, and it is. But it just skips over the if command, as if it came out false, and continues right the the else command, even if the line is blank. I am just a beginner in programming, and don't know much, so i don't know if I'm just making a simple mistake lol. And yes, I understand my code must be inefficient, but since I am new, this is just me experimenting with code.
has answer: http://stackoverflow.com/a/48124800
has comment: http://stackoverflow.com/comment/83226455
has comment: http://stackoverflow.com/comment/83226384
has comment: http://stackoverflow.com/comment/83226418

http://stackoverflow.com/q/48076009
has answer: http://stackoverflow.com/a/48076093
has title: ImportError: No module named cv2 error upon running .py file in terminal
favorite count: 0
linked to: http://stackoverflow.com/q/19876079
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
tagged with: opencv
has comment: http://stackoverflow.com/comment/83125884
has comment: http://stackoverflow.com/comment/83130125
has comment: http://stackoverflow.com/comment/83155661
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83129140
has answer: http://stackoverflow.com/a/48076121
has body: I am having trouble running a python script file that contains import opencv command. Upon running the file, it gives the following error: ImportError: No module named cv2 I then ran pip install python-opencv but it gave Could not find a version that satisfies the requirement python-opencv (from versions: ) No matching distribution found for python-opencv error. Does anyone know what the issue might be? I was able to run this python file at first but I haven't been able to run after that.
score: 0
tagged with: macos

http://stackoverflow.com/q/48053389
has answer: http://stackoverflow.com/a/48053912
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/65937843
downvote count: 0
has answer: http://stackoverflow.com/a/65937843
score: 1
type: Question
has title: DBAPI syntax with pd.read_sql_query() call
answer count: 2
tagged with: pandas
linked to: http://stackoverflow.com/q/41324503
upvote count: 1
has body: I want to read all of the tables contained in a database into pandas data frames. This answer does what I want to accomplish, but I'd like to use the DBAPI syntax with the ? instead of the %s, per the documentation. However, I ran into an error. I thought this answer may address the problem, but I'm now posting my own question because I can't figure it out. Minimal example import pandas as pd import sqlite3 pd.__version__ # 0.19.1 sqlite3.version # 2.6.0 excon = sqlite3.connect('example.db') c = excon.cursor() c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''') c.execute("INSERT INTO stocks VALUES ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)") c.execute('''CREATE TABLE bonds (date text, trans text, symbol text, qty real, price real)''') c.execute("INSERT INTO bonds VALUES ('2015-01-01', 'BUY', 'RSOCK', 90, 23.11)") data = pd.read_sql_query('SELECT * FROM stocks', excon) # &gt;&gt;&gt; data # date trans symbol qty price # 0 2006-01-05 BUY RHAT 100.0 35.14 But when I include a ? or a (?) as below, I get the error message pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT * FROM (?)': near "?": syntax error. Problem code c.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = c.fetchall() # &gt;&gt;&gt; tables # [('stocks',), ('bonds',)] table = tables[0] data = pd.read_sql_query("SELECT * FROM ?", excon, params=table) It's probably something trivial that I'm missing, but I'm not seeing it!
tagged with: sqlite
linked to: http://stackoverflow.com/q/305378
accepted answer: http://stackoverflow.com/a/48053912
favorite count: 0
tagged with: python

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/48081783
tags question: http://stackoverflow.com/q/48133252
tags question: http://stackoverflow.com/q/48162795
tags question: http://stackoverflow.com/q/48143581
tags question: http://stackoverflow.com/q/48015950
tags question: http://stackoverflow.com/q/48124321
tags question: http://stackoverflow.com/q/48163472
tags question: http://stackoverflow.com/q/48130987
tags question: http://stackoverflow.com/q/48036198
tags question: http://stackoverflow.com/q/48096126
tags question: http://stackoverflow.com/q/48050890
tags question: http://stackoverflow.com/q/48076329
tags question: http://stackoverflow.com/q/48041147
tags question: http://stackoverflow.com/q/48049543
tags question: http://stackoverflow.com/q/48051368
tags question: http://stackoverflow.com/q/48154581
tags question: http://stackoverflow.com/q/48171159
tags question: http://stackoverflow.com/q/48064631
tags question: http://stackoverflow.com/q/48057296
tags question: http://stackoverflow.com/q/48070420
tags question: http://stackoverflow.com/q/48098901
tags question: http://stackoverflow.com/q/48046074
tags question: http://stackoverflow.com/q/48113984
tags question: http://stackoverflow.com/q/48129522
tags question: http://stackoverflow.com/q/48058968
type: Tag
tags question: http://stackoverflow.com/q/48127921
tags question: http://stackoverflow.com/q/48023363
tags question: http://stackoverflow.com/q/48037575
tags question: http://stackoverflow.com/q/48016895
tags question: http://stackoverflow.com/q/48046842
tags question: http://stackoverflow.com/q/48158451
tags question: http://stackoverflow.com/q/48020309
tags question: http://stackoverflow.com/q/48085924
tags question: http://stackoverflow.com/q/48053060
tags question: http://stackoverflow.com/q/48060598
tags question: http://stackoverflow.com/q/48087095
tags question: http://stackoverflow.com/q/48048657
tags question: http://stackoverflow.com/q/48127614
tags question: http://stackoverflow.com/q/48049385
tags question: http://stackoverflow.com/q/48146486
tags question: http://stackoverflow.com/q/48113488
tags question: http://stackoverflow.com/q/48033398
tags question: http://stackoverflow.com/q/48137510
tags question: http://stackoverflow.com/q/48123895
tags question: http://stackoverflow.com/q/48156310
tags question: http://stackoverflow.com/q/48127619
tags question: http://stackoverflow.com/q/48092543
tags question: http://stackoverflow.com/q/48136266
tags question: http://stackoverflow.com/q/48081968
tags question: http://stackoverflow.com/q/48040431
tags question: http://stackoverflow.com/q/48070250
tags question: http://stackoverflow.com/q/48037685
tags question: http://stackoverflow.com/q/48095700
tags question: http://stackoverflow.com/q/48018710
tags question: http://stackoverflow.com/q/48140693
tags question: http://stackoverflow.com/q/48067768
tags question: http://stackoverflow.com/q/48122975
tags question: http://stackoverflow.com/q/48139676
tags question: http://stackoverflow.com/q/48139722
tags question: http://stackoverflow.com/q/48028931
tags question: http://stackoverflow.com/q/48027655
tag name: html
tags question: http://stackoverflow.com/q/48051158
tags question: http://stackoverflow.com/q/48171741
tags question: http://stackoverflow.com/q/48131052
tags question: http://stackoverflow.com/q/48037337
tags question: http://stackoverflow.com/q/48060113
tags question: http://stackoverflow.com/q/48107708
tags question: http://stackoverflow.com/q/48032941
tags question: http://stackoverflow.com/q/48158330
tags question: http://stackoverflow.com/q/48141221
tags question: http://stackoverflow.com/q/48124409
tags question: http://stackoverflow.com/q/48022598
tags question: http://stackoverflow.com/q/48020177
tags question: http://stackoverflow.com/q/48098278
tags question: http://stackoverflow.com/q/48041025
tags question: http://stackoverflow.com/q/48091964
tags question: http://stackoverflow.com/q/48145958
tags question: http://stackoverflow.com/q/48034696

http://stackoverflow.com/comment/83167823
comment on: http://stackoverflow.com/q/48096518
type: Comment
score: 4
has text: Duplicate - https://stackoverflow.com/questions/47970683/vectorize-a-numpy-discount-calculation?
type: QuestionComment

http://stackoverflow.com/a/48055785
downvote count: 0
has comment: http://stackoverflow.com/comment/83083925
type: Answer
has body: Maybe you should take a step back and ask, why do we even use CRTP in C++. The reason for CRTP is that we might want to use a class polymorphically at compile-time or elide the virtual function call overhead. Now Python does not have a “compile time” and because it is not statically typed all function calls are essentially virtual. Thus, you will obtain the same behaviour as with CRTP just with regular inheritance. class Base(object): def get_value(self): print("This is the derived value:", self.value) class Derived(Base): def __init__(self, value): self.value = value d = Derived(5) d.get_value() # prints "This is the derived value: 5" Live example If, on the other hand you want CRTP to interact with the Python3 typing system, then you might want to checkout this question: Python 3 type hint for a factory method on a base class returning a child class instance
upvote count: 6
has comment: http://stackoverflow.com/comment/83083848
has comment: http://stackoverflow.com/comment/128221631
answers question: http://stackoverflow.com/q/48055678
score: 6

http://stackoverflow.com/a/74299987
type: Answer
answers question: http://stackoverflow.com/q/48046020
score: 0
has body: In a loop, find indices of zeros in list and nb of ones in front of first zero. In another loop, find the next zero, reduce nOnesInFront by the index difference between current and previous zero def solution(A): count = 0; zeroIndices = [] nOnesInFront = 0; foundZero = False for i in range(len(A)): if A[i] == 0: foundZero = True zeroIndices.append(i) elif foundZero: nOnesInFront += 1; if nOnesInFront == 0: return 0 #no ones in front of a zero if not zeroIndices: return 0 #no zeros iPrev = zeroIndices[0] count = nOnesInFront for i in zeroIndices[1:]: nOnesInFront -= (i-iPrev) - 1 #decrease nb of ones by the differnce between current and previous zero index iPrev = i count += nOnesInFront if count &gt; 1000000000: return -1 else: return count Here are some tests cases to verify the solution: print(solution([0, 1, 0, 1, 1])) # 5 print(solution([0, 1, 1, 0, 1])) # 4 print(solution([0])) # 0 print(solution([1])) # 0 print(solution([1, 0])) # 0 print(solution([0, 1])) # 1 print(solution([1, 0, 0])) # 0 print(solution([1, 0, 1])) # 1 print(solution([0, 0, 1])) # 2

http://stackoverflow.com/q/48074180
accepted answer: http://stackoverflow.com/a/48074319
linked to: http://stackoverflow.com/q/30112202
possible better answer: http://stackoverflow.com/a/57385805
has answer: http://stackoverflow.com/a/48074319
answer count: 2
tagged with: pandas
favorite count: 0
has title: replace a pandas series with the closest values from another series
has answer: http://stackoverflow.com/a/57385805
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
has body: I have a series A, e.g. 1.3, 4.5, 10.11 and a series B 0.8, 5.1, 10.1, 0.3, and I would like to get a series C with the closest number from A for every element in B: 1.3, 4.5, 10.11, 1.3 btw, if it simplifies things the closest number from A can be the closest number larger than the number in B, so the answer can also be 1.3, 10.11, 10.11, 1.3 related to How do I find the closest values in a Pandas series to an input number?
type: Question
upvote count: 2

http://stackoverflow.com/comment/83184284
comment on: http://stackoverflow.com/a/48104079
score: 0
type: Comment
has text: I still get the same error after trying all your code. is there a way to do it without a for loop
type: AnswerComment

http://stackoverflow.com/a/48099304
has comment: http://stackoverflow.com/comment/110330373
has comment: http://stackoverflow.com/comment/83173981
has comment: http://stackoverflow.com/comment/83283371
has body: tf.estimator.DNNClassifier constructor has weight_column argument: weight_column: A string or a _NumericColumn created by tf.feature_column.numeric_column defining feature column representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. If it is a string, it is used as a key to fetch weight tensor from the features. If it is a _NumericColumn, raw tensor is fetched by key weight_column.key, then weight_column.normalizer_fn is applied on it to get weight tensor. So just add a new column and fill it with some weight for the rare class: weight = tf.feature_column.numeric_column('weight') ... tf.estimator.DNNClassifier(..., weight_column=weight) [Update] Here's a complete working example: import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('mnist', one_hot=False) train_x, train_y = mnist.train.next_batch(1024) test_x, test_y = mnist.test.images, mnist.test.labels x_column = tf.feature_column.numeric_column('x', shape=[784]) weight_column = tf.feature_column.numeric_column('weight') classifier = tf.estimator.DNNClassifier(feature_columns=[x_column], hidden_units=[100, 100], weight_column=weight_column, n_classes=10) # Training train_input_fn = tf.estimator.inputs.numpy_input_fn(x={'x': train_x, 'weight': np.ones(train_x.shape[0])}, y=train_y.astype(np.int32), num_epochs=None, shuffle=True) classifier.train(input_fn=train_input_fn, steps=1000) # Testing test_input_fn = tf.estimator.inputs.numpy_input_fn(x={'x': test_x, 'weight': np.ones(test_x.shape[0])}, y=test_y.astype(np.int32), num_epochs=1, shuffle=False) acc = classifier.evaluate(input_fn=test_input_fn) print('Test Accuracy: %.3f' % acc['accuracy'])
has comment: http://stackoverflow.com/comment/83283608
has comment: http://stackoverflow.com/comment/83173796
type: Answer
accepted answer of: http://stackoverflow.com/q/48098951
has comment: http://stackoverflow.com/comment/83174921
has comment: http://stackoverflow.com/comment/83174699
has comment: http://stackoverflow.com/comment/83356430
has comment: http://stackoverflow.com/comment/83206403
score: 8
has comment: http://stackoverflow.com/comment/83283229
has comment: http://stackoverflow.com/comment/83283768
answers question: http://stackoverflow.com/q/48098951
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/83207668
type: AcceptedAnswer

http://stackoverflow.com/q/48111347
has answer: http://stackoverflow.com/a/48111454
tagged with: python
has body: I currently have a code which basically does a few clicks on a website...the code works fine but for some weird reason I can't seem to be able to use Firefox while the automation process is going on. is there a way to stop is ? i.e. be able to use another Firefox window while having the process run my_file = open("links.txt", "r") for url in my_file: browser.get(url) time.sleep(2) browser.find_element_by_css_selector('button.popover').click() time.sleep(2) browser.find_element_by_css_selector('div.faux_field').click() time.sleep(2) browser.find_element_by_css_selector('button.apply').click() time.sleep(2) browser.find_element_by_css_selector('button.click-to-esign').click()
type: UnansweredQuestion
tagged with: selenium
type: Question
has title: Clicking with selenium python
score: 0
answer count: 1

http://stackoverflow.com/a/49887013
score: 0
answers question: http://stackoverflow.com/q/48150314
type: Answer
has body: def skeleton_handler_function(frame): for data in frame.SkeletonData: print("Positions : " , data.SkeletonPositions) try this to get skeleton position data

http://stackoverflow.com/comment/84859135
comment on: http://stackoverflow.com/q/48138094
score: 0
type: QuestionComment
has text: You would need to delete the message before writing it back to the queue, which is risky as it's not an atomic update.
type: Comment

http://stackoverflow.com/comment/83299982
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48160105
has text: I would try something like : redValues = sum(im[:,:][0]) but I´m not sure about the syntax

http://stackoverflow.com/a/48108784
accepted answer of: http://stackoverflow.com/q/48107991
type: Answer
answers question: http://stackoverflow.com/q/48107991
downvote count: 0
score: 1
type: AcceptedAnswer
has body: I believe you need list comprehension with flattening with function window for sliding window: s = pd.Series(["s1, s2, s3, s4","s1, s2, s3"]) print (s) 0 s1, s2, s3, s4 1 s1, s2, s3 dtype: object from itertools import islice #https://stackoverflow.com/a/6822773/2901002 def window(seq, n=2): "Returns a sliding window (of width n) over data from the iterable" " s -&gt; (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result a = [y for x in s.str.split(',\s+') for y in list(window(x))] print (a) [('s1', 's2'), ('s2', 's3'), ('s3', 's4'), ('s1', 's2'), ('s2', 's3')] df = pd.DataFrame(a, columns=['a','b']) print (df) a b 0 s1 s2 1 s2 s3 2 s3 s4 3 s1 s2 4 s2 s3
upvote count: 1

http://stackoverflow.com/a/48066591
has comment: http://stackoverflow.com/comment/83108795
accepted answer of: http://stackoverflow.com/q/48066452
has body: The strings returned by readlines() have an EOL character ('\n') at the end. Try stripping the line before using it. for i in fromDirectory: i = i.strip() bsname = os.path.basename(os.path.dirname(i)) copy_tree(str(i), "H:/spectraDB_copy/{}/".format(bsname))
has comment: http://stackoverflow.com/comment/83109928
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83108873
type: Answer
answers question: http://stackoverflow.com/q/48066452

http://stackoverflow.com/a/48038900
has comment: http://stackoverflow.com/comment/83048501
has comment: http://stackoverflow.com/comment/83048513
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83048650
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48038838
answers question: http://stackoverflow.com/q/48038838
type: Answer
has body: These are some things to help you solve this. I will remove this as it is not an answer. import re import pandas as pd data = dict(col=['texttexttext 0036.01 texttext','texttexttext 0006.21 texttext']) df = pd.DataFrame(data) re.findall("0\d{3}\.\d{2}", str(df['col'])) #Simplified your regex Effectively creates: ['0036.01', '0006.21'] How about trying this: re.findall("0\d{3}\.\d{2}",' '.join(df['col'].tolist())) And if middle rows are not working, extract a sample, e.g., and share that with us: print('\n'.join(df['col'][200:220].tolist()))
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83048629

http://stackoverflow.com/q/48043555
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48043920
tagged with: python
score: 3
has body: thats my first question on stackoverflow. I was mostly able to find here what i need to know. Thanks a lot for this btw. However. If i try to kill my ProcessPoolExecutor it will just work through the whole queue which is generated (.. i think so?). Is there any simple way to immediately clean the queue of a Processpoolexecutor? from concurrent.futures import ProcessPoolExecutor from time import sleep from random import randint def something_fancy(): sleep(randint(0, 5)) return 'im back!' class Work: def __init__(self): self.exe = ProcessPoolExecutor(4) def start_procs(self): for i in range(300): t = self.exe.submit(something_fancy) t.add_done_callback(self.done) def done(self, f): print f.result() def kill(self): self.exe.shutdown() if __name__ == '__main__': work_obj = Work() work_obj.start_procs() sleep(5) work_obj.kill() So what i want to do is generate a Queue by 300 which gets worked out by 4 processes. After 5 seconds it should just quit. I need to use processes because of gil btw.
upvote count: 3
has title: Python Processpoolexecutor - kill queue?
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48043610
tagged with: concurrent.futures

http://stackoverflow.com/comment/83026405
has text: Also, show your code. Following a link elsewhere that you somehow adapted for your needs does not count.
comment on: http://stackoverflow.com/q/48028103
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48132910
answer count: 1
has comment: http://stackoverflow.com/comment/83256742
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: c++
score: 1
has comment: http://stackoverflow.com/comment/83248267
has answer: http://stackoverflow.com/a/48141260
has title: How to handle void pointers in SWIG director methods in Python
type: Question
tagged with: swig
has comment: http://stackoverflow.com/comment/83259631
has body: I am using SWIG to wrap a C++ library as a Python library. The C++ library exposes abstract classes for the user to inherit from it, so we use directors in SWIG to handle. It works mostly OK (with some tweaking). One issue is that this C++ class has two methods as follows: class Base { void* getObject(); void doSomething(void* o); } The user is expected to implement these methods and the object returned by the user in getObject() is then passed to the doSomething() method. The problem is that when going through SWIG, the doSomething() method in Python receives a SwigPyObject with wrapped type 'void*', so we cannot use the original Python object methods as we would hope. And casting is not an option since it's Python (or is it?). Does anyone have any insights? I found some related issues here and there, but none of them seem to address exactly my case, and I've already tried many things to solve it, without any success. Let me know if you need more details and I'll provide it. Thanks a lot!
has comment: http://stackoverflow.com/comment/83255573
downvote count: 0

http://stackoverflow.com/comment/83285654
type: Comment
type: QuestionComment
has text: No sorry, I need to do convolution and pooling along the sample-series (4800000) for each track (10). I'm getting confused sorry
comment on: http://stackoverflow.com/q/48146412
score: 0

http://stackoverflow.com/comment/129431135
comment on: http://stackoverflow.com/q/48059700
type: Comment
score: 0
has text: This is not a duplicate. The other question is about quoting command-line arguments to impact how they are received by `sys.argv` in a script; this question is about passing them *to an interactive REPL session*.
type: QuestionComment

http://stackoverflow.com/comment/83292886
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48156823
type: Comment
has text: Nice one! Like this.

http://stackoverflow.com/q/48101387
answer count: 3
has comment: http://stackoverflow.com/comment/83178762
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48101465
upvote count: 1
tagged with: python
has title: Python Tidy Code
score: 1
has body: I edit all my Python files on a remote Centos server using nano. This seems to work well. Occasionally I need to make a small change that changes the indention over the entire file. Is there an easy way to convert all the one space indents to 4 space etc? I have looked at PythonTidy.py but it seems to change too many things.
has answer: http://stackoverflow.com/a/48101500
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/48104490
has comment: http://stackoverflow.com/comment/83178122
linked to: http://stackoverflow.com/q/1024435
has comment: http://stackoverflow.com/comment/83179211
tagged with: linux

http://stackoverflow.com/comment/83266020
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48127931
has text: This is too complicated, when you can simply store the identifiers in a list or dictionary

http://stackoverflow.com/comment/83123970
has text: Thanks man things are pretty much clear now.. i am going to give it a go...
type: AnswerComment
comment on: http://stackoverflow.com/a/48065234
type: Comment
score: 1

http://stackoverflow.com/a/48082605
has comment: http://stackoverflow.com/comment/83142188
type: Answer
has comment: http://stackoverflow.com/comment/83264404
upvote count: 1
has comment: http://stackoverflow.com/comment/83140120
accepted answer of: http://stackoverflow.com/q/48081783
has body: You could use custom CSS to override the visual spacing from the tags. Something like this. td > p, li > p { margin: 0; } I think it is strange, however, that your output generates tags in tables, as that is not what docutils does, assuming that is what rst2html5 is based upon. I would suggest you contact the author of that library. Edit: Here's my HTML output using Sphinx and your reST sample: Table H1 Table H2a Table H2b a1 b1 a2 b2 a3 b3
has comment: http://stackoverflow.com/comment/83150643
has comment: http://stackoverflow.com/comment/83141556
answers question: http://stackoverflow.com/q/48081783
has comment: http://stackoverflow.com/comment/136719551
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/a/48121091
has comment: http://stackoverflow.com/comment/83218961
upvote count: 1
answers question: http://stackoverflow.com/q/48120967
has body: The basic pattern is to have a class or a function for each frame. Each of these classes or functions creates a single Frame, and places all of its widgets in that frame. Then, all you need to do to switch frames is delete the current frame, and call the function or object to create the new frame. It's as simple as that. Some examples on this site: Switching between frames in python with functions Switch between two frames in tkinter
type: Answer
has comment: http://stackoverflow.com/comment/83218850
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83218876

http://stackoverflow.com/q/48026046
has answer: http://stackoverflow.com/a/48026218
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83021776
has comment: http://stackoverflow.com/comment/83021730
type: Question
has body: import smtplib email_user = 'myemail' email_send = 'myemail' server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login( email_user, "PASSWORD") msg = "Hello" server.sendmail(email_user,email_send, msg) server.quit() Error Message: Traceback (most recent call last): File "python", line 7, in socket.gaierror: [Errno -2] Name or service not known I am using Repl.it; is this the reason for it not working?
has title: (Repl.it) Python 3 Email Not Working?
score: 0
answer count: 1
tagged with: email

http://stackoverflow.com/a/48100406
type: Answer
answers question: http://stackoverflow.com/q/48100173
downvote count: 1
has comment: http://stackoverflow.com/comment/83176025
upvote count: 5
score: 4
has body: If you have confusion matrix in the form of: cmat = [[ 5, 7], [25, 37]] Following simple function can be made: def myscores(smat): tp = smat[0][0] fp = smat[0][1] fn = smat[1][0] tn = smat[1][1] return tp/(tp+fp), tp/(tp+fn) Testing: print("precision and recall:", myscores(cmat)) Output: precision and recall: (0.4166666666666667, 0.16666666666666666) Above function can also be extended to produce other scores, the formulae for which are mentioned on https://en.wikipedia.org/wiki/Confusion_matrix
has comment: http://stackoverflow.com/comment/83175966

http://stackoverflow.com/comment/115629604
type: AnswerComment
score: 0
has text: What is the difference between class member variable and global variable and its advantages?
type: Comment
comment on: http://stackoverflow.com/a/48141726

aiff
tag name: aiff
type: Tag
tags question: http://stackoverflow.com/q/48026172

http://stackoverflow.com/a/48019339
answers question: http://stackoverflow.com/q/48018843
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: This is indeed a NumPy-style operation, it's not particularly mathematical or Matrix-like. To use NumPy methods, first convert Q to a NumPy array first, and then search through the array, applying lambda expr: Zc in expr.free_symbols. Putting everything together, idx = np.nonzero(np.vectorize(lambda expr: Zc in expr.free_symbols)(np.array(Q))) returns (array([0, 1]), array([1, 0])) Caution: this is not a tuple of row-column coordinates, this is a tuple [row coordinates], [column coordinates]. For example, if there was also Zc in bottom right cornet, then idx is (array([0, 1, 2]), array([1, 0, 2])) A more readable form, and the one you probably want, is obtained with np.array(idx).T: array([[0, 1], [1, 0], [2, 2]]) Or, without NumPy, just loop over the elements and report what you found. found = [] for i in range(2): for j in range(2): if Zc in Q[i, j].free_symbols: found.append([i, j]) print(found) Here is a modification of this loop where we search for an expression, such as the product of two symbols. The test is whether the expression is modified if that product is replaced by 0. Also, apparently you don't want other symbols present? Check for that is added too. found = [] for i in range(3): for j in range(3): if Q[i, j].subs(Zc*L, 0) != Q[i, j] and Q[i, j].free_symbols == set([L, Zc]): found.append([i, j]) print(found)
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83028427
has comment: http://stackoverflow.com/comment/83028141
has comment: http://stackoverflow.com/comment/83028209
has comment: http://stackoverflow.com/comment/83026871
accepted answer of: http://stackoverflow.com/q/48018843
has comment: http://stackoverflow.com/comment/83025569

http://stackoverflow.com/q/48107796
type: Question
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has body: I am getting Wrong column names by this code: Why is this happening? Is there any other way to do this? names = {'SYMBOL','CLMP'} data2 = pd.read_csv(filePath +"\\"+ fileNameCM2+'.csv',skiprows = 1, index_col=False, names = names,header=None) df3 = pd.DataFrame(data2) print(df3.head()) OUTPUT: CLMP SYMBOL 0 ACC 853921 1 ADANIENT 2758466 2 ADANIPORTS 7591819 3 ADANIPOWER 11774513 4 AJANTPHARM 257752 EXPECTED: SYMBOL CLMP 0 ACC 853921 1 ADANIENT 2758466 2 ADANIPORTS 7591819 3 ADANIPOWER 11774513 4 AJANTPHARM 257752
tagged with: python
score: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/48107806
answer count: 1
downvote count: 1
tagged with: import-from-csv
type: AnsweredQuestion
has title: PANDAS: Wrong column names while importing data from csv file
favorite count: 0
has answer: http://stackoverflow.com/a/48107806

http://stackoverflow.com/comment/83148602
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48086824
has text: how do you compare "abc" > "cdeFG" ?

http://stackoverflow.com/comment/83174068
comment on: http://stackoverflow.com/q/48092543
type: QuestionComment
type: Comment
has text: %if.... Etc. Would be cool if it would work without PHP
score: 0

http://stackoverflow.com/q/48089391
score: 1
type: Question
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has title: How to add a password log in into screen scraping with Beautiful Soup / Python
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83153421
has answer: http://stackoverflow.com/a/48089528
has body: I am trying to figure out how to add a piece of code that will help the code I already have to sign into the website so that my program can screen scrape the data I need. The sign in is a simple "Log in ID" and "Password". After sign in I am redirected to a page that is not the page I want to scrape data from. I have been unable to test my code. My code always gives me "None". I assuming this is due to it not being able to sign into the website. I am trying to screen scrape: &lt;div class="Object7069"&gt; &lt;div style="font-family:verdana; font-size:9px; text-align:right; color:#999999;"&gt; 124 of 256 &lt;/div&gt; &lt;/div&gt; It is a simple variable "124/256" that will change over time. My code: import urllib2 from bs4 import BeautifulSoup quote_page = 'https://admin252.acellus.com/StudentFunctions/progress.html' page = urllib2.urlopen(quote_page) soup = BeautifulSoup(page, 'html.parser') price_box = soup.find('div', attrs={'class':'object7069'}) price = price_box print price
has comment: http://stackoverflow.com/comment/83153914

http://stackoverflow.com/q/48082819
score: 0
has answer: http://stackoverflow.com/a/48082935
tagged with: python
accepted answer: http://stackoverflow.com/a/48082935
tagged with: django
type: Question
type: AnsweredQuestion
has title: Get full URL image with object ID - Django Rest Framework
has body: I write a Serializer in Django Rest Framework about Profile have Avatar Image but I want to get full URL Image instead of ID. My Serializers (which return profile_pic_url is ID): class ProfileDetailSerializer(ModelSerializer): profile_pic_url = SerializerMethodField() class Meta: model = Profile fields = [ 'profile_pic_url', ] def get_profile_pic_url(self, obj): request = self.context.get('request') profile_pic_url = obj.profile_pic_url.image return request.build_absolute_uri(profile_pic_url) This code returns this issues: 'ImageFieldFile' object has no attribute 'find'
answer count: 1
tagged with: django-rest-framework

beautifulsoup
tags question: http://stackoverflow.com/q/48133252
tags question: http://stackoverflow.com/q/48125988
tags question: http://stackoverflow.com/q/48152899
tags question: http://stackoverflow.com/q/48120003
tags question: http://stackoverflow.com/q/48018277
tags question: http://stackoverflow.com/q/48051766
tags question: http://stackoverflow.com/q/48043726
tags question: http://stackoverflow.com/q/48076329
tags question: http://stackoverflow.com/q/48149218
tags question: http://stackoverflow.com/q/48047250
tags question: http://stackoverflow.com/q/48154581
tags question: http://stackoverflow.com/q/48051371
tags question: http://stackoverflow.com/q/48022598
tags question: http://stackoverflow.com/q/48057296
tags question: http://stackoverflow.com/q/48118464
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/48079366
tags question: http://stackoverflow.com/q/48036885
tags question: http://stackoverflow.com/q/48116316
tags question: http://stackoverflow.com/q/48025409
tags question: http://stackoverflow.com/q/48162390
tags question: http://stackoverflow.com/q/48089010
tags question: http://stackoverflow.com/q/48057647
tags question: http://stackoverflow.com/q/48054837
tags question: http://stackoverflow.com/q/48042083
tags question: http://stackoverflow.com/q/48016895
tags question: http://stackoverflow.com/q/48158451
tags question: http://stackoverflow.com/q/48030398
tags question: http://stackoverflow.com/q/48154085
tags question: http://stackoverflow.com/q/48016979
tags question: http://stackoverflow.com/q/48052647
tags question: http://stackoverflow.com/q/48143126
tags question: http://stackoverflow.com/q/48081376
tags question: http://stackoverflow.com/q/48069806
tags question: http://stackoverflow.com/q/48158028
tags question: http://stackoverflow.com/q/48127614
tags question: http://stackoverflow.com/q/48052549
type: Tag
tags question: http://stackoverflow.com/q/48107191
tags question: http://stackoverflow.com/q/48032574
tags question: http://stackoverflow.com/q/48133838
tags question: http://stackoverflow.com/q/48085980
tags question: http://stackoverflow.com/q/48172972
tags question: http://stackoverflow.com/q/48030726
tags question: http://stackoverflow.com/q/48135461
tags question: http://stackoverflow.com/q/48037685
tags question: http://stackoverflow.com/q/48046518
tags question: http://stackoverflow.com/q/48136660
tags question: http://stackoverflow.com/q/48095700
tags question: http://stackoverflow.com/q/48140693
tags question: http://stackoverflow.com/q/48048955
tags question: http://stackoverflow.com/q/48130963
tags question: http://stackoverflow.com/q/48027655
tags question: http://stackoverflow.com/q/48057732
tags question: http://stackoverflow.com/q/48018096
tags question: http://stackoverflow.com/q/48131052
tags question: http://stackoverflow.com/q/48086330
tags question: http://stackoverflow.com/q/48158330
tags question: http://stackoverflow.com/q/48136266
tags question: http://stackoverflow.com/q/48105399
tags question: http://stackoverflow.com/q/48170490
tags question: http://stackoverflow.com/q/48056360
tags question: http://stackoverflow.com/q/48145958
tags question: http://stackoverflow.com/q/48022511
tags question: http://stackoverflow.com/q/48058150
tags question: http://stackoverflow.com/q/48145845
tags question: http://stackoverflow.com/q/48125300
tags question: http://stackoverflow.com/q/48111052
tags question: http://stackoverflow.com/q/48113622

http://stackoverflow.com/comment/83241813
type: Comment
comment on: http://stackoverflow.com/a/48132109
has text: When I tried installing it from the URL it didn't work, I got HTTP 404 but downloading and installing locally worked. Thanks. I guess this workaround (using the unofficial wheel) is fine for me.
type: AnswerComment
score: 0

http://stackoverflow.com/a/48117955
score: 2
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/48096294
has body: First, create a Pod running "Docker-1" application. Then Kubernetes python client to spawn a second pod with "Docker-2". You can share a volume between your pods in order to return the data to Docker1. In my code sample I'm using a host_path volume but you need to ensure that both pods are on the same node. I did add that code for readability. apiVersion: apps/v1beta2 kind: Deployment metadata: name: docker1 labels: app: docker1 spec: replicas: 1 selector: matchLabels: app: docker1 template: metadata: labels: app: docker1 spec: containers: - name: docker1 image: abhilash/docker1 ports: - containerPort: 8080 volumeMounts: - mountPath: /shared name: shared-volume volumes: - name: shared-volume hostPath: path: /shared The code of run_docker_2 handler: from kubernetes import client, config ... args = "input_combo" config.load_incluster_config() pod = client.V1Pod() pod.metadata = client.V1ObjectMeta(name="docker2") container = client.V1Container(name="docker2") container.image = "abhilash/docker2" container.args = [args] volumeMount = client.V1VolumeMount(name="shared", mount_path="/shared") container.volume_mounts = [volumeMount] hostpath = client.V1HostPathVolumeSource(path = "/shared") volume = client.V1Volume(name="shared") volume.host_path = hostpath spec = client.V1PodSpec(containers = [container]) spec.volumes = [volume] pod.spec = spec v1.create_namespaced_pod(namespace="default", body=pod) return "OK" A handler to read the returned results: @app.route('/read-results') def run_read(): with open("/shared/results.data") as file: return file.read() Note that it could be useful to add a watcher to wait for the pod to finish the job and then do some cleanup (delete the pod for instance)

http://stackoverflow.com/comment/83010937
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48020641
has text: I don't really understand what's going on so I was just experimenting. I realize now that switching makes no difference. When search is clicked, new elements from a database are populated inside the iframe. The next step is to locate an elements inside the iframe, I was trying to do it like this: SubjectList = driver.find_element_by_id("SSR_CLSRCH_WRK_SUBJECT_SRCH$0") Which gives me this error "Cannot find context with specified id" All of the tutorials online talk about swtiching between frames but have not found any info on how to handle changes within frames.
score: 0

http://stackoverflow.com/comment/83324223
has text: `Database Driver Location` is a parameter to specify where jdbc driver (jar file) is located relative to nifi root folder or absolute path. It's optional when driver (jar file) is in `nifi/lib` folder.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48169766

http://stackoverflow.com/comment/83076397
has text: Sigh. After this fix of putting that one 'import' line into the cell I'm running into the same problem with other scripts also not being able import other modules. Most modules load from the .py scripts fine. Some do not. Trying to import a ton of things from Keras and other scripts that try to make use of modules. It's making these fast.ai Jupyter Notebooks unusable.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48050873

http://stackoverflow.com/q/48130038
tagged with: nested-lists
has comment: http://stackoverflow.com/comment/83239347
has title: Working with sets/lists between functions (python)
has comment: http://stackoverflow.com/comment/83240127
has comment: http://stackoverflow.com/comment/83237910
has comment: http://stackoverflow.com/comment/83239470
type: Question
has comment: http://stackoverflow.com/comment/83238209
has comment: http://stackoverflow.com/comment/83239270
has comment: http://stackoverflow.com/comment/83239848
has comment: http://stackoverflow.com/comment/83238267
has answer: http://stackoverflow.com/a/48132460
has answer: http://stackoverflow.com/a/48132576
score: 0
answer count: 2
has body: I'm confused about how my program behaves when I work with sets between functions. I have a few functions that modify a nested list: list1. Imagine I have a 3x9 array, and position (0,0) has a set={6}, and the rest of the cells are sets {1,2,3,4,5,6} def eliminateUnique(list1, (0,0), rowColBoxLocations) takes a one value set, i.e. {6}, and pops it from all the sets in the same row, same column, and the same 3x3 box Now when I run my code, it deletes the {6} from ALL rows and columns, and the array updates. Now my question is, when this function updates the array, if there is no return list1, (and I can't use global list1 as it's in the argument above), how do I get the updated list1 array into another function? So if i call def solve(list1), and it calls (list1, (0,0), rowColBoxLocations), how do I get the new list1 back to the solve function so I can further work on it? I think my eliminate function is not updating and passing the array to my solve function. def main() list1=[[6, 0, 0, 0, 0, 0, 0, 6, 7], [3, 0, 0, 5, 7, 0, 0, 0, 9], [1, 2, 0, 8, 6, 0, 0, 0, 3]] convertToSets(list1) eliminateUnique(list1,location, listOflocations) def convertToSets(list1): s = set(range(1, 10)) list1 = [[{j} if j!=0 else s for j in i] for i in list1] return list1 def eliminateUnique(list1, location, listOfLocations): count =0 locVal = list1[location[0]][location[1]] if len(locVal)==1: lvint = list(locVal)[0] #integer value of number in set. for i in listOfLocations: if (lvint in list1[i[0]][i[1]]) and (i!=location): list1[i[0]][i[1]].remove(lvint) def solve(list1) - here's where i'm having problems! Added some code guys. main runs, calls convertToSets. 0->{1 to 9}, then passes it to eliminateUniques, and that's where I start having problems. eliminateUnique doesn't do what it is supposed to do when passing in a set. When I manually put the array inside the function, it seems fine. I think it might be to do with how I am using the sets.
has comment: http://stackoverflow.com/comment/83241156
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83238061
tagged with: python
tagged with: list

http://stackoverflow.com/a/48166963
has body: You could capture the index by wrapping the String(s) with enumerate() as shown below. def str_lookup_reverse(s, c): index_list = [] for index, char in enumerate(s): if char == c: index_list.append(index) # print(index) return index_list s = "parisa" index_list = str_lookup_reverse(s, "a") print(index_list) ## PRINTS: [1, 5]
type: Answer
answers question: http://stackoverflow.com/q/48166814
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/83297108
comment on: http://stackoverflow.com/a/48158097
type: AnswerComment
score: 0
type: Comment
has text: https://hastebin.com/exexijiveq.vbs view and the html, and thank you for sticking up with me for this long.

http://stackoverflow.com/q/48084586
tagged with: python
answer count: 0
has title: Passing argument psycopg2
has comment: http://stackoverflow.com/comment/83144063
tagged with: psycopg2
type: Question
has comment: http://stackoverflow.com/comment/83144153
score: 0
has body: I'm trying passing parameters to SQL query, however, I don't know if I'm making this correct. def getUser(user): conn = databaseConnection() cur = conn.cursor() conn.set_client_encoding('LATIN1') rows = cur.execute("SELECT * FROM mk_pessoas WHERE nome_razaosocial= %s",(user)) rows = cur.fetchall() return rows Call this function: row = getUser('brian') print row Error: TypeError: not all arguments converted during string formatting
has comment: http://stackoverflow.com/comment/83144134
type: UnansweredQuestion

http://stackoverflow.com/comment/83096489
type: Comment
type: QuestionComment
has text: Windows API function... maybe one such as ShellExecute or ShellExecuteW? .... #ironyModeOn
comment on: http://stackoverflow.com/q/48051283
score: 0

http://stackoverflow.com/q/48106028
has comment: http://stackoverflow.com/comment/83187856
type: Question
score: 3
linked to: http://stackoverflow.com/q/17873384
has comment: http://stackoverflow.com/comment/83188208
has comment: http://stackoverflow.com/comment/83187860
has comment: http://stackoverflow.com/comment/83188080
possible better answer: http://stackoverflow.com/a/70476879
upvote count: 4
has answer: http://stackoverflow.com/a/70476879
has answer: http://stackoverflow.com/a/48108628
has title: Python: Copy an `array.array`
linked to: http://stackoverflow.com/q/2612802
tagged with: arrays
tagged with: copy
has comment: http://stackoverflow.com/comment/83188040
favorite count: 0
accepted answer: http://stackoverflow.com/a/48108628
has comment: http://stackoverflow.com/comment/83188321
answer count: 3
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83208544
has body: Is there a way to copy an array.array (not a list) in Python, besides just creating a new one and copying values, or using .to_something and .from_something? I can't seem to find anything in the documentation. If not, is there a similar builtin datatype that can do this? I am working on a high-performance module, so the faster the answer, the better. My current solution is just using .to_bytes and .from_bytes, which is about 1.8 times faster from my tests.
has answer: http://stackoverflow.com/a/48106916
has comment: http://stackoverflow.com/comment/83187953
downvote count: 1

http://stackoverflow.com/comment/83329332
comment on: http://stackoverflow.com/q/48173238
type: Comment
type: QuestionComment
has text: I believe in python `ActionChains` is what you're looking for.
score: 0

http://stackoverflow.com/comment/83433662
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48066225
has text: @saaj yes, I know that this is an anti-pattern ... up to now. You are talking about polling and locking. I don't see this in my case (PosgreSQL LISTEN/NOTIFY). But maybe I am blind. You say "You don't need full ACID for it". I want it all: ACID, zero costs and a lot of fun. And up to now I do know why I should not. I am sure that performance won't be a problem. Thank you for the hint to Torrelque, Up to now I only knew python-rq.
score: 0

http://stackoverflow.com/q/48138094
tagged with: amazon-sqs
accepted answer: http://stackoverflow.com/a/48138954
answer count: 2
downvote count: 0
has title: how to implement exponential backoff in amazon sqs without writing code
tagged with: amazon-web-services
favorite count: 0
has comment: http://stackoverflow.com/comment/83260363
has comment: http://stackoverflow.com/comment/84859135
has answer: http://stackoverflow.com/a/68320021
tagged with: python
type: AnsweredQuestion
type: Question
upvote count: 12
possible better answer: http://stackoverflow.com/a/68320021
has body: I have a simple task that requires a 3rd party. When a request comes, I push it to an amazon sqs queue, pull it in a worker and call the 3rd party. In case of a time out, I want to implement an exponential backoff (try again in 2 secs, then 4 then 8, then...) with a max retry. Using python, boto -&gt; sqs I've looked for built in parameters to allow me to do so with as little code as possible (ideally, no code at all). Something like from boto import sqs def handle_message(message): try: # send a post to api except TimeOut, err: # send_back_to_itself in 2/4/8 sec if delay &lt; DELAY_LIMIT: queue.write(message, delay=secs)
has answer: http://stackoverflow.com/a/48138954
score: 12

http://stackoverflow.com/comment/83106947
comment on: http://stackoverflow.com/q/48066511
score: 0
type: Comment
type: QuestionComment
has text: While `meth2` is sleeping, your `main` is waiting at `p2.join()` and `meth1` cannot run again until the `while` loop starts again.

http://stackoverflow.com/comment/83151088
has text: https://stackoverflow.com/questions/47615761/pandas-pivot-table-with-multiple-columns-at-once
comment on: http://stackoverflow.com/q/48087693
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48066955
downvote count: 0
has comment: http://stackoverflow.com/comment/83110276
type: Answer
answers question: http://stackoverflow.com/q/48065735
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83110209
has comment: http://stackoverflow.com/comment/83108960
has comment: http://stackoverflow.com/comment/83109107
has body: It's feasible to do this with five measures. from itertools import product from numpy import negative, array_equal choices = [1, 0, -1] measures = 5 limit = len(choices)**measures//2+1 count = 0 measure_combinations = [] for p in product(*([choices]*5)): measure_combinations.append(list(p)) count += 1 if count == limit: break print (len(measure_combinations)) For instance, the inner product of one of the measure_combinations, say [1,1,0,-1,-1] with each row of the measure columns would provide a series of values upon which GoldMeasure could be regressed to obtain a correlation coefficent, and this could be done for the 122 unique possibilities. However, for 41 measures there would be 18,236,498,188,585,393,202 unique possibilities, based on part of the product of 41 repetitions of {-1,0,1}.

http://stackoverflow.com/q/48116789
has answer: http://stackoverflow.com/a/48116944
favorite count: 0
has comment: http://stackoverflow.com/comment/83210323
downvote count: 0
has answer: http://stackoverflow.com/a/48117023
accepted answer: http://stackoverflow.com/a/48117023
tagged with: python
possible better answer: http://stackoverflow.com/a/48116944
linked to: http://stackoverflow.com/q/42519
type: AnsweredQuestion
tagged with: list
score: 1
has comment: http://stackoverflow.com/comment/83210085
duplicate of: http://stackoverflow.com/q/42519
has body: I'm trying to 'rotate' a grid 90 degrees clockwise and came up with the following Python code. def rotate90(grid): rotatedGrid = grid[:] for i in range (0, len(grid)): for j in range (0, len(grid)): rotatedGrid[i][j] = grid[-(j+1)][i][:] return rotatedGrid printing rotate90(grid) on the grid [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] outputs [['7', '4', '7'], ['8', '5', '4'], ['9', '4', '7']], whereas I expected [['7', '4', '1'], ['8', '5', '2'], ['9', '6', '3']]. What is the reason for this difference? (The reason I haven't converted these to ints is that eventually I will be using '@' and '-' characters rather than numbers.)
has comment: http://stackoverflow.com/comment/83210275
type: Question
answer count: 2
tagged with: for-loop
has title: Python function to 'rotate' grid 90 degrees with for loops
upvote count: 1
linked to: http://stackoverflow.com/q/17246693

http://stackoverflow.com/comment/83269910
type: Comment
type: QuestionComment
has text: I saw at least one shader with version 120 on their github, so OpenGL 2.1 will be required.
comment on: http://stackoverflow.com/q/48135738
score: 0

http://stackoverflow.com/q/48017890
has body: I have a dataframe with two levels of multindex rows. The levels of are type: &lt;class 'pandas.tseries.index.DatetimeIndex'&gt; and &lt;class 'pandas.indexes.numeric.Int64Index'&gt; px_settlement contract_code assessment_date contract_serial 2014-01-02 201402 18.640 g14 201403 17.530 h14 201404 16.600 j14 201405 15.900 k14 201406 16.100 m14 201407 16.200 n14 201408 15.210 q14 201409 15.210 u14 201410 15.210 v14 201411 15.210 x14 I'm trying to get a slice of 'all rows where contract_serial = 201410' for example. I've tried several variations of .loc jkm_df.loc[:, 201506] TypeError: cannot do label indexing on &lt;class 'pandas.indexes.base.Index'&gt; with these indexers [201506] of &lt;class 'int'&gt; also jkm_df.loc[(:, 201506), :] ^ SyntaxError: invalid syntax What's the correct way to subselect this multiindex by assessment_date or contract_serial?
type: Question
has comment: http://stackoverflow.com/comment/83004829
has title: slicing multindex rows -- 'cannot do label indexing'
score: 0
has comment: http://stackoverflow.com/comment/83004856
answer count: 2
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/48017954
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48017926
has answer: http://stackoverflow.com/a/48017954
accepted answer: http://stackoverflow.com/a/48017926

http://stackoverflow.com/a/48049259
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48049006
has comment: http://stackoverflow.com/comment/83126011
has comment: http://stackoverflow.com/comment/83125523
type: Answer
has body: You [c/sh]ould change fhandle = open("university_towns.txt") ftext = fhandle.read().split("\n") # to with open("university_towns.txt","r") as f: d = f.readlines() # file is autoclosed here, lines are autosplit by readlines() No regex solution: def save(state,city,dic): '''convenience fnkt to add or create set entry with list of city''' if state in dic: dic[state].append(city) else: dic[state] = [] # fix for glitch dic = {} state = "" with open("university_towns.txt","r") as f: d = f.readlines() for n in d: # iterate all lines if "[edit]" in n: # handles states act_state = n.replace("[edit]","").strip() # clean up state # needed in case 2 states w/o cities follow right after each other save(act_state,"", dic) # create state in dic, no cities state = n.replace("[edit]","").strip() # clean up state else: # splits at ( takes first and splits at [ takes first removes blanks # =&gt; get city name before ( or [ city = n.split("(")[0].split("[")[0].strip() save(state,city,dic) # adds city to state in dic print (dic) Yields (re-formatted): { 'Alabama' : ['Auburn', 'Florence', 'Jacksonville', 'Livingston', 'Montevallo', 'Troy', 'Tuscaloosa', 'Tuskegee'], 'Alaska' : ['Fairbanks'], 'Arizona' : ['Flagstaff', 'Tempe', 'Tucson'], 'Arkansas': ['Arkadelphia', 'Conway', 'Fayetteville'] }
has comment: http://stackoverflow.com/comment/83070746
score: 3
downvote count: 0
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48049006

http://stackoverflow.com/comment/83278703
has text: Thanks a lot! works like a breeze. Issue solved.(Still, if I may, I find it strange that lxml a) forces me to make special arrangements for the default namespace "xml" that the original XML file does not even declare and b) that I can't extend the nsmap that the parser creates ...) Anyway, glad it works. Thanks again!!
score: 0
comment on: http://stackoverflow.com/a/48129673
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48040903
type: Answer
has body: 1) in theory no, but in practice yes. It does not reduce time complexity in O notation, but can reduce in practice as you do not consider even numbers. Hence, this program could be 2 times faster. 2) as mentioned in comment, it is generally beneficial. 3) Of course. you have just considered sqrt(i) which reduces time complexity from O(i) to O(sqrt(i)). 4) it is not a question. However, it is true. 5) Again, it is not a question. However, it is reasonable, as you have checked i is not even.
score: 0
answers question: http://stackoverflow.com/q/48040869

http://stackoverflow.com/comment/137705399
has text: In my case, VS code throws the error: **command 'extension.commandvariable.file.relativeFileDotsNoExtension' not found**
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/75772279
score: 1

http://stackoverflow.com/comment/83240018
type: QuestionComment
comment on: http://stackoverflow.com/q/48131317
has text: Thanks for proposal. If I understood correctly you will mean starting chrome like this: Chrome --disable-web-security --user-data-dir. This gives warning: you are using unsupported command line flag: --disable-web-security .... Plus it didn't fix the problem.
score: 0
type: Comment

http://stackoverflow.com/q/48124112
type: UnansweredQuestion
has body: In python, I am using the Tornado library's HTTPRequest and AsyncHTTPClient().fetch method. The response has a 403 status code. Why does Tornado raise an error on a 403 response and how can I get more information from the error response? For example, when I use the python "requests" library instead, I still get the 403 but I can inspect the body of the response and get more information, whereas Tornado raises an error and I can't access the response at all...
tagged with: python
has answer: http://stackoverflow.com/a/48124234
score: 1
upvote count: 1
has title: Tornado 403 response raises error
type: Question
has comment: http://stackoverflow.com/comment/83225415
tagged with: tornado
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/48064829
has body: In your loop, you multiply the product by j: product *= j, but you want to multiply it by element in new with the index j, therefore just change the line product *= j to product *= new[j] Corrected program: seq = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450' new = [] for n in seq: new.append(int(n)) max_prod = 0 for i in range(0, len(new)-12): product = 1 for j in range(i, i+13): product *= new[j] if product &gt; max_prod: max_prod = product print(max_prod)
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/83102960
answers question: http://stackoverflow.com/q/48064772
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48064772
type: Answer
has comment: http://stackoverflow.com/comment/83107532

http://stackoverflow.com/a/48093087
has comment: http://stackoverflow.com/comment/83160973
downvote count: 1
has comment: http://stackoverflow.com/comment/83160605
has comment: http://stackoverflow.com/comment/83161870
has comment: http://stackoverflow.com/comment/83160873
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48092637
answers question: http://stackoverflow.com/q/48092637
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83161829
has comment: http://stackoverflow.com/comment/83161532
score: 4
has body: See my comment above, you need to use a Spark DataFrame. One easy way to accomplish this would be to turn the index on the Pandas DF into a column and then convert to spark DF: df2=sqlContext.createDataFrame(df.reset_index(drop=False)) Then use: df2.write.save("s3://work/.../filename_2018-01-04_08:50:45.csv", format='csv', header=True)
has comment: http://stackoverflow.com/comment/83160660
has comment: http://stackoverflow.com/comment/83161596
type: Answer
has comment: http://stackoverflow.com/comment/83161473

http://stackoverflow.com/comment/83266904
score: 0
has text: First, almost every operations in modern DB server is thread-safe. Just imagine there are 20 different users instead of threads. Second, maybe you can consider to reconstruct your file C as does it really need to spawns 20 threads? Or using asyncio?
comment on: http://stackoverflow.com/q/48144326
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48141666
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48140773
has body: I'd use the pickle module to save the data, and instead of creating a separate file for each user, I'd save them all in dictionary and save it. Here's what I mean: import pickle # First read any existing database into memory. # database_filename = 'user_db.pkl' db_updated = False # Flag indicating database needs to rewritten. # Read the existing database if any, otherwise create an empty version. try: with open(database_filename, 'rb') as infile: database = pickle.load(infile) except FileNotFoundError: database = {} db_updated = True # Then interact with user or do other operations to it. # step = str(input("Do you have an account (yes or no)? ")) if step == "no": username = input("What do you want your username to be? ") password = input("What do you want your password to be? ") favgenre = input("What is your favourite genre? ") favartist = input("Who is your favourite artist? ") data = [password, favgenre, favartist] database[username] = data db_updated = True elif step == "yes": username = input("Please enter your username: ") if username not in database: print('Error: username {!r} not found in database'.format(username)) else: password = input("OK, please enter your password: ") data = database.get(username) if data[0] != password: print('Error: password does not match') del data else: print('username {!r} found, data: {}'.format(username, data)) else: print('Please enter "yes" or "no"') if db_updated: with open(database_filename, 'wb') as outfile: pickle.dump(database, outfile, pickle.HIGHEST_PROTOCOL) print('Database file updated') There's also info about pickle in my answer to the question Saving an Object (Data persistence).

http://stackoverflow.com/comment/83241521
has text: They are up-to-date: pycairo 1.15.4 is the last version.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48132109

http://stackoverflow.com/comment/83054967
has text: use print do display what you have in variables when you run it - maybe you have different values then you expect. Maybe you have to `strip()` spaces or "\n", or you have to do something more with your data.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48042083

http://stackoverflow.com/a/48153773
upvote count: 20
score: 20
answers question: http://stackoverflow.com/q/48144210
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83311401
type: Answer
accepted answer of: http://stackoverflow.com/q/48144210
has body: On macOS, PyAutoGUI calls the screencapture utility. So it is slow. You can give it a try to MSS, it will be blazing fast and requires no other tools/modules. This is an example you could try (copied from the documentation): import mss import mss.tools with mss.mss() as sct: # The screen part to capture region = {'top': 0, 'left': 0, 'width': 400, 'height': 300} # Grab the data img = sct.grab(region) # Save to the picture file mss.tools.to_png(img.rgb, img.size, output='dummy.png')

http://stackoverflow.com/q/48062271
has comment: http://stackoverflow.com/comment/83098164
favorite count: 0
possible better answer: http://stackoverflow.com/a/48062613
downvote count: 5
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/83098030
tagged with: regex
has comment: http://stackoverflow.com/comment/83097589
answer count: 4
type: AnsweredQuestion
has title: How to take the value before or after "am" and "pm"?
has answer: http://stackoverflow.com/a/48062756
accepted answer: http://stackoverflow.com/a/48062756
has comment: http://stackoverflow.com/comment/83097981
has comment: http://stackoverflow.com/comment/83097064
has comment: http://stackoverflow.com/comment/83097173
has body: I'm a bit of a starter in the regex aspect, my question is : I have a lunch break at 5am later today. I have a lunch break at 5 am later today. The cases that should be taken under consideration are having a space between the number and am and not having a space. In these first and 2 examples the value that i want is 5. EDIT: What i have tried and didn't work: import re value = re.findall('/([1-9]|1[012]) ?[ap]m/','I have a lunch break at 5am later today.') print value
type: Question
has answer: http://stackoverflow.com/a/48062648
has answer: http://stackoverflow.com/a/48062613
has answer: http://stackoverflow.com/a/48062359
upvote count: 2
has comment: http://stackoverflow.com/comment/83097100

http://stackoverflow.com/comment/83434061
has text: about grequests: "Note: You should probably use requests-threads or requests-futures instead." from https://github.com/kennethreitz/grequests. Why does the author suggest to use something else?
comment on: http://stackoverflow.com/a/48199714
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48164176
has comment: http://stackoverflow.com/comment/128731885
type: Question
has body: When attempting to do absolutely anything using pip in the terminal, I instantly receive the message "Access is denied." No other messages, just "Access is denied." I've tried using administrator terminal, going to different directories, but the same issue happens. I have attempted to run "python -m pip install --upgrade pip" from looking at a solution in a different question but it said pip is up to date and no change occurred. I can get around installing using the "python -m pip install (something)" command but I would like to know the cause of this issue and how to resolve it so it doesn't impede me in future when I try doing something other than installing with pip. Any ideas? Help is greatly appreciated, thank you :) I'm running Python 3.6 and Windows 10. So sorry if this is a duplicate question, I've spent a while attempting to see if the answer is already here but for the most part they appear to all be for a different OS or have a different error. Of course, I could have been searching using the wrong query but like Jon Snow, I know nothing, especially about technical stuff. EDIT: I've gone into the pip.exe files locations and have adjusted security permissions so that any user on my device has full control, still no luck. Many reboots have been done but no luck there either. I can't seem to log into the admin account in terminal as it doesn't accept my password, even though I am the sole account and an admin account.
has answer: http://stackoverflow.com/a/48164990
tagged with: python
accepted answer: http://stackoverflow.com/a/72919622
has comment: http://stackoverflow.com/comment/128769981
upvote count: 2
answer count: 3
tagged with: pip
has comment: http://stackoverflow.com/comment/83376747
has title: pip Access denied Windows 10
has comment: http://stackoverflow.com/comment/83307499
has comment: http://stackoverflow.com/comment/83307551
has comment: http://stackoverflow.com/comment/128794257
has answer: http://stackoverflow.com/a/72919622
has comment: http://stackoverflow.com/comment/83307905
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/60337104
possible better answer: http://stackoverflow.com/a/48164990

http://stackoverflow.com/q/48106087
type: UnansweredQuestion
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/48123118
answer count: 1
tagged with: javascript
score: 0
linked to: http://stackoverflow.com/q/5796718
has title: Passing python object to jinja2 template not working
has comment: http://stackoverflow.com/comment/83188736
has body: So I'm passing a JSON object to a jinja2 template. The object is named 'markers' and it contains this data: {'markers': [{'marker_id': 1, 'lat': '-33.8653882', 'lng': '151.216084'}, {'marker_id': 2, 'lat': '49.15987639', 'lng': '5.38442310'}]} When I print the object in a p tag it appears fine, as so: &lt;p&gt;{{markers}}&lt;/p&gt; displays: {'markers': [{'marker_id': 1, 'lat': '-33.8653882', 'lng': '151.216084'}, {'marker_id': 2, 'lat': '49.15987639', 'lng': '5.38442310'}]} but when i try and pass {{markers}} into my javascript at the bottom of the page it appears like this &lt;script&gt; var json = {&amp;#39;markers&amp;#39;: [{&amp;#39;marker_id&amp;#39;: 1, &amp;#39;lat&amp;#39;: &amp;#39;-33.8653882&amp;#39;, &amp;#39;lng&amp;#39;: &amp;#39;151.216084&amp;#39;}, {&amp;#39;marker_id&amp;#39;: 2, &amp;#39;lat&amp;#39;: &amp;#39;49.15987639&amp;#39;, &amp;#39;lng&amp;#39;: &amp;#39;5.38442310&amp;#39;}]}; &lt;/script&gt; i dont know what to search for and i want to know why this is happening and how to stop it. The object is generated by a function in my python script def get_marker(conn): JSONobj = { "markers" : [] } cur = conn.cursor(MySQLdb.cursors.DictCursor) cur.execute("SELECT * FROM marker") data = cur.fetchall() for row in data: JSONobj["markers"].append(row) return JSONobj

http://stackoverflow.com/comment/83236591
type: Comment
comment on: http://stackoverflow.com/a/48121777
has text: that's what it should be for 'aaa'. my mistake. I wanted to save some time on accurate explanations and these are the effects. sorry.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48138757
has title: Can't reshape to right shape size
tagged with: reshape
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83254964
score: 1
has answer: http://stackoverflow.com/a/48140366
has body: My original dataset is 7049 images(96x96) with following format: train_x.shape= (7049,) train_x[:3] 0 238 236 237 238 240 240 239 241 241 243 240 23... 1 219 215 204 196 204 211 212 200 180 168 178 19... 2 144 142 159 180 188 188 184 180 167 132 84 59 ... Name: Image, dtype: object I want to split image-string into 96x96 and get the (7049,96,96) array. I try this method: def split_reshape(row): return np.array(row.split(' ')).reshape(96,96) result = train_x.apply(split_reshape) Then I still got result.shape=(7049,) How to reshape to (7049,96,96) ?
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48140366
downvote count: 0
tagged with: pandas
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48135559
upvote count: 5
answers question: http://stackoverflow.com/q/48130916
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I replicated your problem. Using the %%python magic solved if for me. Try this: %%python from tkinter import filedialog from tkinter import * root = Tk() root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*"))
accepted answer of: http://stackoverflow.com/q/48130916

http://stackoverflow.com/comment/83240765
type: AnswerComment
has text: Thank you, this does help however I was aiming for a listbox because the user can select and highlight rows within it without changing the text. Although, I am sure I could attempt to implement your method into a listbox in different ways. I'll just have to keep having a stab at it.
type: Comment
comment on: http://stackoverflow.com/a/48131491
score: 0

http://stackoverflow.com/comment/83287277
comment on: http://stackoverflow.com/q/48152379
score: 0
type: Comment
type: QuestionComment
has text: @BearBrown `unique_together = (('request', 'targetcode'),)` request_id + targetcode_id makes a record unique together.

http://stackoverflow.com/q/48023481
answer count: 0
upvote count: 2
type: Question
has title: Exception in thread on Heroku
tagged with: flask
has body: Backrground I have deployed an app on Heroku but I'm getting the below error. On my local server it was running fine. Basically I'm using Flask and Tweepy to send a few tweets back whenever I send a request, which is sent in every few seconds and then gets disconnected after a minute class LiveStream(Resource): """ Starts the Stream """ parser = reqparse.RequestParser() parser.add_argument('search_text', type=str, required=True) parser.add_argument('disconnect_time', type=float, required=True) def post(self): search_text = LiveStream.parser.parse_args()['search_text'] myStream = tweepy.Stream(auth=api.auth, listener=MyStreamListener()) myStream.filter(track=[search_text], async=True) stream_start_time = time.time() disconnect_time = LiveStream.parser.parse_args()['disconnect_time'] t = threading.Thread(target=stream_disconnect, name='stream_disconnect', args=(stream_start_time, disconnect_time)) t.start() connected = True return {'message': 'Stream has started'} def stream_disconnect(start_time, last_for): while True: if (time.time() - start_time) &gt;= last_for: global stream_list, connected, myStream myStream.disconnect() myStream = None stream_list = [] connected = False break print('Stream disconnected') return This is the error I'm getting on Heroku Logs. I dont think that Tweepy has been causing this and Twitter has been disconnecting me since It still runs fine on my local server. I suppose its something that I have done wrong. By the way, MyStreamListener appends tweet to stream_list which is being returned to me. My error &gt; 2017-12-29T12:51:49.185114+00:00 app[web.1]: Exception in thread &gt; Thread-4: 2017-12-29T12:51:49.185134+00:00 app[web.1]: File &gt; "/app/.heroku/python/lib/python3.6/site-packages/urllib3/connectionpool.py", &gt; line 601, in urlopen 2017-12-29T12:51:49.185132+00:00 &gt; app[web.1]: Traceback (most recent call last): &gt; 2017-12-29T12:51:49.185135+00:00 app[web.1]: chunked=chunked) &gt; 2017-12-29T12:51:49.185135+00:00 app[web.1]…
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: tweepy
tagged with: heroku
score: 2

http://stackoverflow.com/comment/83081720
type: QuestionComment
type: Comment
has text: Anyway, the documentation excerpt (already linked above) here: ["*If capturing parentheses are used* in pattern, then *the text of all groups in the pattern are also returned* as part of the resulting list."](https://docs.python.org/3/library/re.html)
comment on: http://stackoverflow.com/q/48054636
score: 0

http://stackoverflow.com/q/48152457
tagged with: outlook
upvote count: 1
has title: Python Command to Mark Mails as Read in Outlook (MAPI)
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83283621
type: UnansweredQuestion
tagged with: mapi
tagged with: python
has answer: http://stackoverflow.com/a/49163698
has body: I am writing a python code to download a specific attachment from unread emails in outlook and mark those emails as read. I have managed to finish 90% of it i.e. I can do an iteration to open unread emails and download the attachments with a specific emails. However, I have two issues. I am downloading the attachment with the same name, and if there are two attachments with the same name, it just saves the one it extracts from the last iteration. I tried appending a time stamp at the end of the file name but it has the same effect. Any help would be appreciated. This is not mandatory requirement since the mail comes at stipulated intervals and I can write a separate python code to rename it but I want to pack everything in this single email. I would like to mark the email as read after the attachment is downloaded. I do not know the command for this one. I have attached the code for your reference. P.S. This is my first real python code. Also this is my first post here. Apologies if this is was already asked elsewhere. import win32com.client import os import time date_time_stamp = time.strftime("%Y%m%d-%H%M%S") #set custom working directory os.chdir('C:\\Users\user_name\Desktop\') print(os.getcwd()) outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") main_inbox = outlook.GetDefaultFolder(6) subfolder = main_inbox.Folders.Item("my_child_folder_under_inbox") subfolderitems = subfolder.Items message = subfolderitems.GetFirst() attachment_name = 'my_attachment_name' #Loop to pick messages that are unread for message in subfolderitems: if message.Unread == True: print("New Mail Found... Downloading Attachment...") #Loop to check if the attachment name is the same for attachments in message.Attachments: if attachments.Filename == attachment_name: #Saves to the attachment to the working directory attachments.SaveASFile(os.getcwd() + '\\' + 'my_attachment_name' + date_time_stamp + '.csv') print (attachments) time.sleep(2) break #Go to next unread …
downvote count: 0
score: 1
type: Question

http://stackoverflow.com/comment/83112034
has text: I'm able to reproduce the error if I manually first construct a `DataValue` instance, then call `ctypes._pointer_type_cache.clear()` or `ctypes._reset_cache()`, and then try the assignment.
comment on: http://stackoverflow.com/q/48067886
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48153425
accepted answer of: http://stackoverflow.com/q/48113872
answers question: http://stackoverflow.com/q/48113872
score: 0
type: AcceptedAnswer
type: Answer
has body: Thanks to @raganjosh. I got my solution to the problem by using pandas Grouper. Below is my implementation. I have used dynamic value for 'hr'. timeWindow = str(hr)+'H' # Dividing the log into "n" parts. Depends on timewindow initialisation. df["ST"] = df['StartTime'] df = df.set_index(['ST']) # Using the copied column as an index. df.index = pd.to_datetime(df.index) # Here the parts contain grouped chunks of data as per timewindow, list[0] = key of the group, list[1] = values. parts = list(df.groupby(pd.TimeGrouper(freq=timeWindow))['StartTime', "ProcessTime", "EndTime"])

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

http://stackoverflow.com/q/48121307
has body: I've been stuck on this for a while. I cannot access the value of an object's attribute once constructed, but console prints the names just fine. The names and number of attributes needs to be dynamic and change depending on what source they come from. Therefore I can't just use a consistent way. starting_list = ["Comapny", "Contact Name", "Email", "Phone", "URL", "Country", "Source"] class NewClass(object): _myattrib = None def __setattr__(self, prop, val): super().__setattr__('myattrib', val) print("setting myattrib") def __init__(self): for item in starting_list: #cleaning up a bit item = str(item) item = item.lower() item = item.strip() item = item.replace(' ', '_') self.__setattr__(self, item, 'hi') print(item) #it reads it here print(NewClass.url) any help would be apprecieated.
type: Question
has title: Looping strings to create attributes in class constructor - python
has comment: http://stackoverflow.com/comment/83236215
has comment: http://stackoverflow.com/comment/83219857
accepted answer: http://stackoverflow.com/a/48121577
score: 0
has comment: http://stackoverflow.com/comment/83219274
answer count: 1
tagged with: attributes
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48121577
has comment: http://stackoverflow.com/comment/83219272

static
tags question: http://stackoverflow.com/q/48159515
tags question: http://stackoverflow.com/q/48025335
tag name: static
type: Tag

http://stackoverflow.com/comment/83170983
type: AnswerComment
type: Comment
has text: THANKS for the insight! The last point is what is driving me nuts though-- why cant I round in a dataframe? when I try to round the dataframe it cant be done e.g. df=pd.DataFrame([a17,a18]) then df.round(2) =0.02 but df.round(3)=0.025 but np.round(df.round(3),2)=0.02
comment on: http://stackoverflow.com/a/48096008
score: 0

http://stackoverflow.com/comment/83001891
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48014712
has text: This is not really a programming question and would be better suited at https://math.stackexchange.com/. Try posting there. Once you figure out the math behind it, you can try to ask how to implement the solution.
score: 0

http://stackoverflow.com/comment/83255592
score: 0
comment on: http://stackoverflow.com/q/48133041
type: Comment
type: QuestionComment
has text: You are right I should not be doing correlation, I should be doing summation of point-by-point differences. This takes significantly less time to compute'

feature-detection
type: Tag
tag name: feature-detection
tags question: http://stackoverflow.com/q/48081791
tags question: http://stackoverflow.com/q/48160827

http://stackoverflow.com/comment/83045413
type: Comment
comment on: http://stackoverflow.com/a/48030190
type: AnswerComment
has text: @kyttcar nice! I’m happy that you solved the problem :-)
score: 0

http://stackoverflow.com/q/48160172
tagged with: django-models
type: Question
upvote count: 2
has body: sorry if my question is weird or incoherent. What I'm trying to do is this: I take the string that the user has typed out as his search input and create a list of strings from that input, and then create a loop that goes over the list and searches for each item in that list in database, let me make it a bit clearer with some code: #I take the string that the user inputs as his search query = request.GET.get('q') # I create a list by spliting the original search string query_srch = query.split() # Create a list which will later hold the items returned by the db lookup searchnews = [] #start the loop to lookup for word in query_srch: if word: searchnews += NewsPost.objects.filter( Q(title__icontains=word) ).distinct().order_by('-date') The reason why I do this is because if the title of an article in your website is "Obama: blablabla", but the user searches for "Barack Obama", the article "Obama: blablabla" will not actually come up at all. The problem is that when I do this for loop search thing, if my search query is "Obama Obama Obama", I will get a list with each article not duplicated but triplicated (I think I made that word up). If I search for "Obama Obama Obama Obama" I will get each article quatruplicated(the same article 4 times) etc etc.. I hope you get what I mean. I worked around this for a while by just taking the end list which in my case is searchnews and using the inbuilt python function set(), like this: searchnews = set(searchnews) but this changes the order of the items in the list and I need them ordered by date. Any chance you can help ? Thanks in advance.
answer count: 1
tagged with: database
accepted answer: http://stackoverflow.com/a/48160339
favorite count: 0
has title: Django Q lookup search in title for strings from a list returns duplicates
has answer: http://stackoverflow.com/a/48160339
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83304388
score: 2
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/83287213
score: 4
has text: Is that first line supposed to be `input = "a"`? BTW, you should not use `input` as a variable name because that shadows the built-in `input` function.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48154081

http://stackoverflow.com/comment/83217530
type: AnswerComment
has text: `return not (a_idx == b_idx and a_type == "e" and b_type == "s")`
type: Comment
comment on: http://stackoverflow.com/a/48120461
score: 1

http://stackoverflow.com/comment/83257705
has text: `Encapsulating it All in a Function` does achieve it, thankyou. I'd read over that question but did not understand that would apply to my situation. scwobseggl, you were correct with the removal of the while loop in tile_cost, thanks to that too.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48139804

loops
tags question: http://stackoverflow.com/q/48165710
tags question: http://stackoverflow.com/q/48036929
tags question: http://stackoverflow.com/q/48039971
tags question: http://stackoverflow.com/q/48156069
tags question: http://stackoverflow.com/q/48058197
tags question: http://stackoverflow.com/q/48114794
tags question: http://stackoverflow.com/q/48103331
tags question: http://stackoverflow.com/q/48136421
tags question: http://stackoverflow.com/q/48079133
tags question: http://stackoverflow.com/q/48015571
tags question: http://stackoverflow.com/q/48153180
tags question: http://stackoverflow.com/q/48130638
tags question: http://stackoverflow.com/q/48084397
type: Tag
tags question: http://stackoverflow.com/q/48153604
tags question: http://stackoverflow.com/q/48089366
tags question: http://stackoverflow.com/q/48127108
tags question: http://stackoverflow.com/q/48029672
tags question: http://stackoverflow.com/q/48014709
tags question: http://stackoverflow.com/q/48099923
tags question: http://stackoverflow.com/q/48085979
tags question: http://stackoverflow.com/q/48055551
tags question: http://stackoverflow.com/q/48015692
tags question: http://stackoverflow.com/q/48091040
tags question: http://stackoverflow.com/q/48105967
tags question: http://stackoverflow.com/q/48086841
tags question: http://stackoverflow.com/q/48024917
tags question: http://stackoverflow.com/q/48080414
tags question: http://stackoverflow.com/q/48155121
tags question: http://stackoverflow.com/q/48033209
tags question: http://stackoverflow.com/q/48052487
tag name: loops
tags question: http://stackoverflow.com/q/48017592
tags question: http://stackoverflow.com/q/48085830
tags question: http://stackoverflow.com/q/48019078
tags question: http://stackoverflow.com/q/48059157
tags question: http://stackoverflow.com/q/48056464
tags question: http://stackoverflow.com/q/48135401
tags question: http://stackoverflow.com/q/48086515
tags question: http://stackoverflow.com/q/48033265
tags question: http://stackoverflow.com/q/48071393
tags question: http://stackoverflow.com/q/48143394
tags question: http://stackoverflow.com/q/48124891
tags question: http://stackoverflow.com/q/48118664

http://stackoverflow.com/a/48035473
upvote count: 1
answers question: http://stackoverflow.com/q/48035389
has comment: http://stackoverflow.com/comment/83041008
type: Answer
has comment: http://stackoverflow.com/comment/83040970
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83041063
has body: You can use traceback.format_exc() or sys.exc_info() like : try: raise TypeError("Error !?!") except Exception: print(traceback.format_exc()) # or print(sys.exc_info()[2])
has comment: http://stackoverflow.com/comment/83041158

http://stackoverflow.com/q/48015272
has answer: http://stackoverflow.com/a/48115961
favorite count: 0
has title: django-graphene alter column name deprecation
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83136004
upvote count: 2
accepted answer: http://stackoverflow.com/a/48115961
has comment: http://stackoverflow.com/comment/83208902
tagged with: django
tagged with: graphene-python
type: Question
has body: I would like to alter a column name in a table my database, deprecate the old field in django-graphene and add the new field. How or can I do this without creating the same column twice in my Django model? I can avoid errors during system checks while doing this, but still run into errors with my tests. Model class MyModel(BaseModel): my_column = models.CharField( max_length=255, blank=True, null=True) mycolumn = models.CharField( max_length=255, blank=True, null=True db_column='my_column') Schema class MyNode(DjangoObjectType): mycolumn = String(deprecation_reason='Deprecated') Settings SILENCED_SYSTEM_CHECKS = ['models.E007'] This works, however, now I try to run tests where I create a sample MyModel factory instance. class TestMyModel(TestModelBase): def setUp(self): self.my_model = MyModel(my_model_nm='Some model') Which, of course, throws an exception. django.db.utils.ProgrammingError: column "my_column" specified more than once I seem to be going about this wrong. How do I change a field name in django-graphene, deprecate the old name and have a new field reference the same column in my table? graphene==1.2 graphene-django==1.2.1 graphql-core==1.0.1
has comment: http://stackoverflow.com/comment/83178007
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83149067
has comment: http://stackoverflow.com/comment/83187627

http://stackoverflow.com/comment/83142150
score: 1
comment on: http://stackoverflow.com/a/48081756
has text: @Jan I was thinking about that initially, but let's assume emojis can be inserted into parentheses as well. In that case, the parenthesis balancing will fail. That's why I decided to go another route and assume that balancing parentheses doesn't always work and that the OP should be looking for specific strings instead (`:(`, `:)`, etc.) and selecting the parentheses that don't match those criteria.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48169392
has comment: http://stackoverflow.com/comment/83329836
has comment: http://stackoverflow.com/comment/83319371
upvote count: 3
has comment: http://stackoverflow.com/comment/83318774
score: 3
accepted answer of: http://stackoverflow.com/q/48169038
answers question: http://stackoverflow.com/q/48169038
has comment: http://stackoverflow.com/comment/83326107
type: AcceptedAnswer
has body: Here's a generic vectorized solution using cumsum to replace those sliced summations and argmax for getting the appropriate index to be used for setting the slice limits for those IF-case operations - # Use cumsum to replace sliced summations - Basically all those # `list_amounts[0]`, `sum(list_amounts[0: 2]))`, `sum(list_amounts[0: 3])`, etc. c = np.cumsum(list_amounts) # Use argmax to decide the slicing limits for the intended slicing operations. # So, this would replace the last number in the slices - # list_prices[0: 2], list_prices[0: 3], etc. idx = (c &gt;= BuyAmount).argmax() # Use the slicing limit to get the slice off list_prices needed as the first # input to numpy.average l = list_prices[:idx+1] # This step gets us the weights. Now, in the weights we have two parts. E.g. # for the third-IF we have : # [list_amounts[0],list_amounts[1],BuyAmount - (sum(list_amounts[0: 2]))] # Here, we would slice off list_amounts limited by `idx`. # The second part is sliced summation limited by `idx` again. w = np.r_[list_amounts[:idx], BuyAmount - c[idx-1]] # Finally, plug-in the two inputs to np.average and get avgprice output. avgprice = np.average(l,weights=w) # Get idx element off list_prices as the highprice output. highprice = list_prices[idx] We can further optimize to remove the concatenation step ( with np.r_) and get to avgprice, like so - slice1_sum = np.multiply(list_prices[:idx], list_amounts[:idx]).sum() # or np.dot(list_prices[:idx], list_amounts[:idx]) slice2_sum = list_prices[idx]*(BuyAmount - c[idx-1]) weight_sum = np.sum(list_amounts[:idx]) + BuyAmount - c[idx-1] avgprice = (slice1_sum+slice2_sum)/weight_sum
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83262563
has text: Hey thanks! This helps. Although, the reason I want to combine regex is I've got some data that are multiple words with numbers at the beginning and brackets in the middle. Would be easier to format what to remove!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48142189

matlab
tags question: http://stackoverflow.com/q/48045185
tags question: http://stackoverflow.com/q/48053572
tags question: http://stackoverflow.com/q/48062779
tags question: http://stackoverflow.com/q/48082393
tags question: http://stackoverflow.com/q/48075176
tags question: http://stackoverflow.com/q/48068306
type: Tag
tags question: http://stackoverflow.com/q/48117301
tag name: matlab
tags question: http://stackoverflow.com/q/48130845
tags question: http://stackoverflow.com/q/48070346

http://stackoverflow.com/comment/83218960
type: AnswerComment
comment on: http://stackoverflow.com/a/48114495
has text: The error was not with the gui, the gui worked just fine. The issue was with the PlaceCards function. I edited my post to make this more clear
type: Comment
score: 0

http://stackoverflow.com/q/48156951
type: UnansweredQuestion
has title: Python uncaught exception
upvote count: 1
type: Question
score: 1
has comment: http://stackoverflow.com/comment/83293109
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83334135
downvote count: 0
has comment: http://stackoverflow.com/comment/83296964
favorite count: 0
has comment: http://stackoverflow.com/comment/83293157
tagged with: exception
has body: I've got two programs written in Python2 running on Raspberry Pi, but my question strictly concerns Python. First program detects temperature and prints its value on a 16x2 LCD, while the second one is controlled by an IR remote which is used for toggling LEDs. Both programs use similar try/except mechanism, run in an infinite loop and terminate by CTRL+C. The first one behaves as expected (gives ^CBye!): import os import glob import time from RPi import GPIO from RPLCD.gpio import CharLCD def read_temp_raw(): f = open(device_file, 'r') lines = f.readlines() f.close() return lines def read_temp_c(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = round(int(temp_string) / 1000.0, 2) temp_c = "%.2f" % temp_c return temp_c def read_temp_f(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_f = round((int(temp_string) / 1000.0) * 9.0 / 5.0 + 32.0, 2) temp_f = "%.2f" % temp_f return temp_f try: lcd = CharLCD(cols=16, rows=2, pin_rs=38, pin_e=40, pins_data=[31,33,35,37], numbering_mode=GPIO.BOARD) os.system('modprobe w1-gpio') os.system('modprobe w1-therm') base_dir = '/sys/bus/w1/devices/' device_folder = glob.glob(base_dir + '28*')[0] device_file = device_folder + '/w1_slave' while True: lcd.cursor_pos = (0, 0) lcd.write_string(unicode("Temp: " + read_temp_c() + unichr(223) + "C")) lcd.cursor_pos = (1, 0) lcd.write_string(unicode("Temp: " + read_temp_f() + unichr(223) + "F")) except KeyboardInterrupt: print "\nBye!" except: print "Error... aborting\n" finally: lcd.close(clear=True) #GPIO.cleanup() whereas the other one is not: import lirc #import RPi.GPIO as GPIO import wiringpi #GPIO.setmode(GPIO.BCM) #GPIO.setup(23, GPIO.OUT) #GPIO.setup(24, GPIO.OUT) #GPIO.setup(25, G…
has comment: http://stackoverflow.com/comment/83293866
tagged with: python
has comment: http://stackoverflow.com/comment/83293051
answer count: 0

http://stackoverflow.com/comment/83280971
type: Comment
comment on: http://stackoverflow.com/q/48151017
score: 0
has text: You haven't detailed how you tested your code, I am assuming you typed it into an interactive Python prompt in an IDE, or a console or terminal. At that point *the context sets the codec*. In a Linux or OS X terminal, the *locale* tells Python what codec to expect. In a file (script, module), Python defaults to ASCII unless you use a PEP 263 header to set something different. If you mix `unicode` and `str` types in your code, ASCII always applies, etc.
type: QuestionComment

http://stackoverflow.com/q/48142203
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/120721290
accepted answer: http://stackoverflow.com/a/48178830
has comment: http://stackoverflow.com/comment/120725123
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83269504
downvote count: 3
has body: I am doing a rather complex match with python using re.match, which takes the form of (some_pattern_1)?(some_pattern_2)?..(.*) On the other side of it I have a unit test with about one hundred examples I am checking, which are all sending request asynchronously to my (local, development) server. The server is in django. I am sometime seing the match apparently be non-greedy (i.e. too many things end up in the last catch all block) and the unit test fail, but can't really reproduce it in isolation, and I don't really have an idea what's going on. More concretely, the relevant part of the regex is (in Python): import re input = "1 small shoe" sizes = ["small", "large", "big", "huge"] colors = ["blue", "red", "green", "yellow", "grey"] anySize = u' |'.join(sizes) anyColor = u' |'.join(colors) matched_expression = re.match( r'\s*(?P&lt;amount&gt;(((\d{1,2}\.)?\d{1,3})?)\s*' r'(?P&lt;size&gt;(\b'+anySize+'\b)?)\s*' r'(?P&lt;color&gt;(\b'+anyColor+'\b)?)\s*' r'(?P&lt;name&gt;.*, input, re.UNICODE|re.IGNORECASE) if matched_expression: print(matched_expression.groupdict()["amount"]) print(matched_expression.groupdict()["size"]) print(matched_expression.groupdict()["color"]) print(matched_expression.groupdict()["name"]) And I am sometimes seeing this printed: 1 '' '' 'small shoe' Are there know conditions where this could happen (and am I correct to assume that the regex match is guaranteed to be fully deterministic in principle?) ?
type: Question
score: -2
linked to: http://stackoverflow.com/q/33895542
has title: re.match output not deterministic
answer count: 1
tagged with: regex
has comment: http://stackoverflow.com/comment/120724499
has comment: http://stackoverflow.com/comment/83262652
favorite count: 0
has comment: http://stackoverflow.com/comment/83262540
has comment: http://stackoverflow.com/comment/83269568
has answer: http://stackoverflow.com/a/48178830

http://stackoverflow.com/q/48156612
upvote count: 2
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python
score: 2
has title: Pyinstaller build process cannot locate pywintypes module
has answer: http://stackoverflow.com/a/58995434
type: Question
has body: Recently updated my computer to Windows 10 and now pyinstaller is throwing an error. This has been working on my Windows 7 computer for as long as I can remember. I have tried uninstalling and reinstalling pyinstaller, win32 extentions, and several other things. Any ideas what could be wrong with my computer settings? pyinstaller ZENTRAUtility.spec 328 INFO: PyInstaller: 3.3.1 328 INFO: Python: 2.7.14 328 INFO: Platform: Windows-10-10.0.16299 331 INFO: UPX is not available. 332 INFO: Extending PYTHONPATH with paths ['C:\\Users\\mthornbrugh\\PycharmProjects\\ZentraUtility', 'C:\\Users\\mthornbrugh\\PycharmProjects\\ZentraUtility'] 332 INFO: checking Analysis 347 INFO: Building because out00-Analysis.toc is bad 348 INFO: Initializing module dependency graph... 351 INFO: Initializing module graph hooks... 430 INFO: running Analysis out00-Analysis.toc 431 INFO: Adding Microsoft.VC90.CRT to dependent assemblies of final executable required by c:\python27\python.exe 525 INFO: Found ... ... Traceback (most recent call last): File "&lt;string&gt;", line 3, in &lt;module&gt; File "c:\python27\lib\site-packages\PyInstaller\utils\win32\winutils.py", line 103, in import_pywin32_module name=module_name, globals={}, locals={}, fromlist=['']) ImportError: No module named pywintypes 29585 INFO: Loading module hook "hook-setuptools.py"... 29631 INFO: Loading module hook "hook-PIL.SpiderImagePlugin.py"... 29634 INFO: Excluding import 'FixTk' 29635 INFO: Excluding import 'Tkinter' 29638 INFO: Loading module hook "hook-encodings.py"... 30174 INFO: Loading module hook "hook-reportlab.pdfbase._fontdata.py"... 30234 INFO: Loading module hook "hook-xml.etree.cElementTree.py"... 30236 INFO: Loading module hook "hook-numpy.core.py"... 30318 INFO: Loading module hook "hook-wx.lib.pubsub.py"... 30561 INFO: Loading module hook "hook-win32com.py"... 31109 INFO: Loading module hook "hook-pythoncom.py"... Traceback (most recent call last): File "&lt;string&gt;", line 3, in &lt;module&gt; File "c:\…
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/57932432
favorite count: 0

http://stackoverflow.com/a/48034442
type: Answer
has body: GUI programming is quite different from normal python scripts. When you see the GUI pop up, it is already running in the mainloop. That means that your code is only invoked from the mainloop as a callback attached to some event or as a timeout function. Your code actually interrupts the flow of events in the mainloop. So to keep the GUI responsive, callbacks and timeouts have to finish quickly (say in 0.1 second max). This is why you should not run long loops in a callback; the GUI will freeze. So the canonical way to do a long calculation in a GUI program is to split it up into small pieces. Instead of e.g. looping over a long list of items in a for loop, you create a global variable that holds the current position in the list. You then create a timeout function (scheduled for running by the after method) that takes e.g. the next 10 items from the list, processes them, updates the current position and reschedules itself using after. The proper way to get input for a function is to get the necessary input before starting the function. Alternatively, you could use a messagebox in the function to get the input. But in general it is considered good design to keep the "guts" of your program separate from the GUI. (Consider that you might want to switch from Tkinter to the GTK+ or QT toolkits in the future.) Now onto threads. You might think that using threads can make long-running tasks easier. But that is not necessarily the case. For one thing, the standard Python implementation (we shall call it CPython) has a Global Interpreter Lock that ensures that only one thread at a time can be running Python bytecode. So every time your long-running calculation thread is running, the other thread containing the mainloop is halted. In Python 3 the thread scheduling is improved w.r.t. Python 2 as to try and not starve threads. But there is no guarantee that the GUI thread gets enough runtime when the other thread is doing a ton of work. Another restriction is that the Tkinter GU…
downvote count: 0
answers question: http://stackoverflow.com/q/48033347
score: 1
upvote count: 1

http://stackoverflow.com/q/48048845
upvote count: 1
tagged with: amazon-s3
score: 1
type: Question
answer count: 1
downvote count: 0
tagged with: boto3
has body: If I want to upload a file from my "mac" to S3, I can use import boto3 s3 = boto3.resource('s3', region_name="us-west-1") s3.meta.client.upload_file('/User/gantao/amz.jpg', 'gantao_created', 'amz.jpg') But, Is there any way to upload a file to S3 from EC2 instance (do not use SSH to EC2) ?
favorite count: 0
has title: Python boto3 upload file to S3 from ec2
tagged with: python
has answer: http://stackoverflow.com/a/48049241
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83070400

http://stackoverflow.com/comment/83125528
type: AnswerComment
score: 0
type: Comment
has text: BTW: framework [scrapy](https://scrapy.org/) exports to `csv`, `json`, `xml` automatically. But then you don't use `requests` and don't need `BeautifulSoup`.
comment on: http://stackoverflow.com/a/48075115

http://stackoverflow.com/comment/83073258
score: 0
type: QuestionComment
has text: Edited yet again
type: Comment
comment on: http://stackoverflow.com/q/48050477

http://stackoverflow.com/comment/125064186
comment on: http://stackoverflow.com/a/70744127
score: 0
type: AnswerComment
has text: it is work for me !
type: Comment

http://stackoverflow.com/comment/83026943
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48028394
has text: I am attempting to use .len() to identify whether the data in a given index/variable is valid or not. This is a text field. If that text is less than 4 characters long, I know there is an issue with it and I don't want to use it.

http://stackoverflow.com/comment/83023319
has text: Sorry, it's values, not values()
score: 0
comment on: http://stackoverflow.com/q/48026525
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48168361
has comment: http://stackoverflow.com/comment/99233848
has comment: http://stackoverflow.com/comment/103713569
has body: You should use .dt.total_seconds() method, instead of applying pd.Timedelta.total_seconds function onto datetime64[ns] dtype column: In [232]: test Out[232]: 0 NaT 1 NaT dtype: datetime64[ns] # &lt;---- In [233]: pd.to_timedelta(test) Out[233]: 0 NaT 1 NaT dtype: timedelta64[ns] # &lt;---- In [234]: pd.to_timedelta(test).dt.total_seconds() Out[234]: 0 NaN 1 NaN dtype: float64 Another demo: In [228]: s = pd.Series(pd.to_timedelta(['03:33:33','1 day','aaa'], errors='coerce')) In [229]: s Out[229]: 0 0 days 03:33:33 1 1 days 00:00:00 2 NaT dtype: timedelta64[ns] In [230]: s.dt.total_seconds() Out[230]: 0 12813.0 1 86400.0 2 NaN dtype: float64
has comment: http://stackoverflow.com/comment/103777192
score: 6
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/48168209
has comment: http://stackoverflow.com/comment/103713695
accepted answer of: http://stackoverflow.com/q/48168209

http://stackoverflow.com/q/48136421
type: Question
has answer: http://stackoverflow.com/a/48136511
score: 0
has title: Python 3.4 - Looping under a function
possible better answer: http://stackoverflow.com/a/48136481
has body: I'm pretty new to Python and would like your advise on this. I want to create an array of square number (i.e., 1, 4, 9, 16, 25, etc.) Here is my current code: def near(limit): for element in limit: answer = 0 rounding1 = math.ceil(element ** 0.5) rounding2 = math.floor(element ** 0.5) result1 = rounding1 ** 2 result2 = rounding2 ** 2 lambda1 = abs(result1 - element) lambda2 = abs(result2 - element) if lambda1 &lt; lambda2: answer = result1 else: answer = result2 return answer listing = list(range(1,2000)) nearing = near(listing) But from this code, I am still unable to produce an array/list of squared numbers. Any suggestion is greatly appreciated.
has comment: http://stackoverflow.com/comment/83250219
tagged with: python-3.x
answer count: 3
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48137556
accepted answer: http://stackoverflow.com/a/48137556
has comment: http://stackoverflow.com/comment/83250233
tagged with: loops
has answer: http://stackoverflow.com/a/48136481

http://stackoverflow.com/q/48019798
type: Question
score: 0
tagged with: deep-learning
has body: When I import slim with spyder: import tensorflow.contrib.slim as slim there is an error: RuntimeError: 'path' must be None or a list, not &lt;class'_frozen_importlib_external._NamespacePath'&gt; And the jupyter notebook is ok.
answer count: 1
has title: slim import error with spyder: 'path' must be None or a list, not <class '_frozen_importlib_external._NamespacePath'>
has answer: http://stackoverflow.com/a/48031099
type: UnansweredQuestion
tagged with: spyder
tagged with: python
tagged with: tensorflow

http://stackoverflow.com/comment/83135157
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48080480
has text: Then read https://stackoverflow.com/editing-help
type: Comment

http://stackoverflow.com/q/48058717
has comment: http://stackoverflow.com/comment/83090863
has answer: http://stackoverflow.com/a/48059259
type: Question
has comment: http://stackoverflow.com/comment/83090180
has comment: http://stackoverflow.com/comment/83090654
has body: I have some SQL strings from where I want to find how many times the character %s occurred. Example string: query_fetch_user = """select * from users where id=%s and email LIKE '%sayhello%' """ Here I want to get the exact count of %s only and I want to avoid the email part to be accounted for the count. What I tried. query_fetch_user.count("%s") This is giving count as 2 count = start = 0 while True: start = query_fetch_user.find(sub, start) + 1 if start &gt; 0: count+=1 else: print(count) This also giving count as 2 But the actual count should be 1.
has comment: http://stackoverflow.com/comment/83090477
has comment: http://stackoverflow.com/comment/83091177
has comment: http://stackoverflow.com/comment/83089938
has comment: http://stackoverflow.com/comment/83090237
has comment: http://stackoverflow.com/comment/83090208
downvote count: 2
has comment: http://stackoverflow.com/comment/83091286
answer count: 1
upvote count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/83091020
has comment: http://stackoverflow.com/comment/83089734
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83089804
tagged with: python
has comment: http://stackoverflow.com/comment/83090979
has title: How to find the exact occurrence of %s in a string in python
has comment: http://stackoverflow.com/comment/83091213
has comment: http://stackoverflow.com/comment/83090947
score: 2
has comment: http://stackoverflow.com/comment/83090075
has comment: http://stackoverflow.com/comment/83090835

http://stackoverflow.com/comment/83237602
comment on: http://stackoverflow.com/a/48130110
type: AnswerComment
has text: ok I tried it and you forgot the '#' for some comments. I fixed it and it worked.
score: 0
type: Comment

http://stackoverflow.com/q/48141087
has title: Why does my java client always return null when I try to read response from a global server?
type: Question
has comment: http://stackoverflow.com/comment/83261120
has comment: http://stackoverflow.com/comment/83262424
has comment: http://stackoverflow.com/comment/83264119
has comment: http://stackoverflow.com/comment/83264218
has comment: http://stackoverflow.com/comment/83264032
has comment: http://stackoverflow.com/comment/83263685
has comment: http://stackoverflow.com/comment/83262567
has comment: http://stackoverflow.com/comment/83260566
downvote count: 0
has body: This sends a message to the server which in response is supposed to return "ok". I know this works because I also tried it in python and it worked 100%. But in java I am not able to get the response back. String host = "(name of global host)"; s.connect(new InetSocketAddress(host, 80)); System.out.println("Connected"); OutputStream os = s.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); BufferedWriter bw = new BufferedWriter(osw); bw.write("(insert message to sent to server here)"); bw.flush(); BufferedReader brz = new BufferedReader(new InputStreamReader(s.getInputStream())); String t; while((t = brz.readLine()) != null){ System.out.println(t); } brz.close(); s.close(); // The loop doesn't even run because it returns null And here is the python code which works perfectly fine unlike java one HOST, PORT = "(host name)", 80 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(10) self.wrappedSocket = ssl.wrap_socket(self.sock) initial_connection_payload = '(text to send to server)'.encode('UTF-8') self.wrappedSocket.connect((HOST, PORT)) self.wrappedSocket.send(initial_connection_payload) response = self.wrappedSocket.recv(16384).decode('UTF-8') if "ok" not in response: self._log(response, "[!] Could not connect to server: " + response) self._log("[+] Connected.") So my question is what am I doing wrong in java? I have even tried other ways of doing this such as printwriter dataoutputstream etc. and even tried reading from scanner or just InputStream alone but nothing works. Any help would be appreciated
favorite count: 0
has comment: http://stackoverflow.com/comment/83264353
has comment: http://stackoverflow.com/comment/83261262
has comment: http://stackoverflow.com/comment/83263661
has comment: http://stackoverflow.com/comment/83271093
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83263755
tagged with: python
has comment: http://stackoverflow.com/comment/83260949
has comment: http://stackoverflow.com/comment/83264037
answer count: 0
has comment: http://stackoverflow.com/comment/83260189
score: 1
tagged with: java
has comment: http://stackoverflow.com/comment/83266594
has comment: http://stackoverflow.com/comment/83267282
upvote count: 1
has comment: http://stackoverflow.com/comment/83264216

http://stackoverflow.com/q/48095268
favorite count: 0
tagged with: linux
type: UnansweredQuestion
tagged with: python
has title: How to extract data recursively on Linux?
linked to: http://stackoverflow.com/q/10394723
score: 0
upvote count: 1
downvote count: 1
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/48095375
answer count: 2
has answer: http://stackoverflow.com/a/48096837
tagged with: utf-8
has body: I'm attempting to work on a large dataset, however, the format structure of the data has been split up into hundreds of directories. data/: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z data/0: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z data/1: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z data/2: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z data/3: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z data/4: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z data/5: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z data/6: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z data/7: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z data/8: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z data/9: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z data/a: 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s symbols t u v w x y z Furthermore, the file types are also completely random. 0: UTF-8 Unicode text 1: UTF-8 Unicode text 2: UTF-8 Unicode text 3: UTF-8 Unicode text 4: UTF-8 Unicode text 5: Non-ISO extended-ASCII text, with LF, NEL line terminators 6: UTF-8 Unicode text 7: UTF-8 Unicode text 8: UTF-8 Unicode text 9: UTF-8 Unicode text a: UTF-8 Unicode text ... z: UTF-8 Unicode text The files contain a email:password format. How can I get all of the content into a JSON file, or CSV file? I'm looking to import the data to MongoDB. Thanks.
tagged with: unicode

http://stackoverflow.com/q/48016883
downvote count: 0
tagged with: ffmpeg
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48687903
tagged with: pipe
score: 1
has body: There is a similar question here: Getting 'av_interleaved_write_frame(): Broken pipe' error But what should I do if I want to write the data? I put pipe_out.stdin.write(image.tostring()) in the while loop, like this FFMPEG_BIN = "/home/media/Downloads/ffmpeg" import subprocess as sp import sys width = 360 height = 240 command_in = [ FFMPEG_BIN, '-i', '/home/media/Videos/mytestvideo/zhou.avi', '-f', 'image2pipe', '-pix_fmt', 'bgr24', '-vcodec', 'rawvideo', '-'] pipe_in = sp.Popen(command_in, stdout = sp.PIPE, bufsize = 10**8) command_out = [ FFMPEG_BIN, '-y', # (optional) overwrite output file if it exists '-f', 'rawvideo', '-vcodec','rawvideo', '-s', '360x240', # size of one frame '-pix_fmt', 'bgr24', '-r', '28', # frames per second '-i', '-', # The imput comes from a pipe '-an', # Tells FFMPEG not to expect any audio #'-vcodec', 'mpeg', 'my_output_videofile.mp4' ] pipe_out = sp.Popen( command_out, stdin=sp.PIPE, stderr=sp.PIPE) import numpy import cv2 import pylab # read width*height*3 bytes (= 1 frame) while True: raw_image = pipe_in.stdout.read(width*height*3) image = numpy.fromstring(raw_image, dtype='uint8') image = image.reshape((height,width,3)) pipe_in.communicate() pipe_out.stdin.write(image.tostring()) pipe_out.communicate() pipe_in.stdout.flush() #cv2.imshow('image',image) #cv2.waitKey(0) # throw away the data in the pipe's buffer. ''' pipe_in.stdin.close() pipe_in.stderr.close() pipe_in.wait() pipe_out.stdout.close() pipe_out.stderr.close() pipe_out.wait() ''' #pipe_out.stdin.write(image.tostring()) However, the output video has only 1 frame(the first frame of input video) Any ideas? Thanks!
has title: Pipe video frame to OpenCV image and then to FFmpeg
type: Question
upvote count: 1
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/38156265
tagged with: python

http://stackoverflow.com/a/48109068
score: 1
has body: You can get an easy factor of 3 if you JIT the function using Numba: You should also explore Numpy and play around in a notebook or IPython to do some performance tests depending on your typical input and come back if you have more specific questions. Just a small update: With Julia (https://julialang.org) I get something around 2.5us, so there is still room for improvement ;)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48108909
type: Answer
answers question: http://stackoverflow.com/q/48108909
upvote count: 1

http://stackoverflow.com/q/48127176
answer count: 2
downvote count: 0
has body: The goal of following code is merely to fill array a with 0 to 9: import multiprocessing import numpy as np from joblib import Parallel, delayed num_cores = multiprocessing.cpu_count() inputs = range(10) a = np.zeros(10) def processInput(): def testNested(t): a[t]= t Parallel(n_jobs=num_cores, backend="threading")(delayed(testNested)(t) for t in range(0, 10)) processInput() I get the pickle error when I'm trying to call multiprocess in a function: AttributeError: Can't pickle local object 'processInput.&lt;locals&gt;.testNested' Question: Any suggestion how to achieve this goal, in a case I have to operate multiprocess within other functions?
has answer: http://stackoverflow.com/a/48127599
tagged with: joblib
has answer: http://stackoverflow.com/a/48132578
favorite count: 0
type: UnansweredQuestion
has title: Pickle in multiprocessing
tagged with: pickle
upvote count: 1
tagged with: python
tagged with: parallel-processing
score: 1
tagged with: multiprocessing
type: Question

http://stackoverflow.com/comment/83319066
type: QuestionComment
comment on: http://stackoverflow.com/q/48169391
has text: Thanks you very much jezrael
score: 0
type: Comment

http://stackoverflow.com/comment/83127942
type: QuestionComment
comment on: http://stackoverflow.com/q/48076908
score: 0
type: Comment
has text: I do not have access to the Python side and there is several other information in the result. The result object can contain any number of elements. Is it even possible to loop at this point?

http://stackoverflow.com/q/48170867
has body: I have two pandas DataFrames df1 and df2 and I want to transform them in order that they keep values only for the index that are common to the 2 dataframes. df1 values 1 0 28/11/2000 -0.055276 29/11/2000 0.027427 30/11/2000 0.066009 01/12/2000 0.012749 04/12/2000 0.113892 df2 values 2 24/11/2000 -0.004808 27/11/2000 -0.001812 28/11/2000 -0.026316 29/11/2000 0.015222 30/11/2000 -0.024480 become df1 value 1 28/11/2000 -0.055276 29/11/2000 0.027427 30/11/2000 0.066009 df2 value 2 28/11/2000 -0.026316 29/11/2000 0.015222 30/11/2000 -0.024480
tagged with: dataframe
score: 24
has answer: http://stackoverflow.com/a/74593782
has answer: http://stackoverflow.com/a/48171118
tagged with: pandas
has title: How to get the common index of two pandas dataframes?
has answer: http://stackoverflow.com/a/48170918
favorite count: 0
has answer: http://stackoverflow.com/a/65325082
has answer: http://stackoverflow.com/a/48170919
answer count: 9
has answer: http://stackoverflow.com/a/53434970
tagged with: python
has answer: http://stackoverflow.com/a/48170943
has answer: http://stackoverflow.com/a/53685823
has comment: http://stackoverflow.com/comment/137892130
upvote count: 25
linked to: http://stackoverflow.com/q/51645195
type: UnansweredQuestion
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48171268
linked to: http://stackoverflow.com/q/50779617

http://stackoverflow.com/q/48042559
accepted answer: http://stackoverflow.com/a/48042750
has comment: http://stackoverflow.com/comment/83055785
possible better answer: http://stackoverflow.com/a/48042611
score: 0
answer count: 3
has title: Execute multiple lines with python in one line for loop
favorite count: 0
has comment: http://stackoverflow.com/comment/83055753
has comment: http://stackoverflow.com/comment/83055885
tagged with: python
has comment: http://stackoverflow.com/comment/83055925
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48042750
upvote count: 1
has body: I have a loop that appends to new list named list1 and it is working, but how can I add something more like print(x) or anything useful to list1.append(...)? word="abcdefg" list1=[] [list1.append(word[i]) for i in range(len(word))] print(list1) I've tried using list1.append(word[i]);print("working") and with ,
has answer: http://stackoverflow.com/a/48042599
downvote count: 1
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/48042611

http://stackoverflow.com/comment/83109107
type: AnswerComment
has text: Even 15 looks possible, with patience. I hated to be the bearer of bad news.
type: Comment
comment on: http://stackoverflow.com/a/48066955
score: 0

http://stackoverflow.com/a/48121983
has comment: http://stackoverflow.com/comment/129519571
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/99140684
score: 221
type: Answer
has comment: http://stackoverflow.com/comment/98768013
has comment: http://stackoverflow.com/comment/104744142
answers question: http://stackoverflow.com/q/48121916
has comment: http://stackoverflow.com/comment/105379213
has comment: http://stackoverflow.com/comment/83234663
upvote count: 225
has body: Yeah, you can install opencv (this is a library used for image processing, and computer vision), and use the cv2.resize function. And for instance use: import cv2 import numpy as np img = cv2.imread('your_image.jpg') res = cv2.resize(img, dsize=(54, 140), interpolation=cv2.INTER_CUBIC) Here img is thus a numpy array containing the original image, whereas res is a numpy array containing the resized image. An important aspect is the interpolation parameter: there are several ways how to resize an image. Especially since you scale down the image, and the size of the original image is not a multiple of the size of the resized image. Possible interpolation schemas are: INTER_NEAREST - a nearest-neighbor interpolation INTER_LINEAR - a bilinear interpolation (used by default) INTER_AREA - resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method. INTER_CUBIC - a bicubic interpolation over 4x4 pixel neighborhood INTER_LANCZOS4 - a Lanczos interpolation over 8x8 pixel neighborhood Like with most options, there is no "best" option in the sense that for every resize schema, there are scenarios where one strategy can be preferred over another.
accepted answer of: http://stackoverflow.com/q/48121916
has comment: http://stackoverflow.com/comment/104756648
downvote count: 4

http://stackoverflow.com/comment/83441486
score: 0
type: Comment
has text: @floppy_molly the term `0.1*np.random.randn(1)` is just a single normally distributed random number, just there for the example to show points moving but you'd do this based on the player inputs I assume. I'm not sure you need `juggle_axes`, the mouse rotation seems to look okay for me without it and makes no difference. I've deleted it.
comment on: http://stackoverflow.com/a/48147473
type: AnswerComment

http://stackoverflow.com/comment/83088348
score: 0
type: QuestionComment
type: Comment
has text: @jezrael I think I understood. He wants to split the dataframe in n dataframes between (1 or 2) and (1 or 2). So he gets index 1,2 in 1 (this is between 1 and 2) and index 4 in another (this is between 2 and 1)
comment on: http://stackoverflow.com/q/48057864

http://stackoverflow.com/q/48171462
favorite count: 0
has comment: http://stackoverflow.com/comment/83322494
duplicate of: http://stackoverflow.com/q/28419763
has comment: http://stackoverflow.com/comment/83322547
tagged with: python
tagged with: tkinter-entry
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
downvote count: 1
type: Question
has body: I am using Tkinter and I want my elements to resize when the window resizes (only horizontally) I tried sticking to W+E but apparently this only works when the window is created but not when it's resized. Minimal example: from tkinter import Tk, Entry, Label, StringVar, W, E, N, S class Test: def __init__(self, master): # Variable definitions self.master = master self.var1 = StringVar() # Element definitions self.label1 = Label(text="Dummy test") self.entry1 = Entry(master, textvariable=self.var1) # Grid placement self.label1.grid(row=0, column=0, sticky=W) self.entry1.grid(row=0, column=1, sticky=W+E) root = Tk() Test(root) root.mainloop() Original window when program is executed: When I resize, I want the Entry to grow and shrink with the window
score: 3
upvote count: 4
tagged with: tkinter-canvas
linked to: http://stackoverflow.com/q/28419763
has title: Resize Entry with window in Tkinter
has comment: http://stackoverflow.com/comment/83322460
has comment: http://stackoverflow.com/comment/83322645

http://stackoverflow.com/comment/83318566
type: QuestionComment
has text: How could that be?
comment on: http://stackoverflow.com/q/48169582
score: 0
type: Comment

http://stackoverflow.com/a/48113814
score: 1
accepted answer of: http://stackoverflow.com/q/48109216
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: you just need to install microsoft build tools with latest versions say 2015 and 2017 . Then if problem remains same then you can go towards fix i had given here FixOrangeImageAnalysis . and you must download zip file i had shared there . and put all into your Orange/Lib/site-packages folder . All files whose names startes with any of following must be replaced h cache lap lock msg pill orange pillow image imageanalytics.pth I guess FixOrangeImageAnalysis should solve your issue
upvote count: 1
answers question: http://stackoverflow.com/q/48109216

http://stackoverflow.com/comment/83061493
score: 0
has text: Thank you roganjosh. I feel like like a dummy hahaha. Thank you for pointing that out. It is now printing 16 correctly with the __str__ method and correctly saved in the instance.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48045155

http://stackoverflow.com/a/48136273
upvote count: 3
has comment: http://stackoverflow.com/comment/83255319
has comment: http://stackoverflow.com/comment/83273669
has comment: http://stackoverflow.com/comment/83255370
has comment: http://stackoverflow.com/comment/83255269
has comment: http://stackoverflow.com/comment/83250047
downvote count: 0
has comment: http://stackoverflow.com/comment/83255386
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48135569
has comment: http://stackoverflow.com/comment/83255301
has comment: http://stackoverflow.com/comment/83249930
type: Answer
has body: I think you can use list comprehension: df['A'] = df['A'].apply(lambda x: [str(y).zfill(10) for y in x]) print (df) A 0 [0011234466, 0077777777, 0012345678, 0023452345] 0 [0099999999, 0066666666, 0044332211, 0056781234] df['A'] = [[str(y).zfill(10) for y in x] for x in df['A']] print (df) A 0 [0011234466, 0077777777, 0012345678, 0023452345] 0 [0099999999, 0066666666, 0044332211, 0056781234] Similar solution with format: df['A'] = [['{:010d}'.format(y) for y in x] for x in df['A']] print (df) A 0 [0011234466, 0077777777, 0012345678, 0023452345] 0 [0099999999, 0066666666, 0044332211, 0056781234] EDIT: data = np.array([[11234466], [77777777], [12345678], [23452345]]) data1 = np.array([[99999999], [66666666], [44332211], [56781234]]) df=pd.DataFrame({'A' : [data.tolist()]}) df1=pd.DataFrame({'A' : [data1.tolist()]}) df=pd.concat([df,df1]) df['A'] = [[['{:010d}'.format(z) for z in y] for y in x] for x in df['A']] print (df) A 0 [[0011234466], [0077777777], [0012345678], [00... 0 [[0099999999], [0066666666], [0044332211], [00...
has comment: http://stackoverflow.com/comment/83249990
has comment: http://stackoverflow.com/comment/83255194
accepted answer of: http://stackoverflow.com/q/48135569
score: 3

http://stackoverflow.com/q/48130916
score: 2
downvote count: 0
tagged with: jupyter
has title: Tkinter crashes Jupyter kernel?
has comment: http://stackoverflow.com/comment/83239861
favorite count: 0
tagged with: jupyter-notebook
tagged with: tkinter
type: Question
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48135559
answer count: 1
has body: So I'm starting out with tkinter (8.6.7) for the first time, installed via conda unto one of my environments with python 3.5.4 on it, and for some reasons it just keeps crashing my jupyter notebook. This is the simple code I use, from tkinter import filedialog from tkinter import * root = Tk() root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*"))) and as soon as I exit the dialog window that gets opened using Finder (I'm on a mac), my kernel crashes and restarts, even if I pick no files and just press cancel. Does anyone have any idea why this keeps happening? My environment is up to date, and can use numpy, for ex., with no problems.
tagged with: crash
accepted answer: http://stackoverflow.com/a/48135559
type: AnsweredQuestion

http://stackoverflow.com/comment/101539256
has text: Did you manage to resolve this? I'm just facing the very same issue only on travis CI, while on production it works.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48079316
type: QuestionComment

http://stackoverflow.com/comment/83027980
type: QuestionComment
comment on: http://stackoverflow.com/q/48028871
score: 0
has text: Don't indent manually. Copy, select the code lines in the editor, and use the `{}` button on the toolbar to have the editor manage the indentation for you.
type: Comment

http://stackoverflow.com/a/48035792
answers question: http://stackoverflow.com/q/48035748
type: Answer
score: 0
has body: You can concatenate the lists, cast to set, and check for existence: A=[1,2,3,4] B=[3,6,7,8,9,10] def check_existence(a, b): return bool([i for i in set(a+b) if i in set(a) and i in set(b)] print(check_existence(A, B))

http://stackoverflow.com/comment/137159598
type: Comment
has text: I have seen this pattern of keeping the wsgi.py (file/module) in app folder. since you are doing COPY . /usr/src/app and if I assume wsgi.py file is present in at /usr/src/app/wsgi.py then all you need to do is add WORKDIR /usr/src/app before the last line. making wsgi.py available at base location.
comment on: http://stackoverflow.com/q/48121048
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83017055
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48023385
score: 0
has text: Can you show the result of that command? I was thinking there might be something wrong with the csv or how we parse the csv,

http://stackoverflow.com/q/48155048
score: 1
type: Question
tagged with: difference
has title: Calculate diffrence between two dates
tagged with: pandas
has body: I have a DB with two date column (Y-m-d): Date_from Date_to 17/01/01 17/01/05 17/02/03 NaN 17/05/01 17/05/05 ... Date_from and Date_to are pandas column. I built a function that if: - in Date_to there NaN returns me "corrence"; - in Dta_to there is no Nan makes the difference between the two columns Both results are saved in a third column. Like this: Data_from Date_to Difference 17/01/01 17/01/05 4 17/02/03 NaN corrence 17/05/01 17/05/05 4 ... The function is this: from datetime import datetime def diff(data,d1, d2): if pd.isnull(data.iloc[[1],[12]]): data['difference'] = 366 else: data[d1] = pd.to_datetime(data[d1]) data[d2] = pd.to_datetime(data[d2]) data['difference'] = data[d2] - data[d1] return data d1 = ["Date_from"] d2 = ["Date_to"] df = replace_NaN(df,d1,d2) The error that get out is this: TypeError: replace_NaN() takes 2 positional arguments but 3 were given I don't understand why
upvote count: 1
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48155092
type: UnansweredQuestion
tagged with: datetime
tagged with: python
downvote count: 0

http://stackoverflow.com/q/48082037
has comment: http://stackoverflow.com/comment/83142252
downvote count: 0
has answer: http://stackoverflow.com/a/48093573
has comment: http://stackoverflow.com/comment/83142091
has comment: http://stackoverflow.com/comment/83141964
has comment: http://stackoverflow.com/comment/83142157
has title: Pygame list collision
answer count: 1
has comment: http://stackoverflow.com/comment/83141519
tagged with: python
tagged with: pygame
favorite count: 0
accepted answer: http://stackoverflow.com/a/48093573
upvote count: 1
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/83142123
score: 1
has comment: http://stackoverflow.com/comment/83141963
tagged with: collision-detection
has body: I have a map im creating in python using pygame with a player and walls: import pygame x = 25 y = 19 collision = [ [0,0,0,37],#vertical [4,23,4,27], [12,18,12,25], [13,0,13,1], [13,4,13,7], [13,10,13,11], [15,13,15,18], [15,23,15,37], [19,0,19,13], [29,25,29,26], [29,29,29,37], [35,0,35,9], [35,12,35,17], [35,21,35,26], [35,29,35,37], [36,17,36,21], [44,0,44,6], [44,10,44,17], [54,0,54,17], [0,0,19,0],#horizontal [35,0,46,0], [52,0,54,0], [13,5,19,5], [19,6,24,6], [30,6,35,6], [0,13,10,13], [15,13,21,13], [25,13,44,13], [35,17,36,17], [44,17,54,17], [35,21,36,21], [4,23,12,23], [0,25,4,25], [19,25,36,25], [4,27,12,27], [0,37,35,37], [14,12,14,12],#dots [11,14,11,14] ] white = (255,255,255) black = (0,0,0) red = (255,0,0) pygame.init() screen = pygame.display.set_mode((200,200)) pygame.display.set_caption('Collision') screen.fill(white) for list in collision:#draw map pygame.draw.line(screen,black,(list[0],list[1]),(list[2],list[3]),1) pygame.draw.line(screen,red,(x,y),(x,y),1)#draw player pygame.display.update() while(True): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_w: for list in collision: #---START OF EQUATION---# if(list[0]&lt;=list[2] and not(y-1==list[1] and x&gt;=list[0] and x&lt;=list[2])) or (list[0]&gt;list[2] and not(y-1==list[1] and x&gt;=list[2] and x&lt;=list[0])):#updated #---END OF EQUATION---# pygame.draw.line(screen,white,(x,y),(x,y),1) y-=1 pygame.draw.line(screen,red,(x,y),(x,y),1) break elif event.key == pygame.K_s: for list in collision: if(list[0]&lt;=list[2] and not(y+1==list[1] and x&gt;=list[0] and x&lt;=list[2])) or (list[0]&gt;list[2] and not(y+1==list[1] and x&gt;=list[2] and x&lt;=list[0])):#updated pygame.draw.line(screen,white,(x,y),(x,y),1) y+=1 pygame.draw.line(screen,red,(x,y),(x,y),1) break elif event.key == pygame.K_a: for list in collision: if(list[1]&lt;=list[3] and not(x-1==list[0] and y&gt;=list[1] and y&lt;=list[3])) or (list[1]&gt…
type: Question
has comment: http://stackoverflow.com/comment/83140447
has comment: http://stackoverflow.com/comment/83160511

http://stackoverflow.com/q/48049474
has comment: http://stackoverflow.com/comment/83070552
tagged with: function
has comment: http://stackoverflow.com/comment/83070510
favorite count: 0
tagged with: scope
has answer: http://stackoverflow.com/a/48049508
tagged with: python
has comment: http://stackoverflow.com/comment/83070974
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48049735
has answer: http://stackoverflow.com/a/48049735
has comment: http://stackoverflow.com/comment/83071005
has comment: http://stackoverflow.com/comment/83070955
has body: I have defined a function within another function in python and now I would like to call the inner function. Is this possible, in python? How do I call func2 from func3? def func1(): def func2(): print("Hello!") def func3(): # Enter code to call func2 here
has title: How to call a function within a function from another function in Python?
linked to: http://stackoverflow.com/q/291978
linked to: http://stackoverflow.com/q/8457669
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83070551
accepted answer: http://stackoverflow.com/a/48049508
upvote count: 9
downvote count: 5
duplicate of: http://stackoverflow.com/q/8457669
score: 4
has comment: http://stackoverflow.com/comment/83070512
type: Question
answer count: 2

http://stackoverflow.com/q/48022786
tagged with: pyqt
tagged with: pyqt4
answer count: 1
score: 0
linked to: http://stackoverflow.com/q/19199863
has title: PyQt5: QPainter overlay QWidget
has answer: http://stackoverflow.com/a/48023082
tagged with: python
has body: To this question I am referring to the answer from @Kuba Ober Draw Rectangular overlay on QWidget at click My problem: I dont know how to "translate" the C++ (or C?) into Python. :-( Thus I ask this "duplicated" question again, and wish anyone would help to rewrite the code to achieve the overlay effect in PyQt5. As an example, I prepare here some code: # -*- coding: utf-8 -*- import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * class MyApp(QWidget): def __init__(self): super(MyApp, self).__init__() self.initUI() def initUI(self): self.text = "hello world" self.setGeometry(100, 100, 400, 300) self.setWindowTitle('Draw Demo') self.btn = QPushButton("Butten should be overlayed", self) self.btn.setFixedSize(200, 200) self.btn.move(40, 40) self.show() def paintEvent(self, event): qp = QPainter() qp.begin(self) qp.setPen(QColor(Qt.red)) qp.setFont(QFont('Arial', 20)) qp.drawText(10, 50, "hello Python") qp.setPen(QColor(Qt.blue)) qp.drawLine(10, 100, 100, 100) qp.drawRect(10, 150, 150, 100) qp.setPen(QColor(Qt.red)) qp.drawEllipse(100, 50, 100, 50) # qp.drawPixmap(220, 10, QPixmap("python.jpg")) qp.fillRect(200, 175, 150, 100, QBrush(Qt.SolidPattern)) qp.end() if __name__ == '__main__': app = QApplication(sys.argv) window = MyApp() window.show() sys.exit(app.exec_()) Target is: Let the Button shown in the background (overlayed by QPainter), but it is transparent to mouse event. Thus I could click the button, even though it is covered by QPainter. Any help will be highly appreciated!
type: AnsweredQuestion
tagged with: pyqt5
type: Question
accepted answer: http://stackoverflow.com/a/48023082

http://stackoverflow.com/q/48035125
type: Question
has title: Speed of Logistic Regression on MNIST with Tensorflow
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48070021
accepted answer: http://stackoverflow.com/a/48070021
downvote count: 0
has body: I am taking the CS 20SI: Tensorflow for Deep Learning Research from Stanford. I have question regarding the following code: import time import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Step 1: Read in data # using TF Learn's built in function to load MNIST data to the folder data/mnist MNIST = input_data.read_data_sets("/data/mnist", one_hot=True) # Batched logistic regression learning_rate = 0.01 batch_size = 128 n_epochs = 25 X = tf.placeholder(tf.float32, [batch_size, 784], name = 'image') Y = tf.placeholder(tf.float32, [batch_size, 10], name = 'label') #w = tf.Variable(tf.random_normal(shape = [int(shape[1]), int(Y.shape[1])], stddev = 0.01), name='weights') #b = tf.Variable(tf.zeros(shape = [1, int(Y.shape[1])]), name='bias') w = tf.Variable(tf.random_normal(shape=[784, 10], stddev=0.01), name="weights") b = tf.Variable(tf.zeros([1, 10]), name="bias") logits = tf.matmul(X,w) + b entropy = tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=Y) loss = tf.reduce_mean(entropy) #computes the mean over examples in the batch optimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate).minimize(loss) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) n_batches = int(MNIST.train.num_examples/batch_size) for i in range(n_epochs): start_time = time.time() for _ in range(n_batches): X_batch, Y_batch = MNIST.train.next_batch(batch_size) opt, loss_ = sess.run([optimizer, loss], feed_dict = {X: X_batch, Y:Y_batch}) end_time = time.time() print('Epoch %d took %f'%(i, end_time - start_time)) On this code, logistic regression with MNIST dataset is performed. The author states: Running on my Mac, the batch version of the model with batch size 128 runs in 0.5 second However, when I run it, each epoch takes around 2 seconds, giving a total execution time of around a minute. Is it reasonable that this example takes that time? Currently I have a Ryzen 1700 without OC (3.0…
tagged with: tensorflow
tagged with: logistic-regression
type: AnsweredQuestion
tagged with: performance
score: 1
tagged with: mnist
linked to: http://stackoverflow.com/q/41804380

http://stackoverflow.com/comment/83096874
has text: It is wrong. For that you'd use [`list.extend()`](https://docs.python.org/3/tutorial/datastructures.html).
score: 2
comment on: http://stackoverflow.com/q/48062114
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83263296
comment on: http://stackoverflow.com/a/48142494
type: AnswerComment
score: 0
type: Comment
has text: @PaulRooney Who's to say? I don't know anything about the data importing/processing pipeline. It's simply something to be aware of.

http://stackoverflow.com/a/48125391
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: It seems that, I had to make a tuple of urlconf and app_name. from django.apps import apps products_name = apps.get_app_config('products').verbose_name and then, url(r'^products/', include(('products.urls', products_name), namespace='products')),
accepted answer of: http://stackoverflow.com/q/48125161
answers question: http://stackoverflow.com/q/48125161

http://stackoverflow.com/comment/83235498
score: 0
has text: Maybe str is bit too much for a datetime column
comment on: http://stackoverflow.com/a/48129271
type: AnswerComment
type: Comment

woe-id
type: Tag
tag name: woe-id
tags question: http://stackoverflow.com/q/48034096

http://stackoverflow.com/q/48055935
tagged with: regex
has comment: http://stackoverflow.com/comment/83084175
score: 1
has body: Suppose a string: s = 'F3·Compute·Introduction to Methematical Thinking.pdf' I substitute F3·Compute· with '' using regex In [23]: re.sub(r'F3?Compute?', '',s) Out[23]: 'F3·Compute·Introduction to Methematical Thinking.pdf' It failed to work as I intented When tried, In [21]: re.sub(r'F3·Compute·', '', 'F3·Compute·Introduction to Methematical Thinking.pdf') Out[21]: 'Introduction to Methematical Thinking.pdf' What's the problem with my regex pattern?
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83084236
has comment: http://stackoverflow.com/comment/83084206
answer count: 2
has answer: http://stackoverflow.com/a/48056009
downvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/22937618
has answer: http://stackoverflow.com/a/48056001
type: UnansweredQuestion
has title: Modify string with `re.sub`
tagged with: python
linked to: http://stackoverflow.com/q/22937618

http://stackoverflow.com/comment/83181648
type: Comment
type: QuestionComment
has text: `with open(filename, 'rb') as file:`: problem gone. note that your code cannot work in python 3 because `s` is a string and the output file expects bytes.
score: 1
comment on: http://stackoverflow.com/q/48103124

http://stackoverflow.com/q/48105860
score: 0
has comment: http://stackoverflow.com/comment/83191129
has title: best way to do python multiprocessing with list operations
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83187533
tagged with: multiprocessing
type: Question
linked to: http://stackoverflow.com/q/38393269
has body: I have a list operation where i need to loop through a list, identify an item, and build a dictionary, what's the best multiprocessing way to do this? the list is rather long with over 1M items. result_dict = dict() for id in list_a: if id not in check_list: #black_list for verfication result_dict[id]= func_buildup(id) # function to build up value
has comment: http://stackoverflow.com/comment/83187555
has comment: http://stackoverflow.com/comment/83187727

http://stackoverflow.com/q/48015321
has comment: http://stackoverflow.com/comment/83000001
score: 0
duplicate of: http://stackoverflow.com/q/2087370
tagged with: html-entities
has comment: http://stackoverflow.com/comment/83000932
has comment: http://stackoverflow.com/comment/82999832
linked to: http://stackoverflow.com/q/3094659
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83000090
has title: Python: How to remove html entities from list items?
type: Question
has comment: http://stackoverflow.com/comment/83001044
has body: I have a list with results from re.findall from a web page. List items contains &amp; # 171; &amp; # 8211; etc. How do i remove these substrings from list items ?
has comment: http://stackoverflow.com/comment/83000669

http://stackoverflow.com/q/48022092
upvote count: 2
possible better answer: http://stackoverflow.com/a/48022306
has comment: http://stackoverflow.com/comment/83013231
answer count: 2
downvote count: 3
linked to: http://stackoverflow.com/q/10825926
has answer: http://stackoverflow.com/a/48022306
favorite count: 0
duplicate of: http://stackoverflow.com/q/10825926
has comment: http://stackoverflow.com/comment/83013220
has comment: http://stackoverflow.com/comment/83013242
tagged with: python
has answer: http://stackoverflow.com/a/48022331
accepted answer: http://stackoverflow.com/a/48022331
type: AnsweredQuestion
tagged with: python-3.x
linked to: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/83013514
type: Question
tagged with: rounding
score: -1
has title: Python round() error?
has body: What is wrong with the round function in Python 3.6.3? I tested the code below: a = 0.5 b = 0.5000001 print (round(a),round(b)) ..and get result as 0 1 So rounding 0.5 -> 0 but 0.500001 -> 1. Should both variables get value of 1?

http://stackoverflow.com/q/48082515
has comment: http://stackoverflow.com/comment/83139542
tagged with: group-by
has title: combine rows into single cell
has comment: http://stackoverflow.com/comment/83140607
has comment: http://stackoverflow.com/comment/83140633
has answer: http://stackoverflow.com/a/48083946
answer count: 3
has answer: http://stackoverflow.com/a/48087595
downvote count: 0
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48082852
tagged with: python
has comment: http://stackoverflow.com/comment/83140160
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48082852
accepted answer: http://stackoverflow.com/a/48087595
upvote count: 3
has body: I currently have a dataframe (df) like this: name info alpha foo,bar alpha bar,foo beta foo,bar beta bar,foo beta baz,qux I'm looking to create a dataframe like this: name info alpha (foo,bar),(bar,foo) beta (foo,bar),(bar,foo),(baz,qux) I'm getting close with groupby.apply(list). Eg. new_df=df.groupby('name')['info'].apply(list) However, I can't seem to figure out how to get the output in the original dataframe format. (i.e with two columns (like the example) I think I need reset_index and unstack? Appreciate any help!
type: Question
has comment: http://stackoverflow.com/comment/83139586
score: 3
has comment: http://stackoverflow.com/comment/83139622

http://stackoverflow.com/comment/83252187
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48137454
has text: I think this can be quite unsafe, since `coord` can be zero (or close to zero). Furthermore it would convert an *integer* number to *floating* points, and floating punts are quite unsafe for comparisons (since these are subject to rounding errors).

python-collections
type: Tag
tag name: python-collections
tags question: http://stackoverflow.com/q/48015145
tags question: http://stackoverflow.com/q/48022202

http://stackoverflow.com/q/48062296
answer count: 1
favorite count: 0
has title: Pandas: Keep dataframes from dict that exclude certain values
has answer: http://stackoverflow.com/a/48062326
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I have a dictionary named dfs that contains dataframes as such: team_id player_id x_loc y_loc radius game_clock shot_clock \ 1 -1 -1 27.91690 41.37191 4.18103 710.78 11.71 2 -1 -1 31.90677 36.18951 3.47588 710.30 11.44 3 -1 -1 34.13352 27.62760 1.17149 709.82 11.16 4 -1 -1 34.74723 23.90685 3.42091 709.34 10.88 5 -1 -1 24.68878 15.18316 5.02066 708.86 10.60 6 -1 -1 17.59483 9.16468 3.03803 708.38 10.32 7 -1 -1 18.69309 12.53733 2.22372 707.90 10.04 8 -1 -1 16.23927 17.82597 5.45565 707.42 9.77 9 -1 -1 9.84219 8.62434 8.59493 706.94 9.49 10 -1 -1 5.73599 3.83553 4.77459 706.46 9.21 11 -1 -1 5.49103 3.97060 4.82267 705.98 8.93 12 -1 -1 2.44574 3.85045 0.84340 705.50 8.65 13 -1 -1 30.44487 43.11858 7.48128 713.02 13.01 quarter game_id event_id GAME_ID EVENTMSGTYPE PLAYER1_TEAM_ID 1 1 21500492 1 21500492 NaN 1.610613e+09 2 1 21500492 1 21500492 NaN 1.610613e+09 3 1 21500492 1 21500492 NaN 1.610613e+09 4 1 21500492 1 21500492 NaN 1.610613e+09 5 1 21500492 1 21500492 NaN 1.610613e+09 6 1 21500492 1 21500492 NaN 1.610613e+09 7 1 21500492 1 21500492 NaN 1.610613e+09 8 1 21500492 1 21500492 NaN 1.610613e+09 9 1 21500492 1 21500492 NaN 1.610613e+09 10 1 21500492 1 21500492 NaN 1.610613e+09 11 1 21500492 1 21500492 NaN 1.610613e+09 12 1 21500492 1 21500492 NaN 1.610613e+09 13 1 21500492 2 21500492 2.0 1.610613e+09 I want to find the ones that don't contain the values [3, 5, 6, 7, 8, 9, 10, 11, 12, 13] on the EVENTMSGTYPE column and store them in a new dictionary, but I can't seem to find a way to do it.
type: Question
tagged with: pandas
upvote count: 1
accepted answer: http://stackoverflow.com/a/48062326

http://stackoverflow.com/comment/83187861
has text: you might wanna use try-except because the user might provide values that are not integer
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48105967

http://stackoverflow.com/a/48127848
has body: The ability to pass a tuple of strings to str.endswith() to was introduced in Python 2.5: str.endswith(suffix[, start[, end]]) Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. Changed in version 2.5: Accept tuples as suffix.
upvote count: 1
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48098947

http://stackoverflow.com/q/48127586
has comment: http://stackoverflow.com/comment/83231909
has answer: http://stackoverflow.com/a/48127630
has comment: http://stackoverflow.com/comment/83232025
tagged with: python
tagged with: depth-first-search
has title: Addition and += give different results for list (depth first search)
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/83231875
accepted answer: http://stackoverflow.com/a/48127630
has body: I've been trying to understand depth first search, and using various sources online obtained the following code: graph = {'A': ['B', 'D'], 'B': ['E'], 'C': [], 'D': ['C', 'E'], 'E': ['H', 'I', 'J'], 'F': [], 'G': [], 'H': ['F'], 'I': [], 'J': ['G']} def dfs(graph, start, end, path=None): if path == None: path = [] path = path + [start] paths = [] if start == end: return [path] for neighbour in graph[start]: if neighbour not in path: paths.extend(dfs(graph, neighbour, end, path)) return paths print(dfs(graph, 'A', 'G')) This outputs the desired result: [['A', 'B', 'E', 'J', 'G'], ['A', 'D', 'E', 'J', 'G']] But when I replace the line path = path + [start] with path += [start] (or path.extend([start]), which I understand does the same thing) I get the following output: 'A', 'B', 'E', 'H', 'F', 'I', 'J', 'G', 'D', 'C' I know this is to do with a difference in the operations, but I don't really understand how it applies here. Please could someone explain this?
downvote count: 1
has comment: http://stackoverflow.com/comment/83232080
type: Question
upvote count: 5
score: 4
has comment: http://stackoverflow.com/comment/83231942
has comment: http://stackoverflow.com/comment/83232094
linked to: http://stackoverflow.com/q/1132941
answer count: 1
has comment: http://stackoverflow.com/comment/83231966
has comment: http://stackoverflow.com/comment/83232015
favorite count: 0

http://stackoverflow.com/comment/83022315
has text: Although, looking at the [`aifc` module docs](https://docs.python.org/3.6/library/aifc.html#aifc.aifc.setcomptype), I don't think the module even supports raw 32-bit floating-point data.
comment on: http://stackoverflow.com/q/48026172
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48048811
has body: The error message is this ValueError: Expected 2D array, got 1D array instead The following seems to be a suggestion generated by the library. Try as it tells you to. reshape is actually quite a useful technique to regularize input size for machine learning. It would further be a good practice to keep track of what shape you are inputting for training and testing. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
score: 0
answers question: http://stackoverflow.com/q/48048776
type: Answer
has comment: http://stackoverflow.com/comment/83072496
has comment: http://stackoverflow.com/comment/83072923

http://stackoverflow.com/a/48177252
type: Answer
has body: I found out a solution. Place my data into a byte array, and simply reverse it. In hexadecimal, reversing pairs will change it from big-> little, little-> big etc. Therefore reversing a byte array, where each index is two hex pairs, the same applies. Example, 0000 1F40 (Big endian) -> 401F 0000 (Little Endian) If each each two hex numbers represent a byte, i.e 1F or 40 are equal to one byte therefore reversing a byte array is equivalent.
accepted answer of: http://stackoverflow.com/q/48157435
score: 0
answers question: http://stackoverflow.com/q/48157435
upvote count: 1
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/q/48124891
has answer: http://stackoverflow.com/a/48125299
has answer: http://stackoverflow.com/a/48124910
type: Question
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/48124910
tagged with: python
has body: I'm trying to loop through my subdirectories where each of them contains two images. I'm trying to read those two images, and put them as a pair in a tuple. This is what I did: import os import os.path from PIL import Image import cv2 path = '/Users/abc/Desktop/images' pairs = [] for root, dirs, files in os.walk(path): for file in files: if file.startswith('1'): im1 = cv2.imread(root + '/' + '1.jpg') elif file.startswith('2'): im2 = cv2.imread(root + '/' + '2.jpg') pair = (im1,im2) pairs.append(pair) I however get the following error: Traceback (most recent call last): File "create_pair.py", line 16, in &lt;module&gt; pair = (im1,im2) NameError: name 'im1' is not defined What am I doing wrong? Thanks.
has title: Creating a tuple of image pairs
accepted answer: http://stackoverflow.com/a/48124960
has comment: http://stackoverflow.com/comment/83226759
tagged with: loops
tagged with: computer-vision
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48124960

http://stackoverflow.com/comment/83245779
score: 0
has text: The answers to the question [Saving an Object (Data persistence)](https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence) might be helpful.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48134176

http://stackoverflow.com/q/48103582
has answer: http://stackoverflow.com/a/48103713
score: 1
accepted answer: http://stackoverflow.com/a/48103713
answer count: 1
has comment: http://stackoverflow.com/comment/83182761
downvote count: 0
has title: Python import module load_source
favorite count: 0
has comment: http://stackoverflow.com/comment/83182790
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83182701
upvote count: 1
has body: I have question on the load_source. when my 2 .py files are in the same directory /home/pi they work fine. main.py #!/usr/bin/python import buttonlog buttonlog.py import datetime i = datetime.datetime.now() #OPEN FILE &amp; APPEND f=open('buttonlog.txt','a') #WRITE DATE THEN NEW LINE WITH THE '\N' f.write(i.isoformat() + '\n') When I run python main.py it writes an entry like I'd expect. However I'd like to store main.py in another directory so I tried this, it is stored in the /home/pi/test #!/usr/bin/python import imp imp.load_source('buttonlog', '/home/pi/buttonlog.py') When I run python /home/pi/test/main.py I do not get any errors nor does it write an entry into my file. What am I doing wrong?
type: Question

http://stackoverflow.com/comment/83150510
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48087801
has text: Sorry, I missed that line. But try this anyway, because it sounds like python is looking for `pip` in the wrong place.
type: AnswerComment

http://stackoverflow.com/comment/83164562
type: AnswerComment
comment on: http://stackoverflow.com/a/48093576
type: Comment
has text: Install an aws cli on your machine. You can find some help at: https://stackoverflow.com/questions/24536583/bash-script-to-install-aws-cli-tools This'll help you to work with your s3 buckets from cli.
score: 0

http://stackoverflow.com/comment/83179221
type: QuestionComment
has text: @AntonvBR: Yes, my guess is that this is simply homework to practice recursion.
comment on: http://stackoverflow.com/q/48101933
score: 0
type: Comment

http://stackoverflow.com/comment/83074759
type: Comment
score: 0
type: AnswerComment
has text: I get `Unresolved Reference` error for `WebDriverWait`, for `EC` and for `By`, what are these?
comment on: http://stackoverflow.com/a/48051419

http://stackoverflow.com/a/48081375
score: 1
downvote count: 0
type: Answer
has body: Thanks to @DeepSpace I was able to get this done by using the following because 2.5 is still in beta at the moment: sudo pip3 install openpyxl==2.5.0b1
upvote count: 1
answers question: http://stackoverflow.com/q/48081209

http://stackoverflow.com/q/48072614
tagged with: wxpython
has comment: http://stackoverflow.com/comment/83220770
has comment: http://stackoverflow.com/comment/83188656
has answer: http://stackoverflow.com/a/48122620
has body: I use Python 2.7.14 with pyenv I try to run Ride IDE for Robotframework on macOS. I successfully install Ride with pip: pip install robotframework-ride But when I run ride.py I get error like this: wxPython not found. You need to install wxPython 2.8.12.1 with unicode support to run RIDE. wxPython 2.8.12.1 can be downloaded from http://sourceforge.net/projects/wxpython/files/wxPython/2.8.12.1/ I download wxPyhton from the link, but the installation failed. The installer from this link works, but that's not the version that I'm looking for.
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/83182024
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48122620
tagged with: robotframework
has title: Couldn't install classic wxPython 2.8.12.1 on macOS High Sierra 10.13.2
linked to: http://stackoverflow.com/q/40960855
score: 0
tagged with: robotframework-ide
answer count: 1

http://stackoverflow.com/q/48103882
upvote count: 1
type: Question
score: 1
tagged with: feature-selection
downvote count: 0
has body: I want to apply Recursive Feature Elimination (RFE) on a model that is built using Keras models and layers. When I run: from sklearn.feature_selection import RFE ## building Keras model ... # rfe = RFE(model, 3) rfe = rfe.fit(X_train, y_train) I get following error: TypeError: Cannot clone object '&lt;keras.models.Sequential object at 0x7f1ab93eb510&gt;' (type &lt;class 'keras.models.Sequential'&gt;): it does not seem to be a scikit-learn estimator as it does not implement a 'get_params' methods. I tried to clone my Keras model by clone_model(model), but it did not help. Do I have to use sklearn estimator to be able to use RFE?
tagged with: scikit-learn
tagged with: keras
favorite count: 0
has title: Recursive Feature Elimination on Keras Models
has comment: http://stackoverflow.com/comment/83220061
tagged with: python
has comment: http://stackoverflow.com/comment/83194178
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/83080821
type: Comment
type: QuestionComment
has text: Added code above
comment on: http://stackoverflow.com/q/48054053
score: 0

http://stackoverflow.com/a/48129665
answers question: http://stackoverflow.com/q/48129522
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/83241744
downvote count: 0
score: 1
has body: There is just this User-Agent header check you need to pass: from bs4 import BeautifulSoup import requests web_page = 'https://mcassessor.maricopa.gov/index.php' response = requests.get(web_page, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' }) soup = BeautifulSoup(response.content, 'html.parser') print (soup.prettify())

http://stackoverflow.com/comment/83111270
has text: Whatever number was before the smallest one gets moved to the last place so the entire row shifts until the smallest is first, if you know what I mean.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48068576

http://stackoverflow.com/q/48159051
has body: I am very new to robot framework. I am trying to create object of a python class from Robot framework. The following is the python code: class sample(): def __init__(self,dict1,connect=True): self.device=dict1['device'] self.ip=dict1['ip'] self.uname=dict1['uname'] self.password=dict1['password'] self.dict1={'device':self.device,'ip':self.ip,'uname':self.uname,password:self.password} self.is_connect=False self.is_config_mode=False if connect: self.connects_to() def connect_to(self): print('stuff') I need to make an object of the class sample in Robot file and use it to call other subsequent methods. What I did is: *** Settings *** Documentation Testing connection Library Collections Library RequestsLibrary Library sample.sample ${dict1} WITH NAME obj Variables *** Keywords *** Test_Connection ${name} [Documentation] Testing connection ${a}= obj.connect_ssh I am getting the following error: Test Library 'sample' expected 1 to 2 arguments, got 0. Kindly help. Thanks.
has title: Creating instances of python class from Robotframework
score: 0
linked to: http://stackoverflow.com/q/48134803
possible better answer: http://stackoverflow.com/a/48162421
accepted answer: http://stackoverflow.com/a/48162539
has answer: http://stackoverflow.com/a/48162421
answer count: 3
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48175774
has answer: http://stackoverflow.com/a/48162539
type: Question
tagged with: robotframework

nested
tags question: http://stackoverflow.com/q/48030702
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/48031988
tags question: http://stackoverflow.com/q/48095092
tags question: http://stackoverflow.com/q/48039581
tags question: http://stackoverflow.com/q/48151953
tags question: http://stackoverflow.com/q/48035862
tags question: http://stackoverflow.com/q/48132333
tags question: http://stackoverflow.com/q/48016230
tags question: http://stackoverflow.com/q/48052316
tags question: http://stackoverflow.com/q/48017281
tags question: http://stackoverflow.com/q/48143394

http://stackoverflow.com/q/48107528
upvote count: 2
has comment: http://stackoverflow.com/comment/83217364
tagged with: pandas
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52101477
has title: Insert pandas dataframe into mongodb
score: 2
downvote count: 0
has body: reindexing dataframe to dict,And I want to insert data into mongodb new Collection? Dataframe: df = mydf.groupby(pd.TimeGrouper(key='timestamp', freq='5Min'))['value'].apply(lambda x: x[x!='-1'].count()) k = df.reset_index().T.to_dict().values() print(k) p={} p[name] = k #adding new key into json print(p) db.col8.insert_many(k) #inserting data into mongodb Error: TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping Expected Result: { "_id" : ObjectId("5a4f07559799980e94717c69"), "name": "abc" "timestamp" : ISODate("2018-01-03T12:00:00Z"), "value" : 0 } And insert should not be duplicate it should do upsert.So how to frame the mongodb query for insertion/update using pandas dataframe?
tagged with: pymongo
tagged with: dataframe
type: Question

dictionary
tags question: http://stackoverflow.com/q/48029707
tags question: http://stackoverflow.com/q/48034534
tags question: http://stackoverflow.com/q/48044680
tags question: http://stackoverflow.com/q/48069178
tags question: http://stackoverflow.com/q/48155106
tags question: http://stackoverflow.com/q/48104031
tags question: http://stackoverflow.com/q/48131718
tags question: http://stackoverflow.com/q/48115295
tags question: http://stackoverflow.com/q/48143870
tags question: http://stackoverflow.com/q/48067021
tags question: http://stackoverflow.com/q/48037224
tags question: http://stackoverflow.com/q/48094990
tags question: http://stackoverflow.com/q/48017281
tags question: http://stackoverflow.com/q/48135843
tags question: http://stackoverflow.com/q/48086081
tags question: http://stackoverflow.com/q/48069596
tags question: http://stackoverflow.com/q/48022202
tags question: http://stackoverflow.com/q/48069602
tags question: http://stackoverflow.com/q/48020102
tags question: http://stackoverflow.com/q/48024460
tags question: http://stackoverflow.com/q/48071023
tags question: http://stackoverflow.com/q/48068700
tags question: http://stackoverflow.com/q/48155038
tags question: http://stackoverflow.com/q/48023356
tags question: http://stackoverflow.com/q/48060582
tags question: http://stackoverflow.com/q/48091943
tags question: http://stackoverflow.com/q/48125788
tags question: http://stackoverflow.com/q/48160071
tags question: http://stackoverflow.com/q/48017878
tags question: http://stackoverflow.com/q/48152870
tags question: http://stackoverflow.com/q/48123253
tags question: http://stackoverflow.com/q/48071406
tags question: http://stackoverflow.com/q/48118602
tags question: http://stackoverflow.com/q/48110167
tags question: http://stackoverflow.com/q/48166183
tags question: http://stackoverflow.com/q/48131837
tags question: http://stackoverflow.com/q/48081435
tags question: http://stackoverflow.com/q/48073528
tags question: http://stackoverflow.com/q/48138978
tags question: http://stackoverflow.com/q/48130929
tags question: http://stackoverflow.com/q/48047711
tags question: http://stackoverflow.com/q/48015875
tags question: http://stackoverflow.com/q/48028758
tags question: http://stackoverflow.com/q/48077115
tags question: http://stackoverflow.com/q/48098631
tags question: http://stackoverflow.com/q/48044108
tags question: http://stackoverflow.com/q/48135593
tags question: http://stackoverflow.com/q/48156839
tags question: http://stackoverflow.com/q/48117272
tags question: http://stackoverflow.com/q/48027727
tag name: dictionary
tags question: http://stackoverflow.com/q/48106658
tags question: http://stackoverflow.com/q/48095926
tags question: http://stackoverflow.com/q/48039581
tags question: http://stackoverflow.com/q/48132843
tags question: http://stackoverflow.com/q/48043489
tags question: http://stackoverflow.com/q/48099832
tags question: http://stackoverflow.com/q/48094687
tags question: http://stackoverflow.com/q/48087184
tags question: http://stackoverflow.com/q/48144727
tags question: http://stackoverflow.com/q/48083981
tags question: http://stackoverflow.com/q/48166852
tags question: http://stackoverflow.com/q/48080245
tags question: http://stackoverflow.com/q/48016160
tags question: http://stackoverflow.com/q/48157448
tags question: http://stackoverflow.com/q/48134314
tags question: http://stackoverflow.com/q/48046624
tags question: http://stackoverflow.com/q/48053512
tags question: http://stackoverflow.com/q/48107922
tags question: http://stackoverflow.com/q/48101278
tags question: http://stackoverflow.com/q/48089366
tags question: http://stackoverflow.com/q/48048727
tags question: http://stackoverflow.com/q/48037294
tags question: http://stackoverflow.com/q/48106721
tags question: http://stackoverflow.com/q/48138479
tags question: http://stackoverflow.com/q/48068546
tags question: http://stackoverflow.com/q/48145981
tags question: http://stackoverflow.com/q/48132333
tags question: http://stackoverflow.com/q/48054910
tags question: http://stackoverflow.com/q/48025758

http://stackoverflow.com/a/48117886
answers question: http://stackoverflow.com/q/48117508
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/83214570
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83214814
has comment: http://stackoverflow.com/comment/83261306
upvote count: 7
type: Answer
has comment: http://stackoverflow.com/comment/83264249
has comment: http://stackoverflow.com/comment/83214656
accepted answer of: http://stackoverflow.com/q/48117508
has body: Based on your description, how about: &gt;&gt;&gt; a = "cat is sleeping on the mat" &gt;&gt;&gt; b = "the cat is sleeping on the red mat in the living room" &gt;&gt;&gt; a = a.split(" ") &gt;&gt;&gt; score = 0.0 &gt;&gt;&gt; for word in a: #for every word in your string if word in b: #if it is in your bigger string increase score score += 1 &gt;&gt;&gt; score/len(a) #obtain percentage given total word number 1.0 In case it had a missing word for example: &gt;&gt;&gt; c = "the cat is not sleeping on the mat" &gt;&gt;&gt; c = c.split(" ") &gt;&gt;&gt; score = 0.0 &gt;&gt;&gt; for w in c: if w in b: score +=1 &gt;&gt;&gt; score/len(c) 0.875 Additionally, you can do as @roadrunner suggest and split b and save it as a set to speed up your performance with b = set(b.split(" ")). This will reduce that part complexity to O(1) and improve the overall algorithm to a O(n) complexity. Edit: You say you already tried some metrics like Cosine Similarity etc. However I suspect you may benefit from checking the Levenshtein Distance similarity, which I suspect could be of some use in this case as addition to the solutions provided.

http://stackoverflow.com/a/48101802
downvote count: 0
upvote count: 29
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/133271370
type: Answer
score: 29
accepted answer of: http://stackoverflow.com/q/48100173
answers question: http://stackoverflow.com/q/48100173
has body: Let's consider the case of MNIST data classification (10 classes), where for a test set of 10,000 samples we get the following confusion matrix cm (Numpy array): array([[ 963, 0, 0, 1, 0, 2, 11, 1, 2, 0], [ 0, 1119, 3, 2, 1, 0, 4, 1, 4, 1], [ 12, 3, 972, 9, 6, 0, 6, 9, 13, 2], [ 0, 0, 8, 975, 0, 2, 2, 10, 10, 3], [ 0, 2, 3, 0, 953, 0, 11, 2, 3, 8], [ 8, 1, 0, 21, 2, 818, 17, 2, 15, 8], [ 9, 3, 1, 1, 4, 2, 938, 0, 0, 0], [ 2, 7, 19, 2, 2, 0, 0, 975, 2, 19], [ 8, 5, 4, 8, 6, 4, 14, 11, 906, 8], [ 11, 7, 1, 12, 16, 1, 1, 6, 5, 949]]) In order to get the precision &amp; recall (per class), we need to compute the TP, FP, and FN per class. We don't need TN, but we will compute it, too, as it will help us for our sanity check. The True Positives are simply the diagonal elements: # numpy should have already been imported as np TP = np.diag(cm) TP # array([ 963, 1119, 972, 975, 953, 818, 938, 975, 906, 949]) The False Positives are the sum of the respective column, minus the diagonal element (i.e. the TP element): FP = np.sum(cm, axis=0) - TP FP # array([50, 28, 39, 56, 37, 11, 66, 42, 54, 49]) Similarly, the False Negatives are the sum of the respective row, minus the diagonal (i.e. TP) element: FN = np.sum(cm, axis=1) - TP FN # array([17, 16, 60, 35, 29, 74, 20, 53, 68, 60]) Now, the True Negatives are a little trickier; let's first think what exactly a True Negative means, with respect to, say class 0: it means all the samples that have been correctly identified as not being 0. So, essentially what we should do is remove the corresponding row &amp; column from the confusion matrix, and then sum up all the remaining elements: num_classes = 10 TN = [] for i in range(num_classes): temp = np.delete(cm, i, 0) # delete ith row temp = np.delete(temp, i, 1) # delete ith column TN.append(sum(sum(temp))) TN # [8970, 8837, 8929, 8934, 8981, 9097, 8976, 8930, 8972, 8942] Let's make a sanity check: for each class, the sum of TP, FP, FN, and TN must be equal to the size of our test set…

http://stackoverflow.com/comment/83287042
comment on: http://stackoverflow.com/q/48154011
score: 0
type: Comment
type: QuestionComment
has text: what extension did you use to save that `some_path` image? Your save() call doesn't seem to specify one

http://stackoverflow.com/a/48453823
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: The problem got solved by updating to the latest version of ChromeDriver 2.35 https://chromedriver.storage.googleapis.com/index.html?path=2.35/
accepted answer of: http://stackoverflow.com/q/48028782
answers question: http://stackoverflow.com/q/48028782
type: AcceptedAnswer

http://stackoverflow.com/a/48359616
upvote count: 3
type: AcceptedAnswer
has body: I am currently using Python 3 and I can share the way I use Avro Phonetic. I am using modified python 3 compatible "pyAvroPhonetic" library locally with my scripts. You can get the structure at - "https://github.com/improlabs/Banglish-Sentiment-Analysis/tree/master/python3"
type: Answer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/48081663
answers question: http://stackoverflow.com/q/48081663

http://stackoverflow.com/comment/83439335
type: QuestionComment
score: 0
has text: I think you are getting a timeout from the example code because the `event.json` in that repo appears to be invalid (at least from my experience with SAM). I wrote [this](https://github.com/NZenitram/s3-lambda-html-parser/blob/master/event.json) last week, and I use it today. It works, and is written in python. I use `sam local invoke "S3" --event event.json` to initialize the docker env, and run it another window again to trigger the event. The `event.json` in my case triggers a real event on the bucket I have configured.
comment on: http://stackoverflow.com/q/48104577
type: Comment

http://stackoverflow.com/a/48124233
has body: Change your code like this: file = open('topology_list.txt','r') topology_list = file.readlines() print topology_list for i in topology_list: print "Entered For\n" print i print topology_list When you call file.readlines() the file pointer will reach the end of the file. For further calls of the same, the return value will be an empty list.
downvote count: 0
answers question: http://stackoverflow.com/q/48124206
upvote count: 3
type: Answer
score: 3

win32gui
type: Tag
tag name: win32gui
tags question: http://stackoverflow.com/q/48129124
tags question: http://stackoverflow.com/q/48092655

http://stackoverflow.com/comment/83295483
type: QuestionComment
comment on: http://stackoverflow.com/q/48158028
score: 0
has text: What exactly is the issue?
type: Comment

http://stackoverflow.com/q/48018680
tagged with: python-internals
has body: When I try to update a set while iterating over its elements, what should be its behavior? I tried it over various scenarios and it does not iterate over elements added after iteration is started and also the elements removed during iteration. If I remove and put back any element during iteration, that element is being considered. What's the exact behavior and how does it work? This prints all the permutations of a string: def permutations(s): ans = [] def helper(created, remaining): if len(created) == len(s): ans.append(''.join(created)) return for ch in remaining: remaining.remove(ch) created.append(ch) helper(created, remaining) remaining.add(ch) created.pop() helper([], set(s)) return ans Here the behavior is unpredictable, sometimes e is printed while sometimes it's not: ab = set(['b','c','d']) x = True for ch in ab: if x: ab.remove('c') ab.add('e') x = False print(ch) Here I always see 'c' only once. Even when first character is 'c': ab = set(['b','c','d']) x = True for ch in ab: if x: ab.remove('c') ab.add('c') x = False print(ch) And an alternate way to achieve the same objective of the above function: def permwdups(s): ans = [] def helper(created, remaining): if len(created) == len(s): ans.append(''.join(created)) return for ch in remaining: if (remaining[ch]&lt;=0): continue remaining[ch] -=1 created.append(ch) helper(created, remaining) remaining[ch] +=1 created.pop() counts = {} for i in range(len(s)): if s[i] not in counts: counts[s[i]] = 1 else: counts[s[i]]+= 1 helper([], counts) print(len(set(ans))) return ans
has comment: http://stackoverflow.com/comment/83007004
tagged with: python
has comment: http://stackoverflow.com/comment/83006377
upvote count: 13
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48129438
has title: Updating a set while iterating over its elements
has comment: http://stackoverflow.com/comment/83007218
tagged with: set
has comment: http://stackoverflow.com/comment/83006876
score: 13
has comment: http://stackoverflow.com/comment/83007020
has comment: http://stackoverflow.com/comment/83006948
accepted answer: http://stackoverflow.com/a/48129438
has comment: http://stackoverflow.com/comment/83008824
has comment: http://stackoverflow.com/comment/83261553
type: Question
has comment: http://stackoverflow.com/comment/83008910
has comment: http://stackoverflow.com/comment/83006806
has comment: http://stackoverflow.com/comment/83007057
has comment: http://stackoverflow.com/comment/83006601
linked to: http://stackoverflow.com/q/15175732
has comment: http://stackoverflow.com/comment/83174435
answer count: 1
downvote count: 0
favorite count: 0
tagged with: iteration
has comment: http://stackoverflow.com/comment/83006919
has comment: http://stackoverflow.com/comment/83006537

http://stackoverflow.com/comment/83302170
score: 0
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ That would be explaining specifically the implementation for `min`, `max`, `remove`, and `append`, which I believe is out of scope of the question.
type: Comment
comment on: http://stackoverflow.com/a/48161349

http://stackoverflow.com/a/48157412
downvote count: 1
upvote count: 0
score: -1
has body: Make sure you have Visual Studio installed with C++ packages (C++11 library). Also state exactly the content of Output log file.
answers question: http://stackoverflow.com/q/48156814
type: Answer

http://stackoverflow.com/comment/83326362
score: 0
has text: @NimishBansal there is a possibility that words might repeat.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48173305

http://stackoverflow.com/comment/83242172
type: Comment
has text: In the linecache.getline was my input file and the fileinput.input was my second file, im also trying to count how many times the first line appears in my second file
comment on: http://stackoverflow.com/a/48107788
type: AnswerComment
score: 0

http://stackoverflow.com/a/48043807
has comment: http://stackoverflow.com/comment/83059011
downvote count: 1
type: AcceptedAnswer
score: 1
has comment: http://stackoverflow.com/comment/83064761
has body: I assume that you want to look for the accuracy and loss of your model: model.compile(...) model.fit(...) eval_loss, eval_accuracy = model.evaluate(test_set, test_set, batch_size=batch_size, verbose=1) print("Accuracy: {:.2f}%".format(eval_accuracy * 100)) print("Loss: {}".format(eval_loss)) You can even plot a diagram to see the loss and accuracy during training: import matplotlib.pyplot as plt history = model.fit(...) summarize history for accuracy plt.figure(1) plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() # summarize history for loss plt.figure(1) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() EDIT import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame(columns=['Series', 'Scale Signal']) history = model.fit(...) predicted = model.predict(test_input) df_val_loss = pd.DataFrame(history.history['val_loss']) df_val_loss.plot() df_predicted = pd.DataFrame(predicted).T df_predicted.columns = ['Predicted'] df_result = pd.concat([df, df_predicted], ignore_index=True) df_result.plot() plt.show() The above script gets and plot predicted data and the validation loss. I don't work with time series too often so I can't give you any advice from my experience but here are a few good links that I hope can help you out: Evaluating forecast accuracy Time Series Forecasting Performance Measures With Python How to best evaluate a time series prediction algorithm?
type: Answer
answers question: http://stackoverflow.com/q/48042951
accepted answer of: http://stackoverflow.com/q/48042951
upvote count: 2

http://stackoverflow.com/comment/83077955
type: AnswerComment
has text: that's indeed very easy - thanks. I included the code in an edit
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48038220

http://stackoverflow.com/a/48057816
has comment: http://stackoverflow.com/comment/83088020
has comment: http://stackoverflow.com/comment/83088067
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48057694
type: Answer
answers question: http://stackoverflow.com/q/48057694
score: 3
has body: You would have to handle the special case somehow. One way is use max and avoid using the negative indexing: a[:max(1, len(a) - 1)] You can also use short-circuiting: a[:-1] or a[:]
downvote count: 1
has comment: http://stackoverflow.com/comment/83087974

http://stackoverflow.com/q/48061280
has body: I want to make a Tribonacci sequence. (Every new item is a summation of previous three items from that list.) But it shows list index out of range error whenever I use a while/for loop. Can anybody figure out what is wrong with this code? def tribonacci(signature, n): count = 0 newlist = [] while (len(newlist)&lt;=n): newitem = signature[count]+signature[count+1]+signature[count+2] newlist.append(newitem) count = count+1 print signature + newlist tribonacci([1,1,1], 5) In this above code, my expected output is [1,1,1,3,5,9,17,31] Traceback (most recent call last): File "C:\Users\Vasanth\Desktop\sample.py", line 9, in &lt;module&gt; tribonacci([1,1,1], 5) File "C:\Users\Vasanth\Desktop\sample.py", line 5, in tribonacci newitem = signature[count]+signature[count+1]+signature[count+2] IndexError: list index out of range
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83095119
has answer: http://stackoverflow.com/a/48061815
has answer: http://stackoverflow.com/a/48061420
accepted answer: http://stackoverflow.com/a/48061444
has comment: http://stackoverflow.com/comment/83095242
has comment: http://stackoverflow.com/comment/83095074
type: Question
score: 0
tagged with: concatenation
has answer: http://stackoverflow.com/a/48061444
has answer: http://stackoverflow.com/a/48061428
has comment: http://stackoverflow.com/comment/83095121
has comment: http://stackoverflow.com/comment/83095092
has answer: http://stackoverflow.com/a/48061578
has comment: http://stackoverflow.com/comment/83095086
answer count: 6
has answer: http://stackoverflow.com/a/48061726
possible better answer: http://stackoverflow.com/a/48061428
tagged with: indexoutofrangeexception
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/83095156
has comment: http://stackoverflow.com/comment/83095530
has title: Python: List index out of range inside while/for loop
has comment: http://stackoverflow.com/comment/83095096

http://stackoverflow.com/a/48142541
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/83263202
score: 1
answers question: http://stackoverflow.com/q/48142102
has comment: http://stackoverflow.com/comment/83263326
accepted answer of: http://stackoverflow.com/q/48142102
has body: You can do it by giving the lambda each Button an argument with a default value. There's no need for any extra for loops doing it this way (it's done in the one that creates the Buttons). How to do that is shown below in the spot with the # CHANGED comment. The rest of the code in each lambda function defined each re-configures the text option of the Label named lab_1 by calling its configure() method and passing it the current contents of the text option with the symbol of the associated Button appended to it. ... # Iterating through my list to get a set of buttons row = 0 for i in calculator_layout: col = 0 for a in i: key_press = tk.Button(box_1, text=a[0]) key_press.grid(row=row, column=col, ipadx=10, ipady=8, sticky='we') key_press.configure(background='#545454', fg='white', font=('Computer Modern', 10), activebackground='red', state='normal', # CHANGED. command=lambda sym=str(a[0]): lab_1.configure(text=lab_1.cget('text')+sym)) col += a[1] row += 1 root.mainloop()
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48064415
downvote count: 0
type: UnansweredQuestion
tagged with: regression
has comment: http://stackoverflow.com/comment/83124387
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/83164997
score: 1
type: Question
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/49345401
favorite count: 0
has comment: http://stackoverflow.com/comment/83101988
has title: Getting polynomial regression to overfit with TensorFlow
tagged with: python
has body: The Sklearn documentation contains an example of a polynomial regression which beautifully illustrates the idea of overfitting (link). The third plot shows a 15th order polynomial that overfits the simulated data. I replicated this model in TensorFlow, but I cannot get it to overfit. Even when tuning the learning rate and the numbers of learning epochs, I cannot get the model to overfit. What am I missing? import tensorflow as tf import numpy as np import matplotlib.pyplot as plt def true_fun(X): return np.cos(1.5 * np.pi * X) # Generate dataset n_samples = 30 np.random.seed(0) x_train = np.sort(np.random.rand(n_samples)) # Draw from uniform distribution y_train = true_fun(x_train) + np.random.randn(n_samples) * 0.1 x_test = np.linspace(0, 1, 100) y_true = true_fun(x_test) # Helper function def run_dir(base_dir, dirname='run'): "Number log directories incrementally" import os import re pattern = re.compile(dirname+'_(\d+)') try: previous_runs = os.listdir(base_dir) except FileNotFoundError: previous_runs = [] run_number = 0 for name in previous_runs: match = pattern.search(name) if match: number = int(match.group(1)) if number &gt; run_number: run_number = number run_number += 1 logdir = os.path.join(base_dir, dirname + '_%02d' % run_number) return(logdir) # Define the polynomial model def model(X, w): """Polynomial model param X: data param y: coeficients in the polynomial regression returns: Polynomial function Y(X, w) """ terms = [] for i in range(int(w.shape[0])): term = tf.multiply(w[i], tf.pow(X, i)) terms.append(term) return(tf.add_n(terms)) # Create the computation graph order = 15 tf.reset_default_graph() X = tf.placeholder("float") Y = tf.placeholder("float") w = tf.Variable([0.]*order, name="parameters") lambda_reg = tf.placeholder('float', shape=[]) learning_rate_ph = tf.placeholder('float', shape=[]) y_model = model(X, w) loss = tf.div(tf.reduce_mean(tf.square(Y-y_model)), 2) # Square error loss_rg = tf.multiply(lambda_reg, tf.reduce_sum(tf.square(w))) …
has comment: http://stackoverflow.com/comment/83136458

http://stackoverflow.com/q/48106692
has answer: http://stackoverflow.com/a/48121774
type: Question
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/83218615
answer count: 1
has body: I'm not entirely sure if this makes any sense, but since it's viewable in the app, shouldn't there be an endpoint for the announcement channel setting? This isn't a piece of code that isn't working, it's a lacking feature. Also, it's apparently called "new member message channel"...
accepted answer: http://stackoverflow.com/a/48121774
tagged with: python
tagged with: discord
favorite count: 0
has comment: http://stackoverflow.com/comment/83189535
score: -4
has comment: http://stackoverflow.com/comment/83218715
type: AnsweredQuestion
tagged with: discord.py
has title: find server's "announcements" channel

http://stackoverflow.com/a/48065679
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48063266
type: Answer
answers question: http://stackoverflow.com/q/48063266
score: 0
has body: Reinstallation from scratch fixed the issue, there was some conflict of versions in the installed packages.

http://stackoverflow.com/q/48166766
tagged with: python-2.7
score: 0
tagged with: python
has body: I'm a python beginner and I am attempting to write a function which computes the nearest neighbours of a lattice point, and am recieving the following error: lattice[x, (y - 1) % N] + lattice[x, (y + 1) % N] TypeError: 'function' object has no attribute 'getitem' Any solutions I've found online seem to be to do with passing a function instead of its results, but I can't see how that is happening here. Here is my code: def lattice(N): lattice = np.random.rand(N,N) lattice = np.where(lattice &lt;= 0.5, 1,-1) def nearestneighbours(lattice, x, y): return lattice[(x - 1) % N, y] + lattice[(x + 1) % N, y] + \ lattice[x, (y - 1) % N] + lattice[x, (y + 1) % N]
favorite count: 0
has comment: http://stackoverflow.com/comment/83312929
upvote count: 2
accepted answer: http://stackoverflow.com/a/48166998
downvote count: 2
has comment: http://stackoverflow.com/comment/83312713
has title: Index in function causing error with function has no attribute getitim
type: AnsweredQuestion
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/48166998

http://stackoverflow.com/a/48074925
has body: You are aware of how Unicode is broken into blocks, and how each block represents a contiguous range of code-points? IE, there's a much more efficient solution than a regular expression. There is a single code block for Hangul Jamo, with additional characters in the CJK block, a compatability block, Hangul syllables, etc. The most efficient way is to check if each character is within the acceptable range, using if/then statements. You could almost certainly speed this up using a C-extension. For example, if I were just checking the Hangul block (insufficient, but merely a simple starting place), I would check each character in a string with the following code: def is_hangul_character(char): '''Check if character is in the Hangul Jamo block''' value = ord(char) return value &gt;= 4352 and value &lt;= 4607 def is_hangul(string): '''Check if all characters are in the Hangul Jamo block''' return all(is_hangul_character(i) for i in string) It would be easy to extend this for the 8 or so blocks that contain Hangul characters. No tables lookups, no regex compilation. Just fast range checks based on the block of the Unicode character. In C, this would be very easy as well (if you would like a significant performance boost, to match a fully-optimized library with little work): // Return 0 if a character is in Hangul Jamo block, -1 otherwise int is_hangul_character(char32_t c) { if (c &gt;= 4352 &amp;&amp; c &lt;= 4607) { return 0; } return -1; } // Return 0 if all characters are in Hangul Jamo block, -1 otherwise int is_hangul(const char32_t* string, size_t length) { size_t i; for (i = 0; i &lt; length; ++i) { if (is_hangul_character(string[i]) &lt; 0) { return -1; } } return 0; } Edit A cursory glance at the CPython implementation shows CPython uses this exact approach for the unicodedata module. IE, it's efficient despite the relative ease to implement it on your own. It is still worth implementing, since you don't have to allocate any intermediate string, or use superfluo…
type: AcceptedAnswer
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/83125413
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48074764
answers question: http://stackoverflow.com/q/48074764
has comment: http://stackoverflow.com/comment/83125731
score: 5

http://stackoverflow.com/comment/83079654
has text: Thank you. Makes sense. Maybe you'll know this one too. Why when I want to install one single module in the environment and enter 'conda install -c anaconda pil' so many other modules get installed? 4 modules + Tensorflow being installed now just from entering that one line. EDIT: Now 15 other packages loading.
type: AnswerComment
comment on: http://stackoverflow.com/a/48051977
score: 0
type: Comment

http://stackoverflow.com/comment/83241145
type: Comment
has text: Ah, should have been more specific. I want to pickle date in Python 2.7
type: AnswerComment
comment on: http://stackoverflow.com/a/48127571
score: 0

http://stackoverflow.com/q/48157353
has comment: http://stackoverflow.com/comment/83294117
has comment: http://stackoverflow.com/comment/83294018
has body: While clearing some values from the global variable of type list via list.remove(value) function, I get an error "ValueError: list.remove(x): x not in list" My class definition looks like this: class Deck(object): global_l_init = ['2h','2d','2s','2c','3h','3d','3s','3c','4h','4d','4s','4c', '5h','5d','5s','5c','6h','6d','6s','6c','7h','7d','7s','7c', '8h','8d','8s','8c','9h','9d','9s','9c','10h','10d','10s','10c', 'Jh','Jd','Js','Jc','Qh','Qd','Qs','Qc','Kh','Kd','Ks','Kc', 'Ah','Ad','As','Ac'] #Cards' value d={'2h':2,'2d':2,'2s':2,'2c':2,'3h':3,'3d':3,'3s':3,'3c':3, '4h':4,'4d':4,'4s':4,'4c':4,'5h':5,'5d':5,'5s':5,'5c':5, '6h':6,'6d':6,'6s':6,'6c':6,'7h':7,'7d':7,'7s':7,'7c':7, '8h':8,'8d':8,'8s':8,'8c':8,'9h':9,'9d':9,'9s':9,'9c':9, '10h':10,'10d':10,'10s':10,'10c':10,'Jh':10,'Jd':10,'Js':10, 'Jc':10,'Qh':10,'Qd':10,'Qs':10,'Qc':10,'Kh':10,'Kd':10,'Ks':10,'Kc':10, 'Ah':10,'Ad':10,'As':10,'Ac':10,'Ah':1,'Ad':1,'As':1,'Ac':1} def __init__(self,plr_cur_value): self.plr_cur_value = plr_cur_value def deck_change(self): self.global_l_init.remove(self.plr_cur_value) What I do to check how it works, is: D1=Deck(['2h','Jh']) D1.deck_change() The error is as follows: ValueError Traceback (most recent call last) &lt;ipython-input-534-6f04c0ca0556&gt; in &lt;module&gt;() 1 D1=Deck(['2h','Jh']) ----&gt; 2 D1.deck_change() &lt;ipython-input-528-7691239e1d5b&gt; in deck_change(self) 54 55 def deck_change(self): ---&gt; 56 self.global_l_init.remove(self.plr_cur_value) 57 ValueError: list.remove(x): x not in list I am new to python. Maybe the question is stupid enough. But still cannot figure out why global_l_init defined as class variable is not accessed/changed?... Appreciate your answers.
accepted answer: http://stackoverflow.com/a/48176171
answer count: 1
has comment: http://stackoverflow.com/comment/83294158
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/83294061
has comment: http://stackoverflow.com/comment/83294080
tagged with: python
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/83294135
tagged with: items
has answer: http://stackoverflow.com/a/48176171
downvote count: 1
has comment: http://stackoverflow.com/comment/83331872
type: Question
has comment: http://stackoverflow.com/comment/83294142
upvote count: 0
has title: In python while using list.remove(value_of_the_list) a ValueError is thrown
has comment: http://stackoverflow.com/comment/83316866
has comment: http://stackoverflow.com/comment/83294155

http://stackoverflow.com/q/48063376
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: django
type: Question
has body: I have an abstract model from which a couple of my main models are inherited. Main difficulty in this case is that I have a need in reference to the same model, like a ForeignKey to self. I have read that the ForeignKey is not possible in abstract models and GenericForeignKey can help, however I can`t really make it work. As I understand structure should be something like following: class BaseModel(models.Model): versions = GenericRelation('self') date_created = models.DateTimeField(default=datetime.datetime.now) is_deleted = models.BooleanField(default=False) content_type = models.ForeignKey(ContentType, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) content_object = GenericForeignKey('content_type', 'object_id') class FirstModel(BaseModel): some_fields... class AnotherModel(BaseModel): another_fields... But with this approach I get an error: &gt;&gt;&gt; item1 = FirstModel.objects.get(id=1) &gt;&gt;&gt; item2 = FirstModel.objects.get(id=2) &gt;&gt;&gt; item2.content_object = item1 Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/home/michael/.virtualenvs/diagspecgen/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py", line 245, in __set__ ct = self.get_content_type(obj=value) File "/home/michael/.virtualenvs/diagspecgen/lib/python3.6/site-packages/django/contrib/contenttypes/fields.py", line 163, in get_content_type return ContentType.objects.db_manager(obj._state.db).get_for_model( AttributeError: 'ReverseGenericRelatedObjectsDescriptor' object has no attribute '_state' Is that I am trying to reach is absolutely impossible and the only solution is to explicitly create needed fields in existing models?
has comment: http://stackoverflow.com/comment/83099874
upvote count: 1
linked to: http://stackoverflow.com/q/367461
answer count: 1
has comment: http://stackoverflow.com/comment/83100104
has title: Django refering to same model instances in Abstract Model
favorite count: 0
has answer: http://stackoverflow.com/a/48064085
accepted answer: http://stackoverflow.com/a/48064085
tagged with: django-generic-relations
tagged with: python

http://stackoverflow.com/a/48042463
downvote count: 2
score: 9
answers question: http://stackoverflow.com/q/48042132
upvote count: 11
has body: Is it ok to change settings? Short answer: No, unless you do it during the startup. Long answer: Django docs are correct, you should not modify settings at runtime. This means, no settings modifications after the app has been started, like changing configuration in views.py, serializers.py, models.py or other modules you add during the development. But it is ok to modify settings if they depend on local variables if you do it at startup and you are fully aware of what happens. Can you modify settings while testing? Yes, if you think you need it. Feel free to rely on override_settings to change settings value for testing purposes in the unit tests, see example of usage here Also, everything that this decorator does - is overriding settings with provided values and restoring settings value after test has passed (decorated function executed). Why Django does modify them while testing the code. From what I see, they change settings only for testing purposes and the only thing they do - adding a local host to allowed host so they can test the code using a local domain. Examples like that seem pretty reasonable for me as change is done only once and during unit tests set up. Imagine having overrride_settings call every time, that would be monstrous. General recommendation. Try not to, there is no need to modify settings and if there is - think about it, maybe settings is not the right place for a mutable setting? If you want to modify settings at runtime - please be aware that settings might be cached somewhere, copied and accessed all over the place - this is a plenty of space for new bugs. There is nothing bad in it, except having an unexpected behavior of the system due to an old/new value of the modified setting. Hope this makes sense.
type: Answer

http://stackoverflow.com/q/48054822
has comment: http://stackoverflow.com/comment/83082072
answer count: 2
upvote count: 1
linked to: http://stackoverflow.com/q/5598524
favorite count: 0
tagged with: file-io
has body: i want to delete specific lines in this Html file. I want to look where the String STARTDELETE is and remove from there +1 to the String ENDDELETE -1 i have marked the lines to delete with 'xxx' for better understanding. How can i do it with python? Bootstrap Example Image Gallery xxx xxx xxx xxx xxx xxx Test xxx xxx xxx xxx
tagged with: python
has title: python remove specific lines from file
tagged with: python-3.x
tagged with: list
has answer: http://stackoverflow.com/a/48054886
downvote count: 0
has answer: http://stackoverflow.com/a/48054997
possible better answer: http://stackoverflow.com/a/48054886
accepted answer: http://stackoverflow.com/a/48054997
type: AnsweredQuestion
score: 1
type: Question

http://stackoverflow.com/comment/83297086
has text: The problem here is it's deleting all of the contents of the output file when it should be saving after lets say i run the code 3 times, 42 should appear in the output file 3 times, which should be printed in the python shell
comment on: http://stackoverflow.com/a/48158647
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48169602
has body: I am trying to pass Java arraylist to Python function. I am getting below error SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/GEO_DM] threw exception [Cant instantiate class: com.ppts.bean.TriggerLawSocietyServiceBean.] with root cause java.lang.IllegalArgumentException: 'ofArrayType' must be compatible with existing array type of [Lorg.python.core.PyObject; see java.lang.Class.getName(). Please see my java code below: PythonInterpreter interpreter=new PythonInterpreter(); PyList pyList=new PyList(new ArrayList&lt;&gt;()); interpreter.execfile(getClass().getResourceAsStream("/com/ppts/propertiesfiles/sample_return_script.py")); PyObject function=interpreter.get("returnSample"); PyObject result=function.__call__(new PyInteger(1),pyList,new PyDictionary()); progress=(int) result.__tojava__(Integer.class); Please see my python code: def returnSample(var, list, dict): print(var) b=1 flag=True print(list[0]) print(dict.keys()) return b Please dont see the logics done in python. Just help me to pass the Arraylist to that python function
tagged with: python
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: java
has comment: http://stackoverflow.com/comment/83327518
has title: How to pass Java List to Python function using Jython?
type: Question
has comment: http://stackoverflow.com/comment/83340107
has comment: http://stackoverflow.com/comment/83361951
upvote count: 1
tagged with: jython
favorite count: 0

http://stackoverflow.com/comment/83072290
type: AnswerComment
type: Comment
has text: Have you put the rigth addons path in the config file? Keep in mind that you shoud use the `odoo-bin` file instead of `odoo.py` in the 11 version. Anyway I have tried with the 8th version. I will try with the 11 version later if I have time
score: 2
comment on: http://stackoverflow.com/a/48033498

http://stackoverflow.com/comment/83240166
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48126376
has text: Thank you so much for the tips! I'm really excited to work on style and learn more about how to use the most neat and compact code I can.

http://stackoverflow.com/q/48170811
has comment: http://stackoverflow.com/comment/83322132
has answer: http://stackoverflow.com/a/48171827
upvote count: 1
has comment: http://stackoverflow.com/comment/83322908
type: AnsweredQuestion
tagged with: conditional-statements
has comment: http://stackoverflow.com/comment/83321968
has comment: http://stackoverflow.com/comment/83322288
accepted answer: http://stackoverflow.com/a/48171827
has title: Pandas: Parsing with two conditions issue
type: Question
answer count: 2
has body: I have a dataframe called transcripts and a numpy array called genes. genes is simply the unique values of the geneID column of transcripts. For each value of genes I would like to find the longest transcript (column transcriptLength in transcripts), and remove all others from the transcripts dataframe. I thought I would use the code below and then loop through genes. #subset transcripts, leaving only rows with id of genes[20000] x=transcripts.loc[(transcripts['geneID'] == genes[20000])].copy() #Find longest transcript y = x.transcriptLength.max() #subset transcripts df to remove all transcripts that are shorter for that gene z=transcripts.loc[(transcripts['geneID'] != genes[20000]) &amp; (transcripts['transcriptLength'] != y)].copy() However, for some reason this code removes all transcripts with that geneID. I have subsetted before like this (and looked at other similiar stack questions) and my code appears to be correct so I cannot fathom what the issue is. Is there something missing here? FYI geneID column is strings, whilst transcriptLength column is ints. Here is the first rows of transcripts: geneID transcriptID transcriptLength 0 ENSPTRG00000042638 ENSPTRT00000076395 71 1 ENSPTRG00000042646 ENSPTRT00000076407 949 2 ENSPTRG00000042654 ENSPTRT00000076381 69 3 ENSPTRG00000042645 ENSPTRT00000076409 1558 4 ENSPTRG00000042644 ENSPTRT00000076406 75 EDIT: Here is a toy example, where we are trying to find the longest transcript for gene g2 and remove any that are shorter: #Create dataframe (akin to transcripts above) d = {'transcriptID' : pd.Series(['t1', 't2', 't3', 't4'], index=['a', 'b', 'c', 'd']), 'geneID' : pd.Series(['g1', 'g2', 'g3', 'g2'], index=['a', 'b', 'c', 'd']), 'transcriptLength' : pd.Series([212, 715, 213, 984], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) #Subset df to include only values where geneID = g2 x=df.loc[(df['geneID'] == 'g2')].copy() #Find max transcriptLength y = x.transcriptLength.max() #Subset main df to remove all g2 values exc…
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48171893
tagged with: pandas
has answer: http://stackoverflow.com/a/48171893
tagged with: python
score: 1

http://stackoverflow.com/q/48031283
has title: Why is PHP7 so much faster than Python3 in executing this simple loop?
has answer: http://stackoverflow.com/a/53668276
downvote count: 0
has comment: http://stackoverflow.com/comment/83032930
favorite count: 0
answer count: 5
has comment: http://stackoverflow.com/comment/83032846
has comment: http://stackoverflow.com/comment/83032870
tagged with: python
has comment: http://stackoverflow.com/comment/83032883
has comment: http://stackoverflow.com/comment/83032942
has answer: http://stackoverflow.com/a/63722108
has body: As an extremely simple benchmark, I executed the below simple code on PHP 7.0.19-1 and Python 3.5.3 (command line) on the same Raspberry Pi 3 model B. Python's execution time was horrible in comparison to PHP's (74 seconds vs 1.4 seconds). Can anyone help me understand why the execution takes so much longer on Python? Is there something I'm doing wrong, or some optimizations/settings that would improve its performance to meet or exceed that of PHP? Or is Python just that much slower (surely not!)? Yes I saw this benchmark, which reports PHP 7 blazes past the other languages, but you'd think both would be fairly equally optimized when doing such a simple operation. Python executes the loop about twice as fast if a string assignment is substituted for the addition. But that's still 34 seconds vs about 1.1 sec. PHP7 code: &lt;?php function test($x) { $t1 = microtime(true); $a = 0; for($i = 0; $i &lt; $x; $i++) { $a++; } $t2 = microtime(true); echo "Time for $x was " . ($t2 - $t1) . "\n"; return $a; } echo test(100000); echo test(1000000); echo test(10000000); Results: Time for 100000 was 0.036377191543579 100000Time for 1000000 was 0.18501400947571 1000000Time for 10000000 was 1.3939099311829 Python3 code: import time def test(x): t1 = time.clock() a = 0 for i in range(x): a += 1 t2 = time.clock() print("Time for {} was {}".format(x, t2 - t1)) return x print(test(1000000)) print(test(10000000)) print(test(100000000)) Results: Time for 1000000 was 0.761641 1000000 Time for 10000000 was 7.427618000000001 10000000 Time for 100000000 was 74.320387 100000000 UPDATE: yes after @Amber pointed it out, I realize I totally PEBKAKed and the loop counters are an order of magnitude apart. Even so, the answers were really interesting so it was worth asking the question.
score: 15
has comment: http://stackoverflow.com/comment/83032888
has answer: http://stackoverflow.com/a/48031406
tagged with: php
has comment: http://stackoverflow.com/comment/83032928
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/92338545
tagged with: performance
has answer: http://stackoverflow.com/a/58842192
linked to: http://stackoverflow.com/q/6889747
has answer: http://stackoverflow.com/a/51158913
type: Question
upvote count: 15
possible better answer: http://stackoverflow.com/a/53668276
accepted answer: http://stackoverflow.com/a/48031406

http://stackoverflow.com/comment/83089869
has text: I think the answer is going to be to use a Windows API function, start by searching for how to do that from C/C++/.C#, then translate the result to python via ctypes
comment on: http://stackoverflow.com/q/48051283
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83063810
score: 0
type: QuestionComment
has text: If the messages are sent/received as a whole (e.i. you only see them after the other person hits enter) then its just a matter of using a queue to display them one after another. If you want real-time, then things are gonna get a lot more tricky.
type: Comment
comment on: http://stackoverflow.com/q/48046227

http://stackoverflow.com/comment/83292616
type: Comment
has text: I guess the list comp is a little more readable than using `list` and `map`, but IMHO `map` is ok here because you're calling `max`, a built-in function written in C. OTOH, using `map` or `filter` with a `lambda` is not so efficient because it involves an extra Python function call per iteration compared to using a list comp.
type: AnswerComment
comment on: http://stackoverflow.com/a/48156692
score: 1

http://stackoverflow.com/comment/83195575
type: Comment
has text: You **cannot** index dictionaries as they have no particular order. You can, however, *index a list in which the dictionary items have been cast into*. In your case, that would be `list(result.items())[0]` (or `list(result.values())[0]`). But, note, that there is no notion of **first** or **nth** item in a dictionary. So the above code **can produce different outputs for the same input**. You have been warned ;)
score: 3
comment on: http://stackoverflow.com/q/48110167
type: QuestionComment

http://stackoverflow.com/q/48120471
tagged with: pandas
favorite count: 0
possible better answer: http://stackoverflow.com/a/48120541
tagged with: python
has answer: http://stackoverflow.com/a/48120541
type: AnsweredQuestion
score: 3
downvote count: 0
has body: i'm trying to do something like this: d={'Month':['January','February','March','April'], 'Saves':[2000, 2100, 1900, 1500]} saves=pd.DataFrame(data=d) and turns like this: Month Saves 0 January 2000 1 February 2100 2 March 1900 3 April 1500 What i would like is to create a new column 'Spent' with the logic: if the value of the last month is more ->"Yes", else -> 'No', like: Month Saves Spent 0 January 2000 - 1 February 2100 No 2 March 1900 Yes 3 April 1500 Yes I have no idea how to do it, tried iterating in many ways, but it didn't work. Thanks!
type: Question
has title: Conditional values for column in pandas
answer count: 2
has answer: http://stackoverflow.com/a/48120531
accepted answer: http://stackoverflow.com/a/48120531
upvote count: 3

http://stackoverflow.com/q/48051810
has answer: http://stackoverflow.com/a/49325957
upvote count: 1
tagged with: python
tagged with: pyshp
tagged with: import
type: Question
answer count: 1
downvote count: 0
has title: importing a shapefile to python with pyshp
score: 1
has comment: http://stackoverflow.com/comment/83075908
favorite count: 0
tagged with: shapefile
has body: I'm trying to import the shapefile "Metropolin_31Jul_0921.shp" to python using the following code: import shapefile stat_area_df = shapefile.Reader("Metropolin_31Jul_0921.shp") but i keep getting this error: File "C:\Users\maya\Anaconda3\lib\site-packages\shapefile.py", line 291, in load raise ShapefileException("Unable to open %s.dbf or %s.shp." % (shapeName, shapeName) ) shapefile.ShapefileException: Unable to open Metropolin_31Jul_0921.dbf or Metropolin_31Jul_0921.shp. Does anyone know what it means? I tried adding the directory but it didn't help.
type: UnansweredQuestion

http://stackoverflow.com/comment/103967374
score: 1
has text: Please also try to explain your solution with some comments
type: AnswerComment
comment on: http://stackoverflow.com/a/58846374
type: Comment

http://stackoverflow.com/q/48019615
tagged with: hadoop
has comment: http://stackoverflow.com/comment/83084608
type: Question
tagged with: python
answer count: 0
score: 0
has body: Scenario: I have a python application which connects to hive database and extracts data, creates sub tables for processing data,drops temp tables etc.. 90% of the processing is done using hive queries which is essentially generated from python code and sends to hive server to execute. There is a minimum time spent on sending each query to hive server, and returning the status or data. I understand there are unavoidable scenarios where the data is in hive. Then there is processing time of the hive query. There are scenarios where It consumes lot of time to process each query when there are lot of queries to execute in a loop. Question : If we assume the data is like some 50k rows. Would it be much faster to fetch 50k rows to python itself(ofcourse the data transfer time is overhead here)- like into a list of tuples- and mimic the join/filter operations hive does and avoid the 10-50 queries run against hive? Would this be a better approach? Or should i look for hive query optimization techniques. I prefer hive queries as it is convenient to use.
has comment: http://stackoverflow.com/comment/83034699
tagged with: hive
has title: Hive query vs python list processing performance
type: UnansweredQuestion

http://stackoverflow.com/q/48015378
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/48019686
linked to: http://stackoverflow.com/q/39219767
answer count: 2
has answer: http://stackoverflow.com/a/48062299
has body: For the past few days I have been trying to get weather station data interpolated in a map for my country only. I do this as follows: Loading the data, I create a grid using interpolation Based on this grid I draw a contour and contourf image I then draw shapefiles for Germany, Belgium and France on top of the map in order to cover the irrelevant contour/contourf elements. I used this tutorial for that. Finally, I use an oceans shapefile (IHO Sea Areas; www.marineregions.org/downloads.php#iho) to plot as well in order to cover the North Sea. Using QGIS, I edited this oceans shapefile and removed everything except for the North Sea - given time constraints :) You would say that everything goes fine -- but for some reason parts of the country as well as the islands are interpreted as being water. I guess this is because these are distinct parts, all not connected to the main land (due to waters/rivers). Strangely enough, the edges are drawn, but they are not filled. I've tried and searched a lot but have no clue about how to fix this. I guess it is somewhere in the LineCollection because in QGIS the shapefile is correct (i.e. it recognizes no shape when clicking the islands etc., which is correct since it should only recognize a shape when clicking on the sea). I sincerely hope that you could help me point out where I'm wrong and how I can fix this! Thanks a lot! This is the map that I'm getting: https://i.sstatic.net/SKohA.png My code is as follows (and you can probably see that I'm very new to this kind of programming, I started yesterday :)): import numpy as np import matplotlib matplotlib.use('Agg') from scipy.interpolate import griddata from mpl_toolkits.basemap import Basemap, maskoceans import matplotlib.pyplot as plt from numpy.random import seed import shapefile as shp from matplotlib.collections import LineCollection from matplotlib import cm # Set figure size plt.figure(figsize=(15,15), dpi=80) # Define map bounds xMin, xMax = 2.5, 8.0 yMin, yMax = 50.6, 53…
has comment: http://stackoverflow.com/comment/83007536
score: 2
has title: Plotting shapefile using LineCollection shows all edges, but partially fills them
downvote count: 0
tagged with: matplotlib-basemap
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83010342
accepted answer: http://stackoverflow.com/a/48062299
type: AnsweredQuestion
upvote count: 2
type: Question
has answer: http://stackoverflow.com/a/48019686

http://stackoverflow.com/q/48158760
duplicate of: http://stackoverflow.com/q/38083990
accepted answer: http://stackoverflow.com/a/48160794
favorite count: 0
has title: Why do two different data processing ways in pyspark produce separate results?
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has body: I am trying to create a sample dataset off my current dataset. I try two different ways and they produce two separate results. Separate in a way each sampled row should be integer and string ([5,unprivate], [1,hiprivate]). The first way is giving me string and string for each row ([private,private], [unprivate, hiprivate]). The second way is giving me the correct output. Why are they producing two totally different datasets? dataset 5,unprivate 1,private 2,hiprivate ingest data from pyspark import SparkContext sc = SparkContext() INPUT = "./dataset" def parse_line(line): bits = line.split(",") return bits df = sc.textFile(INPUT).map(parse_line) 1st way - outputs something like [[u'unprivate', u'unprivate'], [u'unprivate', u'unprivate']] #1st way columns = df.first() new_df = None for i in range(0, len(columns)): column = df.sample(withReplacement=True, fraction=1.0).map(lambda row: row[i]).zipWithIndex().map(lambda e: (e[1], [e[0]])) if new_df is None: new_df = column else: new_df = new_df.join(column) new_df = new_df.map(lambda e: (e[0], e[1][0] + e[1][1])) new_df = new_df.map(lambda e: e[1]) print new_df.collect() 2nd way - outputs something like [(0, [u'5', u'unprivate']), (1, [u'1', u'unprivate']), (2, [u'2', u'private'])] #2nd way new_df = df.sample(withReplacement=True, fraction=1.0).map(lambda row: row[0]).zipWithIndex().map(lambda e: (e[1], [e[0]])) new_df2 = df.sample(withReplacement=True, fraction=1.0).map(lambda row: row[1]).zipWithIndex().map(lambda e: (e[1], [e[0]])) new_df = new_df.join(new_df2) new_df = new_df.map(lambda e: (e[0], e[1][0] + e[1][1])) print new_df.collect() I am trying to figure out the unisample function in page 62 http://info.mapr.com/rs/mapr/images/Getting_Started_With_Apache_Spark.pdf
type: Question
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/48160794
tagged with: pyspark
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83313780
linked to: http://stackoverflow.com/q/38083990
has comment: http://stackoverflow.com/comment/83334457
tagged with: apache-spark

http://stackoverflow.com/a/48051947
answers question: http://stackoverflow.com/q/48051891
score: 4
accepted answer of: http://stackoverflow.com/q/48051891
type: AcceptedAnswer
downvote count: 0
has body: Yes, in python 2 the division / is a intger division but in python 3 it is float. // is integer division in both 2 and 3. You can solve your problem by adding from __future__ import division
type: Answer
upvote count: 4

http://stackoverflow.com/comment/83075444
score: 2
type: AnswerComment
has text: Thanks! It's working now, but you should add 'widget=' before each widget parameter.
comment on: http://stackoverflow.com/a/48051451
type: Comment

http://stackoverflow.com/a/48105955
answers question: http://stackoverflow.com/q/48097742
has comment: http://stackoverflow.com/comment/84758178
has comment: http://stackoverflow.com/comment/84793839
has comment: http://stackoverflow.com/comment/98701124
downvote count: 1
has comment: http://stackoverflow.com/comment/84762153
has comment: http://stackoverflow.com/comment/84758253
has comment: http://stackoverflow.com/comment/84760086
has comment: http://stackoverflow.com/comment/134041233
accepted answer of: http://stackoverflow.com/q/48097742
has comment: http://stackoverflow.com/comment/98701104
has comment: http://stackoverflow.com/comment/84790227
has comment: http://stackoverflow.com/comment/98701191
has comment: http://stackoverflow.com/comment/98699931
type: AcceptedAnswer
upvote count: 48
score: 47
has comment: http://stackoverflow.com/comment/83634774
has comment: http://stackoverflow.com/comment/98700984
has body: Not really clear what kind of data structures you actually have. Also, all your expected results are False, so that's kind of hard to check. Assuming GeoSeries and GeoDataFrames, I would do this: from shapely.geometry import Point, Polygon import geopandas polys = geopandas.GeoSeries({ 'foo': Polygon([(5, 5), (5, 13), (13, 13), (13, 5)]), 'bar': Polygon([(10, 10), (10, 15), (15, 15), (15, 10)]), }) _pnts = [Point(3, 3), Point(8, 8), Point(11, 11)] pnts = geopandas.GeoDataFrame(geometry=_pnts, index=['A', 'B', 'C']) pnts = pnts.assign(**{key: pnts.within(geom) for key, geom in polys.items()}) print(pnts) And that gives me: geometry bar foo A POINT (3 3) False False B POINT (8 8) False True C POINT (11 11) True True
type: Answer
has comment: http://stackoverflow.com/comment/98701121
has comment: http://stackoverflow.com/comment/83617299

http://stackoverflow.com/comment/83042722
has text: It appears that the sample data you've shown here isn't representative of your actual data, since the values in question are already floats. Perhaps you have `int`s or `str`ings that you want to convert to `float`?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48036134

http://stackoverflow.com/q/48165097
has title: Docstring - Usage of parameter name and type of in python
answer count: 1
tagged with: docstring
score: 0
linked to: http://stackoverflow.com/q/9195455
tagged with: python
has comment: http://stackoverflow.com/comment/83309527
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83309932
has body: I've written some classes in Python and I have written docstrings for them like this: class DB: def execute_and_return(self, sql): """Execute the query and returns the result as a list of list Parameters ---------- sql: str Your query Returns ------- list"" If I want to access the docstring in another class I can simply call DB.execute_and_return.__doc__ and I get the string. However if I'm interesting to know the name of the parameters (in this case sql) and the type of data (in this case str) is there any built in functions for accessing that?
has answer: http://stackoverflow.com/a/48166038
type: Question

http://stackoverflow.com/comment/83289984
type: AnswerComment
has text: Ah, I see. I don't believe there is an equivalent of `2to3` for `six`. In these situations, as arduous as it might sound, I make sure that everything has unit tests, set the tests to run on both python 2 and 3 during CI, and then start inserting `six` where appropriate.
comment on: http://stackoverflow.com/a/48154499
score: 0
type: Comment

http://stackoverflow.com/comment/124224714
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48160723
type: Comment
has text: @kellpossible To answer your question - Yes, you don't need to download packages from `anaconda` and `conda-forge` too much any more these days. Keep in mind [conda](https://docs.conda.io/projects/conda/en/latest/index.html) is a package & environment management tool and is different from [Anaconda](https://www.anaconda.com/). It lets the user decide where to download packages from. I still use it to manage my environment, exactly like in Option 2 where all my dependencies are downloaded via `pip` but I am able give provide a name and python version to use for my environment.

http://stackoverflow.com/q/48173038
type: Question
tagged with: c#
has answer: http://stackoverflow.com/a/48258953
has title: is it possible to use cnn models trained in cntk python in c#?
upvote count: 2
answer count: 1
favorite count: 0
tagged with: python
tagged with: c++
score: 2
downvote count: 0
tagged with: cntk
type: UnansweredQuestion
has body: I want to use CNTK python to train a CNN model and then use the trained model when i am programming in c# or c++. Is it possible to use CNTK python trained model in C# or c++?

http://stackoverflow.com/a/48066456
answers question: http://stackoverflow.com/q/48055036
has comment: http://stackoverflow.com/comment/83114626
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48055036
type: Answer
has body: You need to scale and resize both the rubber-band and its container. Here is a demo based on your example: import sys from PyQt5 import QtCore, QtGui, QtWidgets class ResizableRubberBand(QtWidgets.QWidget): def __init__(self, parent=None): super(ResizableRubberBand, self).__init__(parent) self.setWindowFlags(QtCore.Qt.SubWindow) layout = QtWidgets.QHBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget( QtWidgets.QSizeGrip(self), 0, QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) layout.addWidget( QtWidgets.QSizeGrip(self), 0, QtCore.Qt.AlignRight | QtCore.Qt.AlignBottom) self._band = QtWidgets.QRubberBand( QtWidgets.QRubberBand.Rectangle, self) self._band.show() self.show() def resizeEvent(self, event): size = QtCore.QSize(3, 4) size.scale(self.size(), QtCore.Qt.KeepAspectRatio) self.resize(size) self._band.resize(self.size()) class Window(QtWidgets.QWidget): def __init__(self): super(Window, self).__init__() self.button = QtWidgets.QPushButton('Show Rubber Band') self.button.clicked.connect(self.handleButton) self.label = QtWidgets.QLabel() self.label.setScaledContents(True) self.label.setPixmap(QtGui.QPixmap('image.jpg')) layout = QtWidgets.QVBoxLayout(self) layout.addWidget(self.label) layout.addWidget(self.button) def handleButton(self): self.band = ResizableRubberBand(self.label) self.band.setGeometry(50, 50, 150, 300) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = Window() window.setGeometry(800, 100, 600, 500) window.show() sys.exit(app.exec_())
score: 1
upvote count: 1

http://stackoverflow.com/a/48105402
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83186723
downvote count: 0
has comment: http://stackoverflow.com/comment/83186757
type: Answer
accepted answer of: http://stackoverflow.com/q/48105256
has comment: http://stackoverflow.com/comment/83186814
answers question: http://stackoverflow.com/q/48105256
upvote count: 1
has body: Your should shrink the size that random.randint can choose from. Based on your application, I think it should be random.randint(0, len(unpicked)-1) Another thing is that in the following line unpicked = [x for x in numbers+picked if x not in picked] you don't need numbers+picked. Just put numbers would be enough because numbers always have from 0 to 99.

http://stackoverflow.com/q/48058412
type: Question
has title: How can str.translate from Python 2, only removing characters, be made to work in Python 3?
has comment: http://stackoverflow.com/comment/83089065
upvote count: 0
has comment: http://stackoverflow.com/comment/83089098
has comment: http://stackoverflow.com/comment/83089573
has answer: http://stackoverflow.com/a/48058555
has body: This is an assignment that needs to change the name of the file within a certain folder, however, it doesn't change the name after all. Can anyone help? import os def rename_files(): file_list = os.listdir(r"C:\Users\Downloads\prank") saved_path = os.getcwd() print("Current Working Directory is " +saved_path) os.chdir(r"C:\Users\Downloads\prank") for file_name in file_list: os.rename(file_name, file_name.translate(None, "0123456789")) os.chdir(saved_path) rename_files() result: Traceback (most recent call last): File "C:\Users\Downloads\prank\rename_files.py", line 10, in &lt;module&gt; rename_files() File "C:\Users\Downloads\prank\rename_files.py", line 8, in rename_files os.rename(file_name, file_name.translate(None, '0123456789')) TypeError: translate() takes exactly one argument (2 given) This code works in Python 2, but does not work in Python 3. How can it be made to work in Python 3.6, I only need to delete characters.
answer count: 1
score: -6
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83089241
duplicate of: http://stackoverflow.com/q/41708770
tagged with: python
downvote count: 6
duplicate of: http://stackoverflow.com/q/23175809

http://stackoverflow.com/q/48053139
has body: In my dataframe I have a column containing numbers, some positive, some negative. Example Amount 0 -500 1 659 3 -10 4 344 I want to turn all numbers Df['Amount'] into positive numbers. I thought about multiplying all numbers with *-1. But though this turns negative numbers positive, and also does the reverse. Is there a better way to do this?
has comment: http://stackoverflow.com/comment/83078506
has answer: http://stackoverflow.com/a/48053155
type: Question
linked to: http://stackoverflow.com/q/29077188
has answer: http://stackoverflow.com/a/48053180
possible better answer: http://stackoverflow.com/a/48053155
downvote count: 0
duplicate of: http://stackoverflow.com/q/29077188
accepted answer: http://stackoverflow.com/a/48053180
answer count: 3
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/48053158
has title: Pandas - Turning column of mixed positive / negative numbers to positive
favorite count: 0
upvote count: 11
has comment: http://stackoverflow.com/comment/83078486
score: 11
type: AnsweredQuestion

http://stackoverflow.com/comment/135590583
type: Comment
comment on: http://stackoverflow.com/a/64073933
score: 0
type: AnswerComment
has text: I am personally a fan of 'conda env create'. However, I would really like to have all the flags from 'conda create'. Especially the --no-deps flag. With 'conda env create', to my knowledge, I am forced to use 'conda remove ... --force ...' to get rid of the dependencies I don't care, which really annoying.

http://stackoverflow.com/comment/83009193
type: Comment
type: QuestionComment
has text: Did see this? :https://learn.microsoft.com/en-us/python/api/azure.mgmt.network.v2017_09_01.operations.networkinterfacesoperations?view=azure-python#azure_mgmt_network_v2017_09_01_operations_NetworkInterfacesOperations_list_virtual_machine_scale_set_network_interfaces
comment on: http://stackoverflow.com/q/48018835
score: 0

http://stackoverflow.com/comment/83073007
type: QuestionComment
type: Comment
has text: connection pool is above 800 (max_connections).
comment on: http://stackoverflow.com/q/48049396
score: 0

http://stackoverflow.com/comment/83245873
has text: Explain us how you got newProductName? So we can recommend a pandas way.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48133834
type: QuestionComment

http://stackoverflow.com/q/48163430
answer count: 3
favorite count: 0
has title: :TypeError: %d format: a number is required, not str: even numbers were given in python pandas
type: UnansweredQuestion
tagged with: parameterized-query
has body: I am trying to update the values in the mysql database using parameterized queries. But after running the below code: df = pd.read_sql('SELECT * FROM df LIMIT 3', con=db_connection) print(df.shape) labels = ('I1','I2','I3') ids = (123456,123457,123458) data = (labels,ids) cursor = db_connection.cursor() for i in df.id: cursor.execute("UPDATE df SET label = %s WHERE id= %d",data) db_connection.commit() db_connection.close() I am getting this error: TypeError: %d format: a number is required, not str The data type of 'id' is int in database. And I am providing numbers only. don't know why it is throwing such error...
tagged with: python
score: 1
linked to: http://stackoverflow.com/q/5785154
tagged with: mysql
has answer: http://stackoverflow.com/a/48168653
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/60790655
downvote count: 0
has answer: http://stackoverflow.com/a/48163536
has comment: http://stackoverflow.com/comment/101226841

http://stackoverflow.com/a/48065620
type: Answer
answers question: http://stackoverflow.com/q/48055536
score: 2
has comment: http://stackoverflow.com/comment/83180710
has comment: http://stackoverflow.com/comment/83148494
upvote count: 3
has comment: http://stackoverflow.com/comment/83180674
has comment: http://stackoverflow.com/comment/83148463
has comment: http://stackoverflow.com/comment/83181732
downvote count: 1
has comment: http://stackoverflow.com/comment/83115239
has comment: http://stackoverflow.com/comment/83181022
has comment: http://stackoverflow.com/comment/83147948
has comment: http://stackoverflow.com/comment/83113641
has body: how can I construct my train and validation dataset? Not sure if a rule of thumb, but a common approach is to split your dataset into a ~80% training set and ~20% validation set; in your case this would be approximately 80k and 20k. The actual percentages may vary, but that ratio is the one most sources recommend. Ideally you would also want to have a test dataset, one that you never used during training or validation, to evaluate the final performance of your models. Now, regarding the shape of your data it is important to recall what the keras docs on Recurrent Layers says: Input shape 3D tensor with shape (batch_size, timesteps, input_dim). Defining this shape would depend on the nature of your problem. You mention you want to predict sales, so this can be phrased as a Regression Problem. You also mention your data consists of 300 columns that make up your time series, and naturally you have the real sales value for each of those rows. In this case, using a batch size of 1, your shape seems will be (1, 300, 1). Which means you are training on batches of 1 element (the most thorough Gradient update), where each has 300 time steps and 1 feature or dimension on each time step. For splitting your data one option you can use that has helped me before is the train_test_split method from Sklearn, where you simply pass your data and labels and indicate the ratio you want: from sklearn.cross_validation import train_test_split #Split your data to have 15% validation split X, X_val, Y, Y_val = train_test_split(data, labels, test_size=0.15)
has comment: http://stackoverflow.com/comment/83115257
has comment: http://stackoverflow.com/comment/83180817
has comment: http://stackoverflow.com/comment/83180760

http://stackoverflow.com/a/48050344
type: AcceptedAnswer
type: Answer
has body: I reinstall it before install mysql, it works! I guess this command 'yum -y remove mysql57-community-release-el7-10.noarch' disrupte the environment files.
upvote count: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48034645
score: 0
answers question: http://stackoverflow.com/q/48034645

http://stackoverflow.com/q/48066466
downvote count: 0
has answer: http://stackoverflow.com/a/61507570
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/83138435
type: Question
has body: I am developing an application with PyQT4 and Python 2.7. I am using PyInstaller to compile/build the application to an executable. The issue I'm having is whenever I build the application using PyInstaller using its --icon=icon.ico (for example), it gives the application an icon. However, the taskbar icon and the window icon do not show. When I do not use the parameter (--icon), and use the following lines instead, the application has no icon, yet the taskbar icon and window icon both have the correct icons. app.setWindowIcon(QtGui.QIcon(':/images/Images/icon.ico')) LoginMainWindow.setWindowIcon(QtGui.QIcon(':/images/Images/icon.ico')) If I combine both the parameter and those lines of code, the application has an icon, yet the taskbar icon and window icon do not show.
tagged with: pyqt4
tagged with: python-2.7
has title: How to set Window and Taskbar Icon with PyQT4 and PyInstaller?
tagged with: pyqt
answer count: 1

http://stackoverflow.com/comment/83184185
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48104261
has text: You might want to mention the optional extra argument to getattr, or the possibility of an `AttributeError` in the case where the user enters something besides `'sam'` or `'dan'`.

http://stackoverflow.com/a/49261852
has body: trying to do the same thing here and found out the LinkedIn hide the page source using javascript which is not readable by the WebDriver as there is no HTML to work with. I am using this code to get the inner HTML but having issues clicking the connect button. You will notice that the actual HTML is inside data variable, how can I get the click to work in this situation. Hany help would be highly appreciable. this code is a small part of a large project which does a lot of things on LinkedIn. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import WebDriverException import time from time import sleep from bs4 import BeautifulSoup from tqdm import tqdm import csv from urllib.parse import urljoin import re import sys import colorama import random email = input("Your Login Email Please: ") print(email) password = input("Your Password Please: ") print(password) time_delay = int(input("Please Enter Delay In Secs For Randomization: ")) print(time_delay) option = webdriver.ChromeOptions() option.add_argument("--normal") option.add_argument("--start-maximized") option.add_argument("--disable-extensions") option.add_argument("--auto-open-devtools-for-tabs") option.add_argument("--disable-infobars") option.add_argument("--disable-extensions") driver = webdriver.Chrome(executable_path=r"C:\Users\Rohit.METRO-ROHIT\Desktop\Selenium Development\chromedriver.exe", chrome_options=option) Development\chromedriver.exe", chrome_options=option) driver.get('https://www.linkedin.com') email_box = driver.find_element_by_id('login-email') email_box.send_keys(email) time.sleep(random.random() * time_delay) pass_box = driver.find_element_by_id('login-password') pass_box.send_keys(password) time.sleep(random.random() * time_delay) submit_button = driver.find_element_by_id('login-submit') submit_button.click() with open('lets_connect.csv') as example_file: example_reader = csv.reader(example_file) for row in example_reader: time.sleep(r…
has comment: http://stackoverflow.com/comment/85537927
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48120556

database
tags question: http://stackoverflow.com/q/48080579
tags question: http://stackoverflow.com/q/48154172
tags question: http://stackoverflow.com/q/48062763
type: Tag
tags question: http://stackoverflow.com/q/48173347
tags question: http://stackoverflow.com/q/48076096
tags question: http://stackoverflow.com/q/48122906
tags question: http://stackoverflow.com/q/48134780
tags question: http://stackoverflow.com/q/48066546
tags question: http://stackoverflow.com/q/48160172
tag name: database
tags question: http://stackoverflow.com/q/48171485
tags question: http://stackoverflow.com/q/48110630
tags question: http://stackoverflow.com/q/48105991
tags question: http://stackoverflow.com/q/48133762
tags question: http://stackoverflow.com/q/48143659
tags question: http://stackoverflow.com/q/48101903
tags question: http://stackoverflow.com/q/48099843
tags question: http://stackoverflow.com/q/48031568
tags question: http://stackoverflow.com/q/48131705
tags question: http://stackoverflow.com/q/48158574
tags question: http://stackoverflow.com/q/48161770
tags question: http://stackoverflow.com/q/48146748

http://stackoverflow.com/a/48049401
upvote count: 5
has body: You might consider embedding some javascript code in your jinja template which can do that work for you. Embeded javascript code will look something like this. &lt;script&gt; window.setTimeout(function(){ // Move to a new location or you can do something else window.location.href = "https://www.google.co.in"; }, 5000); &lt;/script&gt;
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48049300
answers question: http://stackoverflow.com/q/48049300
score: 5

http://stackoverflow.com/comment/83297827
score: 0
comment on: http://stackoverflow.com/a/48159118
type: Comment
type: AnswerComment
has text: This is the xpath I get. //*[@id="yui-gen2-button"] it doesn't seem to work

http://stackoverflow.com/comment/83110157
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48068270
has text: you are looking for `isin`
type: Comment

http://stackoverflow.com/a/48024107
score: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/48023744
answers question: http://stackoverflow.com/q/48023744
upvote count: 5
type: AcceptedAnswer
downvote count: 0
has body: You can simply use NumPy functions to get the desired result: np.sum(np.abs(np.diff(time))) This works according to your desired formula even though np.diff calculates the difference time[i+1] - time[i] (instead of time[i] - time[i+1]) because you're using the absolute value. Because this uses NumPy functions on a NumPy array it's probably much faster than any Python comprehension and/or functions.

http://stackoverflow.com/a/59096829
type: Answer
has comment: http://stackoverflow.com/comment/129097132
score: 2
upvote count: 2
has body: With pgloader you can execute command instructions to load data from SQLite into Postgres. Install on OSX with Homebrew: brew install pgloader Create a script file. Eg migrate.script: load database from sqlite:///path/to/db.sqlite3 into postgresql:///yourpostgresdbname with include drop, create tables, create indexes, reset sequences set work_mem to '16MB', maintenance_work_mem to '512 MB'; Run it: pgloader migrate.script I did a testdrive with a SQLite database containing a minimal Wagtail project (some pages, revisions and images) and it worked perfectly.
answers question: http://stackoverflow.com/q/48141975
downvote count: 0

http://stackoverflow.com/comment/83004363
type: QuestionComment
comment on: http://stackoverflow.com/q/48017570
has text: @Exprator updated with models. My gut is telling me that it's accessing the post_save which is jumping to the other models file before loading in the initial AccessLevel.
score: 0
type: Comment

http://stackoverflow.com/a/48032082
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/83034664
answers question: http://stackoverflow.com/q/48031797
has body: import pandas as pd import numpy as np wu=pd.DataFrame({'a':['hhh',2,3,4,5],'b':[1,2,np.nan,np.nan,5]}) #wu = wu[wu.a.str.contains('\d+',na=False)] #wu = wu[wu.a.apply(lambda x: x.isnumeric())] wu = wu[wu.a.apply(lambda x: isinstance(x, (int, np.int64)))] print(wu) Note that you missed out a closing parenthesis when creating your DataFrame. I tried 3 ways, but only the third one worked. You can always try the other ones (commented out) if that works for you. Do let me know if it works on the larger dataset.
has comment: http://stackoverflow.com/comment/83034767
has comment: http://stackoverflow.com/comment/83071181
has comment: http://stackoverflow.com/comment/83034849
has comment: http://stackoverflow.com/comment/83034842

http://stackoverflow.com/a/48037104
answers question: http://stackoverflow.com/q/48037051
has comment: http://stackoverflow.com/comment/83044338
has comment: http://stackoverflow.com/comment/83046499
type: Answer
has comment: http://stackoverflow.com/comment/83044272
has comment: http://stackoverflow.com/comment/83046379
score: 0
has body: To use a global variable in python, I think you should declare the variable without the global keyword outside of the function, and then declare it with the global keyword inside of the function. x=5 def h(): global x x=6 print(x) h() print(x) This code would print 5 6 However global variables are usually something to avoid.

http://stackoverflow.com/q/48120944
has answer: http://stackoverflow.com/a/48121224
has body: Say I have the following two SQLAlchemy ORM classes: import sqlalchemy as sa class Address(Base): __tablename__ = 'DimAddress' AddressKey = sa.Column(sa.Integer, primary_key=True) # ... columns ... class DealerOrganisation(Base): __tablename__ = 'DimDealerOrganisation' DealerOrganisationKey = sa.Column(sa.Integer, primary_key=True) # ... columns ... DealerOrganizationAddressKey = sa.Column(sa.Integer, sa.ForeignKey('DimAddress.AddressKey'), nullable=False) # ... columns ... address = relationship('Address') I can get dealer organizations and their address, if present, as follows: session = Session() query = session.query(DealerOrganisation).outerjoin(DealerOrganisation.address).options(contains_eager(DealerOrganisation.address)) This gives me SQL approximately like this: SELECT * FROM DimDealerOrganisation LEFT JOIN DimAddress ON AddressKey = DealerOrganizationAddressKey But what if I want to do an ORM query for only a subset of related objects: SELECT * FROM DimDealerOrganisation LEFT JOIN DimAddress ON AddressKey = DealerOrganizationAddressKey AND ZipCode = '90210' That is, I want all the dealers, but I only want their address if the zip code is 90210. As far as I can tell, join() and outerjoin() let you specify either a relationship or an explicit condition, but not both. In this contrived example I could use an explicit condition and get back rows instead of ORM objects, but it would be unwieldy in a real query involving multiple tables and one-to-many relations. I want to add additional conditions to the on clause but still have it populate the address attribute of the returned DealerOrganisation objects. Is this possible?
tagged with: sqlalchemy
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/11144536
score: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48121224
duplicate of: http://stackoverflow.com/q/11144536
tagged with: sql-server
type: Question
tagged with: python
has title: Can you add conditions to the on clause of a relationship join in SQLAlchemy?
upvote count: 2
answer count: 1

http://stackoverflow.com/q/48170759
has title: python - concatenate two time series with different time stamps
tagged with: python
accepted answer: http://stackoverflow.com/a/48171322
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46666383
linked to: http://stackoverflow.com/q/20109391
type: Question
tagged with: concatenation
has body: My question is exactly same with the question But, my language is Python, not R. So I ask this question again. I have two time series with different time stamps and a different number of data points. For example, first data is second data is . I concatenate two tables into one table. I want to do two things. First, time index should be in order. It is easily done by pd.concat([df1, df2], axis=1). The result is The second thing is to replace 'NA' by the most recent data point. For example, at time 0.1, the value of column 'B' is 2.1 which is the value at time 0.09. In a same manner, the value of columns 'A' at time 0.30 should be 3.0. But still, there is no value at time 0.09 for columns 'A'. How can I do this second job? Thank you!
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83321143
has answer: http://stackoverflow.com/a/48171322
tagged with: time

http://stackoverflow.com/q/48053955
has comment: http://stackoverflow.com/comment/83080789
has comment: http://stackoverflow.com/comment/117108907
has comment: http://stackoverflow.com/comment/83106201
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/62925227
accepted answer: http://stackoverflow.com/a/62925227
has comment: http://stackoverflow.com/comment/83098753
has comment: http://stackoverflow.com/comment/83080829
tagged with: sqlalchemy
upvote count: 28
type: Question
has comment: http://stackoverflow.com/comment/122565971
has title: Alembic Migrations on Multiple Models
answer count: 3
tagged with: alembic
favorite count: 0
possible better answer: http://stackoverflow.com/a/60388520
score: 28
has comment: http://stackoverflow.com/comment/83114061
has answer: http://stackoverflow.com/a/60388520
has answer: http://stackoverflow.com/a/73697383
has comment: http://stackoverflow.com/comment/83081553
tagged with: python
has body: I am attempting to create a revision with --autogenerate using Alembic for two Models, but am receiving a duplicate table keys error. Does, a schema need to be specified? If so, how can it be set? The documentation I've read says to use __table_args__ = {'schema': 'somename'}, but that hasn't helped. Any tips or suggestions are greatly appreciated. My current setup is: base.py from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() workspace.py from sqlalchemy import Column, Integer, String from base import Base class WorkspaceModel(Base): __tablename__ = 'workspaces' id = Column(Integer, primary_key=True) name = Column(String) host.py from sqlalchemy import Column, Integer, String from base import Base class HostModel(Base): __tablename__ = 'hosts' id = Column(Integer, primary_key=true) ip = Column(String) alembic/env.py from host import HostModel from workspace import WorkspaceModel target_metadata = [HostModel.metadata, WorkspaceModel.metadata] Error ValueError: Duplicate table keys across multiple MetaData objects: "hosts", "workspaces"

http://stackoverflow.com/comment/134998784
has text: `if isinstance(pkl, pd.DataFrame) or isinstance(pkl, pd.Series):` seems to be sufficient
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48126264
type: Comment

http://stackoverflow.com/q/48103771
downvote count: 0
has comment: http://stackoverflow.com/comment/83183229
has title: Python append to list issue
score: 1
possible better answer: http://stackoverflow.com/a/48104069
has answer: http://stackoverflow.com/a/48104041
has answer: http://stackoverflow.com/a/48104069
type: Question
has comment: http://stackoverflow.com/comment/83190415
answer count: 2
has body: My issue is in regards to appending a list in Python. I am making a program with Python and kivy that gives a student a math test. The student is asked a series of random math questions, and then my goal is to give them a final grade once they are done with 50 math questions. However, I am having trouble adding their answers to a list of correct answers and incorrect answers. They may get a question for example like "2 + 2". Their answer could be 4, and I'd like to add the string 4 to an empty list called self.correct_answers. If their answer was 5, i'd like to add it to a list called self.incorrect_answers. I am using the append method to add the answer to the list, but then when the next question is asked, it deletes my prior list. So if I ask them a series of questions, the list will only contain the most recent answer. It won't contain the prior 9 answers. Here is a piece of my code below: def __init__(self, **kwargs): super(Easy_Level_Addition, self).__init__(**kwargs) def rand_numbers(self, min_num=0, max_num=10): """Generate a minimum/maximum number threshold for the 'easy' level. These numbers will fall between 0 and 10. """ self.max_num = max_num self.min_num = min_num self.operation = None self.num_1 = None self.num_2 = None self.QUESTION = "{} {} {}"#This is how the question will be formatted def get_random_question(self):#Number 1 and 2 will be a random integer between 1 and 10 self.rand_numbers() self.num_1 = random.randint(self.min_num, self.max_num) self.num_2 = random.randint(self.min_num, self.max_num) self.operation = "+" self.q_s = self.QUESTION.format(self.num_1, self.operation, self.num_2) self.answer = str(self.num_1 + self.num_2) self.ids.questions_easy.text = str(self.q_s) #self.ids.answers.text = str(self.answer) self.ids.answers.text = "" self.ids.result_easy.text = "" def user_answers(self): #Pass the prior function def __init__(self, **kwargs): super(self.answer, self).__init__(**kwargs) self.correct_answers = [] self.incorrect_answers = …
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83183206
accepted answer: http://stackoverflow.com/a/48104041
tagged with: python
tagged with: kivy
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/48064451
score: -1
has body: I have a Python API with three endpoints hosted on Azure. One of the endpoints started returning a server error last week. I checked the platform so everything is OK there. I checked the logs and found that for this endpoint, the traceback returns this line at the end File ".\app\models.py", line 280, in json return {'entity': otherentity.name, 'details': self.details, 'entity_id': otherentity.id, AttributeError: 'NoneType' object has no attribute 'name' This is the stdout and std error: StdOut: StdErr: D:\home\site\wwwroot\env\Lib\site- packages\flask_cache\jinja2ext.py:33: ExtDeprecationWarning: Importing flask.ext.cache is deprecated, use flask_cache instead. from flask.ext.cache import make_template_fragment_key ErrorCode Access is denied. (0x5) The block of code that line 280 references is part of a class. Here is the block: def json(self, entityid): otherentity = self.entity_1 if entityid == self.entity_id2 else self.entity_2 return {'entity': otherentity.name, 'details': self.details, 'entity_id': otherentity.id, 'id': self.id} This app was kind of thrown at me so I'm new at debugging and from what I can see, the issue is with calling .name because it doesn't exist? Also, not sure if flask_cache being deprecated has anything to do with this problem. I found that flask_cache is no longer maintained and I should be using flask-caching instead. Any ideas about how to proceed to fix this server error? I'm not sure why the other two endpoints using the same model works but not this one.
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/48107182
downvote count: 1
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/83102068
tagged with: http-error
tagged with: azure
has comment: http://stackoverflow.com/comment/83102989
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/83102325
has comment: http://stackoverflow.com/comment/83103235
has comment: http://stackoverflow.com/comment/83107775
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/48107182
has title: API endpoint returning 500 server error - traceback returning attribute error

http://stackoverflow.com/comment/83219424
score: 0
type: Comment
has text: Put a loop in `handle()`.
type: QuestionComment
comment on: http://stackoverflow.com/q/48121053

http://stackoverflow.com/q/48109170
score: 1
has body: I have recently signed up for using telegram bot API but when I look into every example, it says to include API TOKEN of our own but have not mentioned how to get the token. When I go to Telegram site , all it shows me are some api id , hash and a RSA key pair . How do I generate a telegram API Token or how and where to get one ?
type: Question
tagged with: telegram-bot
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-telegram-bot
tagged with: telegram
type: UnansweredQuestion
has title: Where can I find the Telegram bot API TOKEN?
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48109513

http://stackoverflow.com/a/48136458
has body: I've tweaked your code little bit: 1) apall = ap_database[0], ap_database[1], ap_database[2] this assignment is not necessary, since ap_database = apdb.get('AP Database') this will make ap_database already a list 2) ip_list = ['100.20.300.400', '100.20.300.500', '100.20.300.700'] this should be out of the loop and no need for reassignment for each loop cycle 3) instead of the 2 lines below, you can directly search for public ip in the ip_list like: if public in ip_list: for ip in ip_list: if ip == public: 4) and instead of using getitem it's more readable for me to just use get method (just for me, if you prefer, you can use getitem) apdb = {'AP Database': [{'AP Type': '110H', 'Name': 'varagu', 'Public IP': '100.20.300.400', 'Wired MAC Address': 'aa:bb:cc:dd:ee:11'}, {'AP Type': '110H', 'Name': 'thinai', 'Public IP': '100.20.300.500', 'Wired MAC Address': 'aa:bb:cc:dd:ee:22'}, {'AP Type': '110H', 'Name': 'Ragi', 'Public IP': '100.20.300.600', 'Wired MAC Address': 'aa:bb:cc:dd:ee:33'}]} ap_database = apdb.get('AP Database') ip_list = ['100.20.300.400', '100.20.300.500', '100.20.300.700'] results = {'success': [], 'fail': []} for ap in ap_database: public = ap.get('Public IP') name = ap.get('Name') if public in ip_list: results['success'].append(public) else: results['fail'].append(public) print(results['success'], reuslts['fail'])
has comment: http://stackoverflow.com/comment/83250645
type: Answer
has comment: http://stackoverflow.com/comment/83250999
answers question: http://stackoverflow.com/q/48136280
score: 0

http://stackoverflow.com/a/48172029
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83324696
type: Answer
has body: There is no need to write a regex here. This is already builtin in Python with str.isalpha: Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. So we can check it with: if your_string.isalpha(): pass Note however that: Note: str.isalpha also includes diacritics, etc. For example: &gt;&gt;&gt; 'ä'.isalpha() True this is not per se a problem. But it can be something to take into account. In case you do not want diacricics, you can for instance check that all characters have an ord(..) less than 128 as well: if your_string.isalpha() and all(ord(c) &lt; 128 for c in your_string): pass The advantage of using builtins is that these are more self-explaining (isalpha() clearly suggests what it is doing), and furthermore it is very unlikely to contain any bugs (I am not saying that other approaches do contain bugs, but writing something yourself, typically means it is not tested very effectively, hence it can still not fully cover edge and corner cases).
score: 4
accepted answer of: http://stackoverflow.com/q/48171985
answers question: http://stackoverflow.com/q/48171985
upvote count: 4
has comment: http://stackoverflow.com/comment/83323607

http://stackoverflow.com/a/48036388
upvote count: 1
has comment: http://stackoverflow.com/comment/83042806
has comment: http://stackoverflow.com/comment/83043202
has body: One of the values for energy in your excel file is a string "..." and when in your coverter function, you just return energy as is if it is a string datatype. Therefore you are getting a string returned along with your numbers which then changes the dtype of you column to 'object. You could try something like this: def convert_energy(energy): if energy == "...": return np.nan elif isinstance(energy, float): return float(energy*1000000) else: return float(energy) df = pd.read_excel('http://unstats.un.org/unsd/environment/excel_file_tables/2013/Energy%20Indicators.xls', skiprows=17, skip_footer=38, usecols=[2,3,4,5], na_values=['...'], names=['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable'], converters={1: convert_energy}).set_index('Country') df.info() Output: &lt;class 'pandas.core.frame.DataFrame'&gt; Index: 227 entries, Afghanistan to Zimbabwe Data columns (total 3 columns): Energy Supply 222 non-null float64 Energy Supply per Capita 222 non-null float64 % Renewable 227 non-null float64 dtypes: float64(3) memory usage: 6.2+ KB
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48036296

http://stackoverflow.com/comment/83016253
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48020132
has text: See the most upvoted answer. Possible duplicate of [Python: Unable to download with selenium in webpage](https://stackoverflow.com/questions/44072022/python-unable-to-download-with-selenium-in-webpage/44196146#44196146)
type: QuestionComment

http://stackoverflow.com/comment/83175350
type: AnswerComment
has text: ohh ok .. thnks :)
type: Comment
comment on: http://stackoverflow.com/a/48074275
score: 0

http://stackoverflow.com/comment/83298642
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48159461
has text: no. You've not given the math behind this much thought if you think that.

http://stackoverflow.com/comment/83051326
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48040346
type: Comment
has text: @dkato I'm not sure what you mean by "feature". But I have 2 columns of data in my csv: Height and Points per Game. I also have 18 rows as you indicated earlier.

http://stackoverflow.com/q/48037197
has comment: http://stackoverflow.com/comment/83044978
type: Question
has comment: http://stackoverflow.com/comment/83044884
tagged with: numpy
has comment: http://stackoverflow.com/comment/83044841
tagged with: arrays
score: 0
has body: I am reading a bunch of images with opencv in python like so: data = [] for imagePath in imagePaths: image = cv2.imread(imagePath) image = img_to_array(image) data.append(image) so data contains an array of numpy arrays. I would now like to convert it all to float and then divide by 255 like so: data = np.array(data, dtype='float') / 255.0 But I get the error ValueError; setting an array element with a sequence Does this mean that there are some values in data that are not convertible to float? Does img_to_array sometimes return non-number values?
type: UnansweredQuestion
tagged with: python
tagged with: opencv
has comment: http://stackoverflow.com/comment/83044876
has comment: http://stackoverflow.com/comment/83044503
answer count: 0
has title: Python; When trying to convert an image to a numpy array of type float I get "ValueError; setting an array element with a sequence."

http://stackoverflow.com/q/48059523
has comment: http://stackoverflow.com/comment/83092876
has comment: http://stackoverflow.com/comment/83091702
tagged with: networkx
has answer: http://stackoverflow.com/a/48060968
type: AnsweredQuestion
has body: Here is a fragment of the code responsible for creating the graph and its edges, depending on whether the edge exists and the condition that validates the shortest paths: for q in range(len(aaa_binary)): if len(added)!=i+1: g.add_nodes_from (aaa_binary[q]) t1 = (aaa_binary[q][0],aaa_binary[q][1]) t2 = (aaa_binary[q][1],aaa_binary[q][2]) t3 = (aaa_binary[q][2],aaa_binary[q][3]) if g.has_edge(*t1)==False and g.has_edge(*t2)==False and g.has_edge(*t3)==False: g.add_edge(*t1) g.add_edge(*t2) g.add_edge(*t3) added.append([aaa_binary[q],'p'+ str(i)]) for j in range(len(added)): if nx.shortest_path(g, added[j][0][0], added[j][0][3])!=added[j][0] or nx.shortest_path(g, aaa_binary[q][0], aaa_binary[q][3])!=aaa_binary[q]: g.remove_edge(*t1) g.remove_edge(*t2) g.remove_edge(*t3) added.remove([aaa_binary[q],'p'+ str(i)]) break if g.has_edge(*t1)==False and g.has_edge(*t2)==False and g.has_edge(*t3)==True: g.add_edge(*t1) g.add_edge(*t2) added.append([aaa_binary[q],'p'+ str(i)]) for j in range(len(added)): if nx.shortest_path(g, added[j][0][0], added[j][0][3])!=added[j][0] or nx.shortest_path(g, aaa_binary[q][0], aaa_binary[q][3])!=aaa_binary[q]: g.remove_edge(*t1) g.remove_edge(*t2) added.remove([aaa_binary[q],'p'+ str(i)]) break # ... and then the rest of the False and True possibilities combinations in the `if g.has_edge()'condition. added[] - list of currently valid paths in the form [[[0, 2, 4, 6], 'p0'], [[0, 2, 4, 1], 'p1'],...] aaa_binary[] - list of path combinations to check in the form [[0, 2, 4, 6], [0, 2, 6, 4], [0, 4, 2, 6],...] Loop operation: The algorithm selects one sublist from the aaa_binary list, then adds nodes to the graph and creates edges. Then the algorithm checks if the given edge exists. If it does not exist, it adds it to the graph, if it exists, it does not add. Then, if the condition of the shortest path is not met, only the newly added edge is removed from the graph. And so until you find the right path from the aaa_binary list. As you can see onl…
tagged with: algorithm
tagged with: if-statement
has title: Many combinations multi-line conditions of the 'if' in a loop
has answer: http://stackoverflow.com/a/48060431
possible better answer: http://stackoverflow.com/a/48060968
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83092587
has comment: http://stackoverflow.com/comment/83092750
has comment: http://stackoverflow.com/comment/83091897
has comment: http://stackoverflow.com/comment/83092284
score: 0
has comment: http://stackoverflow.com/comment/83091861
accepted answer: http://stackoverflow.com/a/48060431
tagged with: python

http://stackoverflow.com/comment/83097677
score: 3
has text: Wow this is really strange. Unfortunately I cannot reproduce the behavior, as I cannot run your code without the data. Can you provide a [minimal example](https://stackoverflow.com/help/mcve) that reproduces the behavior?
comment on: http://stackoverflow.com/q/48062499
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48141088
downvote count: 0
tagged with: cmd
has title: Keeping cmd cursor on same line after printing
favorite count: 0
type: UnansweredQuestion
tagged with: windows
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/83260214
has body: Im making a game that runs in command prompt and its supposed to take an input after being prompted. However, I need the cursor to remain on the same line as the prompt. Something like "Input next move: [cursor stays here]". im using msvcrt to get the input. def getinput(game): display(game) inp = 21 print("Input next move: ") while True: if msvcrt.kbhit(): inp = int(msvcrt.getch().decode("UTF-8")) while (inp &gt; 8 or inp &lt;0): print("Choose a number between 0 and 8") inp = int(msvcrt.getch().decode("UTF-8")) while (listgame[inp] != "."): print("Already occupied. Choose an available space") inp = int(msvcrt.getch().decode("UTF-8")) break game[inp]=enemy print("You played: " + str(inp))
score: 1
type: Question
has comment: http://stackoverflow.com/comment/83260009
upvote count: 1
has answer: http://stackoverflow.com/a/48142393
answer count: 1

http://stackoverflow.com/comment/83279616
score: 1
type: AnswerComment
has text: @rockstar I mean iterating from bottom to top. Anyhow, removed it.
type: Comment
comment on: http://stackoverflow.com/a/48150484

http://stackoverflow.com/q/48116430
has body: Is there a better way to create a multidimensional array in numpy using a FOR loop, rather than creating a list? This is the only method I could come up with: import numpy as np a = [] for x in range(1,6): for y in range(1,6): a.append([x,y]) a = np.array(a) print(f'Type(a) = {type(a)}. a = {a}') EDIT: I tried doing something like this: a = np.array([range(1,6),range(1,6)]) a.shape = (5,2) print(f'Type(a) = {type(a)}. a = {a}') however, the output is not the same. I'm sure I'm missing something basic.
score: 6
duplicate of: http://stackoverflow.com/q/11144513
tagged with: python
upvote count: 7
downvote count: 1
has answer: http://stackoverflow.com/a/63865190
has answer: http://stackoverflow.com/a/48116621
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/72796400
linked to: http://stackoverflow.com/q/11144513
has title: best way to create numpy array from FOR loop
has comment: http://stackoverflow.com/comment/83209360
has comment: http://stackoverflow.com/comment/83214689
linked to: http://stackoverflow.com/q/10093293
has answer: http://stackoverflow.com/a/48117112
answer count: 4
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/83051373
comment on: http://stackoverflow.com/q/48040346
type: Comment
type: QuestionComment
has text: @dkato That worked! Thank you very much. How do I mark your answer as the answer?
score: 0

http://stackoverflow.com/comment/96282746
comment on: http://stackoverflow.com/a/48125183
has text: @ShravyaBoggarapu I am not sure I understand your question. What is your input format, and what do you need on output?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48130638
tagged with: calculator
favorite count: 0
has answer: http://stackoverflow.com/a/48130725
tagged with: python-3.x
linked to: http://stackoverflow.com/q/23294658
has body: I want to make this code much more elegant, using loop for getting user input into a list and also making the list as a list of floats withot having to define each argument on the list as a float by itself when coming to use them or print them... I am very new to python 3.x or python in general, this is the first code i have ever written so far so 'mercy me pardon!' Name = "john" Place = "Colorado" print (("Hello %s What's up? \nare you coming to the party tonight in %s\n if not at least try to make simple calculator:") % (Name, Place)) print ("you will input 2 numbers now and i will devide them for you:") calc =list(range(2)) calc[0] = (input("number 1:")) calc[1] = (input("number 2:")) print (float(calc[0])/float(calc[1]))
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83238589
upvote count: 1
tagged with: loops
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48130684
score: 0
has answer: http://stackoverflow.com/a/48130687
answer count: 3
has title: using loops for input list by user

http://stackoverflow.com/comment/83271116
comment on: http://stackoverflow.com/a/48145017
score: 0
has text: ---> 21 arrays_in_week = [my_dict[day_int] for day_int in week_to_date_list[week]] IndexError: list index out of range
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83226411
comment on: http://stackoverflow.com/q/48124647
type: Comment
type: QuestionComment
has text: @StevenTautonico For an empty file, `print(open("Memory.txt", 'r').readlines())` will give you `[]` whereas for a file with blank line, you will get `['\n']`.
score: 0

http://stackoverflow.com/q/48131052
has answer: http://stackoverflow.com/a/48132586
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/48132586
answer count: 1
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/html
has title: BeautifulSoup child-tags and removing duplicates
tagged with: python
has body: I'm attempting to clean some html by parsing it through BeautifulSoup using Python 2. BeautifulSoup parses the raw_html which is associated with a website_id in the html_dict. It also removes any attribute associated with the html tags (, , and ). html_dict = {"l0000": ["test", "lol", "test"], "l0001":[" this is html ", " this is html "]} clean_html = {} for website_id, raw_html in html_dict.items(): for i in raw_html: soup = BeautifulSoup(i, 'html.parser') scrape_selected_tags = soup.find_all(["a", "b", "p"]) # Remove attributes from html tag for i in scrape_selected_tags: i.attrs = {} print website_id, scrape_selected_tags This outputs: l0001 [ this is html ] l0001 [ this is html ] l0000 [test] l0000 [] l0000 [test, test] I have two questions: 1) The last output has outputted "test" twice. I assume this is because it is surrounded by both the and tags? How does one deal with child-tags to output test only? 2) Given a unique website_id, how would one remove duplicates, so that there's only one occurrence of this is html for l0001? I know that scrape_selected_tags has a type of bs4.element.ResultSet and I'm not sure how to handle this and insert the new output in the same format as html_dict but in clean_html. Thanks
type: AnsweredQuestion

http://stackoverflow.com/q/48147971
answer count: 2
score: 0
tagged with: pandas
has body: I have a pandas dataframe with multiple duplicate IDs as such: id col1 col2 col3 ENE80R N N Y ENE80R N N N ENE80R Y N N What I'm trying to achieve is this: id col1 col2 col3 ENE80R Y N Y I tried using df.drop_duplicates but it doesn't update all the Ys into one column, it just keeps the first row and removes the duplicates. Any idea how I can go about this? EDIT: The data doesn't only contain Y and N in it, there are columns that contain data and other text and integer data. But the only data that differ in the duplicated data are the Ys and Ns.
tagged with: python
possible better answer: http://stackoverflow.com/a/48148155
has comment: http://stackoverflow.com/comment/83274440
has answer: http://stackoverflow.com/a/48148155
accepted answer: http://stackoverflow.com/a/48148052
tagged with: data-cleaning
has title: Merge duplicate rows and delete all duplicates after merging into one row
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48148052
tagged with: dataframe
type: Question

http://stackoverflow.com/a/48043158
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48043033
score: 1
has body: You are returning None Therefore, you get None. return is equivalent to return None And the code after your return statement, is just unreachable code. you probably want: return liste_t,liste_l,liste_y
type: Answer

http://stackoverflow.com/comment/83146151
has text: Fantastic, I ended up using a slight variant of what you've given here. Also appreciate the edge case handling discussion
type: AnswerComment
comment on: http://stackoverflow.com/a/48082117
score: 0
type: Comment

http://stackoverflow.com/comment/83301435
has text: What does this have to do with deleting columns?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48160937
type: AnswerComment

http://stackoverflow.com/a/48056446
answers question: http://stackoverflow.com/q/48045412
upvote count: 1
has body: If you are using Selenium 3.x along with the recent Frirefox Quantum browsers, you have to download geckodriver.exe from this location place it in your system and mention the absolute location of the geckodriver binary through the argument executable_path as follows: from selenium import webdriver driver = webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe') driver.get('https://www.google.co.in') print("Page Title is : %s" %driver.title) driver.quit()
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/48084178
has body: The p variable starts out as a list of lists of strings. The strings get replaced with turtles: for i in range(4): for j in range(4): while h &lt; 16: p[i][j]=turtle.Turtle() # ... h+=1 The logic for looping over h is incorrect, you effectively set p[0][0] to a turtle 16 times and leave the rest as strings. Which fails later on when you try to use them as turtles. Instead consider: for i in range(4): for j in range(4): p[i][j]=turtle.Turtle() # ... h+=1 You don't need to explicitly test if h is 16 as it is being incremented 4 * 4 times.
type: Answer
answers question: http://stackoverflow.com/q/48083159
score: 0

http://stackoverflow.com/comment/83044885
type: Comment
score: 2
type: QuestionComment
has text: Your source code is being read as UTF-8 because you told Python to (with encoding comment you added at the top), but you have instead saved it in a different encoding. Use a text editor that lets you save as UTF-8, or change the encoding in the header to be correct.
comment on: http://stackoverflow.com/q/48037284

http://stackoverflow.com/comment/83034601
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48032107
has text: After I make a change, I get `[3, 2, 1, None]` instead of `[4, 3, 2,1 ]` and I am not sure why the 4 is gone. Any idea?

http://stackoverflow.com/comment/83308327
type: Comment
type: QuestionComment
has text: most likely, 'split_data[4]' does not contain what you think it does. Since you're printing it beforehand and can thus see the value, the most likely explanation would be that it contains some sort of whitespace.
score: 1
comment on: http://stackoverflow.com/q/48164539

http://stackoverflow.com/comment/83335723
comment on: http://stackoverflow.com/q/48170304
has text: Updated the question with a clearer problem statement (as I understand it). **The question is a duplicate of https://stackoverflow.com/questions/18449360/access-item-in-a-list-of-lists and should be closed**.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/66936300
has body: It's been a while since this question has been posted, but just in case someone stumbled upon this answer, this code snippet with cap.set() worked for me. I relied on the documentation that can be found here (cpp) and here (python). import cv2 # Get video handle. cap = cv2.VideoCapture("path/to/video") if not cap.isOpened(): print("Cannot initialize cap.") exit() # Get length of the video. video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # Initialize count. count = 0 # Frames loop. while True: # Check length of the video. if count == video_length: # Reset to the first frame. Returns bool. _ = cap.set(cv2.CAP_PROP_POS_FRAMES, 0) count = 0 # Get the frame. success, image = cap.read() if not success: print("Cannot read frame.") break # do something with the image. cv2.imshow("Frame", image) # Quit by pressing 'q'. if cv2.waitKey(1) & 0xFF == ord('q'): break count += 1 # Post loop. cap.release() cv2.destroyAllWindows() I used the above to go some n number of frames back by combining cap.get() and cap.set().
type: Answer
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48040138

http://stackoverflow.com/comment/83097173
has text: There isn't a question here, only a request for free labour... what have you tried?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48062271
score: 1

http://stackoverflow.com/q/48023457
favorite count: 0
tagged with: pycharm
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
score: 1
has title: Pycharm debugger skips breakpoints after specific line of code - why?
has body: I'm new to pycharm and so far my impression of the debugger is that it's marverlous! However, it behaves weird in my code and I cannot figure out what is going wrong. If I set a breakpoint to these lines of code and then press "step over" or "step into my code" it runs until the end ignoring all other upcoming breakpoints. Any idea what I do wrong? Breakpoints before that line work perfectly fine. for ind, fit in zip(pop, fitnesses): ind.fitness.values = fit my code You need to pip install deap, efel and brian2 for the code to run. # DEAP # https://github.com/DEAP/deap/tree/54b83e2cc7a73be7657cb64b01033a31584b891d # import array import matplotlib.pyplot as plt import pandas as pd from scipy.io import loadmat import random, numpy, os, efel, scipy, math, time, array, json from deap import algorithms, base, creator, tools, benchmarks from deap.benchmarks.tools import diversity, convergence # , hypervolume from machine_hh_model_v02 import brian_hh_model # parallel processing # from scoop import futures parallel_processing = "no" # Starting values channels = {"ENa": 65, "EK": -90, "El": -70, "ECa": 120, "gNa": 0.05, "gK": 0.005, "gL": 1e-4, "gM": 8e-5, "gCa": 1e-5} # Boundaries bounds = {"ENa": [50, 70], "EK": [-100, -80], "El": [-50, -100], "ECa": [100, 120], "gNa": [0, 1], "gK": [0, 1], "gL": [0, 1], "gM": [0, 1], "gCa": [0, 1]} low, up = [x[0] for x in bounds.values()], [x[1] for x in bounds.values()] # Set parameters ext = 2.5 # external current stimulation [nA] num_gen = 2 # number of generations num_parents = 40 # number of parents num_params = len(channels) # number of parameters to optimize prob_crossover = 0.9 # probability that crossover takes place # How to generate individuals def initIndividual(container, sigma): return container(random.gauss(x, sigma) for x in channels.values()) # CREATOR # http://deap.readthedocs.io/en/master/tutorials/basic/part1.html # The create() function takes at least two arguments, a name for the newly created class and a base class…
type: Question
tagged with: debugging
upvote count: 1

http://stackoverflow.com/a/48036169
score: 0
has comment: http://stackoverflow.com/comment/83052043
type: AcceptedAnswer
has body: Generate output files with pprint, run /usr/bin/diff -u or difflib against them, and you're done. Oh, and do code this in python3. You'll be glad you did.
has comment: http://stackoverflow.com/comment/83050841
type: Answer
accepted answer of: http://stackoverflow.com/q/48035856
has comment: http://stackoverflow.com/comment/83051881
answers question: http://stackoverflow.com/q/48035856
has comment: http://stackoverflow.com/comment/83050168

http://stackoverflow.com/q/48043845
tagged with: python
has body: If HTML is uploaded into Google App Engine with an intent to be serviced into an iframe, what is the best way to sanitize it (e.g. remove script and other malicious html) ? I am thinking of reader = blobstore.BlobReader(binfo.key()) value = reader.read() newHtml = lxml.html.clean.Cleaner().clean_html (value) #save newHtml as the blob in google cloud store to be served. I am wondering if there is a better way to do this and any help is much appreciated. NB: It will also be great if there is a way to remove anchors or make anchors(or sources) non-relative and secure http, etc.. (or just completely disallow).
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48051716
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/958997
downvote count: 0
tagged with: sanitization
accepted answer: http://stackoverflow.com/a/48051716
answer count: 1
has title: How to sanitize html blob uploads in python in Google App Engine?
favorite count: 0
tagged with: google-app-engine

http://stackoverflow.com/q/48151386
tagged with: python-asyncio
tagged with: asynchronous
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: Idiomatically gather results from a dict of futures
tagged with: python
score: 22
has comment: http://stackoverflow.com/comment/121863360
has body: I'm trying to write something as idiomatic as possible to gather results from futures stored in a dict. Let's imagine I have the following code: import asyncio async def sleep(seconds): print(f'sleeping for {seconds} seconds') await asyncio.sleep(seconds) print(f'finished sleeping {seconds} seconds') async def run(): tasks = { '4': sleep(4), '3': sleep(3), '2': sleep(2), '1': sleep(1), } print(await gather_from_dict(tasks)) if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(run()) The output I'm expecting is: sleeping for 2 seconds sleeping for 1 seconds sleeping for 4 seconds sleeping for 3 seconds finished sleeping 1 seconds finished sleeping 2 seconds finished sleeping 3 seconds finished sleeping 4 seconds {'4': None, '3': None, '2': None, '1': None} So far the cleanest solution I've found is: async def gather_from_dict(tasks:Dict[Hashable, Awaitable], loop=None, return_exceptions=False) -&gt; Dict: results = await asyncio.gather( *tasks.values(), loop=loop, return_exceptions=return_exceptions ) return dict(zip(tasks.keys(), results)) Any ideas on how to do this in a simpler way? Thanks!!!
has comment: http://stackoverflow.com/comment/83282605
type: Question
has comment: http://stackoverflow.com/comment/107874750
upvote count: 22
answer count: 2
has answer: http://stackoverflow.com/a/58774457
downvote count: 0
linked to: http://stackoverflow.com/q/2053021
tagged with: idioms
has answer: http://stackoverflow.com/a/49446818

http://stackoverflow.com/comment/83118721
score: 0
type: Comment
type: QuestionComment
has text: @user2896976.. no my application is a complete package and is not invoked as python app.py. The main function of the application is invoked through the console_script of the entry_point of setup.py
comment on: http://stackoverflow.com/q/48070973

http://stackoverflow.com/comment/83146346
comment on: http://stackoverflow.com/q/48085578
has text: Might be a Python 2.x vs. 3.x issue.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48123410
has body: df.B &gt; 0 results in a Series, e.g.: 0 True # 4 &gt; 0 =&gt; True 1 True # 2 &gt; 0 =&gt; True 2 True # ... 3 True 4 True 5 True 6 True 7 True 8 False # 0 is not &gt; 0 =&gt; False 9 False # 0 is not &gt; 0 =&gt; False ... Multiple values are returned which results in ambiguity (some are True while others are False). One solution is to use np.where: sentinel = np.nan # Or 0 if you must... df = df.assign(C=np.where(df['B'] != 0, df['A'] / df['B'], sentinel)) &gt;&gt;&gt; df A B C 0 2 4 0.5 1 0 2 0.0 2 1 2 0.5 3 4 4 1.0 4 1 1 1.0 5 4 4 1.0 6 2 4 0.5 7 1 2 0.5 8 4 0 NaN # NaN is assigned in cases where the value in Column `B` is zero. 9 1 0 NaN ...
score: 10
has comment: http://stackoverflow.com/comment/83223781
answers question: http://stackoverflow.com/q/48123368
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48123368
type: Answer
has comment: http://stackoverflow.com/comment/107154610
upvote count: 10
has comment: http://stackoverflow.com/comment/107166452

http://stackoverflow.com/q/48098985
accepted answer: http://stackoverflow.com/a/48099030
favorite count: 0
has title: pandas iterate rows to a new dataframe
upvote count: 2
downvote count: 2
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48099046
has answer: http://stackoverflow.com/a/48099046
has body: How to I sperate rows and form a new dataframe with the series ? Suppose I have a dataframe df and I am iterating over df with the following and trying to append over an empty dataframe df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)), columns=['a', 'b', 'c', 'd', 'e']) df1 = pd.DataFrame() df2 = pd.DataFrame() for index,row in df.iterrows(): if (few conditions goes here): df1.append(row) else: df2.append(row) the type of each rows over iteration is a series, but if I append it to empty dataframe it appends rows as columns and columns as row. Is there a fix for this ?
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48099030
score: 0
tagged with: pandas

http://stackoverflow.com/comment/83166105
score: 0
comment on: http://stackoverflow.com/q/48090757
type: Comment
type: QuestionComment
has text: You can use CountVectorizer or TfidfVectorizer in sklearn to convert your filtered words into numerical data ready to be used by ML algorithms.

http://stackoverflow.com/q/48137332
answer count: 4
has answer: http://stackoverflow.com/a/48137574
type: AnsweredQuestion
score: 3
has body: If you multiply an inequality by a negative number you must reverse the direction of the inequality. For example: 1 &lt; x &lt; 6 (1) -1 > -x > -10 (2) if x = 6, it is consistent with equation (1) and (2). Is there a way to multiply an inequality statement by an integer in a one-liner for Python to reverse the signs? From the practical point of view, I am trying to extract DNA/protein sequences from TBLASTN results. There are strands +1 and -1 and the operation after that condition statement is the same. # one-liner statement I would like to implement if (start_codon &lt;= coord &lt;= stop_codon)*strand: # do operation # two-liner statement I know would work if (start_codon &lt;= coord &lt;= stop_codon) and strand==1: # do operation elif (start_codon &gt;= coord &gt;= stop_codon) and strand==-1: # do operation
upvote count: 3
accepted answer: http://stackoverflow.com/a/48137385
has title: How to Reverse inequality statement?
has comment: http://stackoverflow.com/comment/83252344
type: Question
tagged with: if-statement
has comment: http://stackoverflow.com/comment/83252470
has answer: http://stackoverflow.com/a/48137385
possible better answer: http://stackoverflow.com/a/48137397
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83252394
has answer: http://stackoverflow.com/a/48137454
tagged with: python
has answer: http://stackoverflow.com/a/48137397

http://stackoverflow.com/q/48119483
answer count: 1
has title: Save body response from specific URL to file and decode it using mitmproxy
tagged with: mitmproxy
tagged with: python
tagged with: python-3.x
downvote count: 0
tagged with: man-in-the-middle
tagged with: https
type: Question
score: 2
accepted answer: http://stackoverflow.com/a/48158427
type: AnsweredQuestion
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/48158427
has body: I'm trying to save and decode body response from "https://example.com/orders" to the file using mitmdump. I found a script which saves only response to file, but it seems doesn't work on latest mitmproxy. from mitmproxy.models import decoded def response(context, flow): with decoded(flow.response): # automatically decode gzipped responses. with open("body.txt","ab") as f: f.write(flow.response.content) When I'm running script error message displaying : Script error: Traceback (most recent call last): File "save_body.py", line 1, in &lt;module&gt; from mitmproxy.models import decoded ImportError: No module named 'mitmproxy.models' My Operating System and version: Mitmproxy version: 2.0.2 (release version) Python version: 3.5.2 Platform: Linux-4.10.0-28-generic-x86_64-with-Ubuntu-16.04-xenial SSL version: OpenSSL 1.0.2g 1 Mar 2016 Linux distro: Ubuntu 16.04 xenial How can I save decoded body from only one URL, excluding other URLs, to a file? And how to do so: if this request from URL I need repeats, I need mitmdump to overwrite "body.txt"?

http://stackoverflow.com/comment/83047088
has text: Hi, sorry ... the cum_sum above is the column I was trying to create. and the code below worked , however it printed some warnings at the top. df_2['cum_sum'] =df_2.groupby(['words'])['count'].cumsum()
type: QuestionComment
comment on: http://stackoverflow.com/q/48033351
score: 0
type: Comment

http://stackoverflow.com/comment/95571932
type: AnswerComment
type: Comment
score: 1
has text: I get notified via email of any new question tagged ruamel.yaml, no need to notify me via a comment for that.
comment on: http://stackoverflow.com/a/48019045

http://stackoverflow.com/comment/83218610
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48120541
has text: @EliasUhalde yw~ You can consider accept and upvote for those answer you like . :-)

http://stackoverflow.com/a/48139042
answers question: http://stackoverflow.com/q/48138778
has comment: http://stackoverflow.com/comment/83255961
accepted answer of: http://stackoverflow.com/q/48138778
type: AcceptedAnswer
score: 0
has body: To get the value of the pixel you could use PIL and you could use a for loop and append a tuple of the x and y coordinate like this: from PIL import Image pixels = [] i = Image.open("image.jpg") p = i.load() for x in range(128): for y in range(128): pixels.append(p[x,y]) #gets the RGB value this would work for the whole image for those blocks you could just add an extra loop from PIL import Image pixels = [] i = Image.open("image.jpg") p = i.load() for b in range(4): block = [] for x in range(32): for y in range(32): block.append(p[x,y]) #do something with pixels from block edit: If you want to use a grayscale image you should do this: from PIL import Image pixels = [] i = Image.open("image.jpg").convert("LA") p = i.load() for b in range(4): block = [] for x in range(32): for y in range(32): block.append(p[x,y][0]) #do something with the pixels from the block the first int in the tuple is the grayscale 0 (black) to 255 (white) the second int is the alpha but my guess would be that you don't use alpha in a grayscale image
type: Answer

http://stackoverflow.com/q/48126003
type: UnansweredQuestion
tagged with: python
has title: No module named fragbuilder, Import error?
answer count: 0
type: Question
tagged with: python-2.7
score: 0
tagged with: python-import
has comment: http://stackoverflow.com/comment/83229034
has body: Past two days I am trying to solve one problem and I did every thing to resolve this problem. there is a package available. called "fragbuilder". https://github.com/jensengroup/fragbuilder I have used this package inside an Django Application. As per the installation instruction I have installed this package. How to use 1) Clone fragbuilder from this repository git clone https://github.com/andersx/fragbuilder 2) Export the frabuilder directory to your PYTHONPATH eg: export PYTHONPATH=/home/andersx/dev/fragbuilder:$PYTHONPATH 3) In your Python: import fragbuilder This method work for me and when I use my Django Application I am able to run this application successfully. But when I deploy this application on apache2 server either with native or virtualenv python installation, it shows error like given bellow: ImportError at /Pep_Des/ No module named fragbuilder Request Method: GET Request URL: http://172.16.16.46/Pep_Des/ Django Version: 1.8 Exception Type: ImportError Exception Value: No module named fragbuilder Exception Location: /home/jai/myproject/Peptide_Descriptor/dis_str_gen.py in &lt;module&gt;, line 4 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/jai/myproject', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/local/lib/python2.7/dist-packages/geoplotlib-0.3.2-py2.7.egg', '/usr/local/lib/python2.7/dist-packages/virtualenv-15.1.0-py2.7.egg', '/usr/local/lib/python2.7/dist-packages/sklearn_theano-0.0.1-py2.7.egg', '/usr/local/lib/python2.7/dist-packages/Theano-0.9.0-py2.7.egg', '/usr/local/lib/python2.7/dist-packages/progress-1.3-py2.7.egg', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/wx-3.0-gtk2', '/usr/l…
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83229501

http://stackoverflow.com/comment/83223875
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48122798
has text: I'm using Python version 3.6.2, and the system is 64 bit (MacBook Air).

http://stackoverflow.com/comment/83021910
type: Comment
comment on: http://stackoverflow.com/q/48025614
score: 0
type: QuestionComment
has text: As I cannot take a closer look on movies_review, what kind of formatting is expected? In the tutorial they just load them in and made the training and test dataset

http://stackoverflow.com/a/75017962
upvote count: 1
answers question: http://stackoverflow.com/q/48100939
downvote count: 0
type: Answer
has body: Let's say that you want to train your scikit-learn model and you want to be able to store the warnings (if any). Let's say that you fit the model as follows: clf.fit(X_train, y) If you want to catch the warning. Then you can run the model: with warnings.catch_warnings(record=True) as caught_warnings: clf.fit(X_train, y) Finally, you can get the warnings by iterating the caught_warnings as follows: for warn in caught_warnings: print(warn)
score: 1

http://stackoverflow.com/comment/83599401
comment on: http://stackoverflow.com/q/48141097
type: Comment
type: QuestionComment
has text: I sniped the form out of python documentation, and added fake values that conformed to the example.
score: 0

http://stackoverflow.com/a/48171911
has comment: http://stackoverflow.com/comment/83331416
type: Answer
has comment: http://stackoverflow.com/comment/83325955
has comment: http://stackoverflow.com/comment/83324378
has comment: http://stackoverflow.com/comment/83563175
has comment: http://stackoverflow.com/comment/83328545
has comment: http://stackoverflow.com/comment/83328483
has comment: http://stackoverflow.com/comment/83330526
has comment: http://stackoverflow.com/comment/83326474
has comment: http://stackoverflow.com/comment/83327701
has comment: http://stackoverflow.com/comment/83331044
has comment: http://stackoverflow.com/comment/83324991
has comment: http://stackoverflow.com/comment/83323930
has comment: http://stackoverflow.com/comment/83524920
has comment: http://stackoverflow.com/comment/83324040
has comment: http://stackoverflow.com/comment/83325780
has comment: http://stackoverflow.com/comment/83324479
has comment: http://stackoverflow.com/comment/83325339
has comment: http://stackoverflow.com/comment/83327882
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83324409
has comment: http://stackoverflow.com/comment/83324501
accepted answer of: http://stackoverflow.com/q/48171679
has comment: http://stackoverflow.com/comment/83328500
answers question: http://stackoverflow.com/q/48171679
has body: For the requests library in python, the data object takes a python dict object, not a JSON string. If you were to edit your code to: import requests import json url = "http://172.125.169.21/api/user/login" payload = {"name": "test5", "password": "Hello123"} headers = {'Content-Type': "application/json"} response = requests.request("POST", url, json=payload, headers=headers) # the json parameter should handle encoding for you print(response.text) print(response.headers) Cookies are available to you in the cookies parameter of the response object. See the requests documentation for more information. print(json.dumps(response.cookies, separators=(",",":"), indent = 4)) This should pretty print the cookie(s) you've received. You can use requests' session handling abilities or a variable to store this information, however you choose. We'll save these cookies to a requests cookiejar: cookies = response.cookies and we'll use those cookies in the authorization check or any other requests: auth_check_url = "172.125.169.21/api/user/checkLogin" response = requests.get(auth_check_url, cookies=cookies) print(response.text)
has comment: http://stackoverflow.com/comment/83325950

http://stackoverflow.com/q/48090962
answer count: 1
score: 0
has body: On this website, I want to find the wheel file of opencv-python. The version I want is "opencv_python-3.3.1+contrib-cp35-cp35m-win_amd64.whl", but this website is updated. I can't find it. How can I find the old wheel file?
has comment: http://stackoverflow.com/comment/83156812
has answer: http://stackoverflow.com/a/48091639
accepted answer: http://stackoverflow.com/a/48091639
has title: How can I find the old wheel file of opencv-python 3.3.1 on this website?
favorite count: 0
has comment: http://stackoverflow.com/comment/83156877
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/83156913
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83156970
type: Question

http://stackoverflow.com/q/48062237
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83101353
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/83102354
has title: Adding cookie data into a requests.urlretrieve
score: 2
type: AnsweredQuestion
tagged with: cookies
accepted answer: http://stackoverflow.com/a/48064691
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/48064691
has comment: http://stackoverflow.com/comment/83098063
has body: i am trying to download a .torrent file from a password protected site. I have managed to get to the site using cookies like so: cookies = {'uid': '232323', 'pass': '31321231jh12j3hj213hj213hk', '__cfduid': 'kj123kj21kj31k23jkl21j321j3kl213kl21j3'} try: # read site content read = requests.get(s_string, cookies=cookies).content except RequestException as e: raise print('Could not connect to somesite: %s' % e) soup = BeautifulSoup(read, 'html.parser') With this above code i get access to the site and scrape the data i need. With the scraped data i build a link to a .torrent file, which i then want to download, but this is where i am stuck. Here is what im trying right now: (cookie data not real obviously, like its not in above code either) cookies = {'uid': '232323', 'pass': '31321231jh12j3hj213hj213hk', '__cfduid': 'kj123kj21kj31k23jkl21j321j3kl213kl21j3'} # construct download URL torrent_url = ('https://www.somesite.com/' + torrent_url) # for testing purposes DELETE! print('torrent link:', torrent_url) # download torrent file into a folder filename = torrent_url.split('/')[-1] save_as = 'torrents/' + filename + '.torrent' try: r = request.urlretrieve(torrent_url, save_as, data=cookies) print("Download successful for: " + filename) except request.URLError as e: raise print("Error :%s" % e) This code would work without the cookies on a normal site, but this .torrent file im trying to get is behind a passworded/captchaed site, so i need to use cookies to scrape it. So question is, what am i doing wrong here? without data=cookies i get http 404 error and with the data=cookies i get the following error: File "/usr/lib/python3.6/http/client.py", line 1064, in _send_output + b'\r\n' TypeError: can't concat str to bytes </error> ps. before anyone asks, yes im 100% sure the torrent_url is correct, i have it printed and manually copy/pasting it into my own browser promps the download window for the .torrent file in question EDIT: try: read = requests.session().get(torrent_url…
tagged with: urlretrieve
has comment: http://stackoverflow.com/comment/83098604
has comment: http://stackoverflow.com/comment/83098231
answer count: 1

http://stackoverflow.com/comment/83113188
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48069555
has text: I don't see a user, password in your connection string, "dialect+driver://username:password@host:port/database"
score: 0

mlab
tags question: http://stackoverflow.com/q/48059662
type: Tag
tag name: mlab

http://stackoverflow.com/a/48128637
answers question: http://stackoverflow.com/q/48127152
has body: You mention an excel file, but your code seems to expect a text file (maybe this is the problem?) of the following format: country name 1, population 1, phone number 1 country name 2, population 2, phone number 2 ... country name N, population N, phone number N and then indeed it sums populations, using the the condition in the "if" statement. I, btw, don't understand the motivation for the statement following "else".
has comment: http://stackoverflow.com/comment/83239330
score: 0
type: Answer

http://stackoverflow.com/a/48018502
answers question: http://stackoverflow.com/q/48018287
has body: Instead of actually reopening and reading the log file, you can just tail the file. If you are not familiar with the Unix tail command, read here. The -f flag is commonly used for file monitoring. I am sure there are lots of implementations in Python.
score: 0
type: Answer

http://stackoverflow.com/comment/83097414
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48062326
type: AnswerComment
has text: Yes, it is possible, give me some time.

http://stackoverflow.com/a/48063492
has comment: http://stackoverflow.com/comment/83103875
score: 1
has body: If I could understand you properly then the below code will get you there: from bs4 import BeautifulSoup import requests dict_val={} res = requests.get("http://idg.receita.fazenda.gov.br/orientacao/tributaria/cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/dados-abertos-do-cnpj") soup = BeautifulSoup(res.text, "lxml") table = soup.select("table.plain")[0] for items in table.select("tr"): data = [[item.text,item['href']] for item in items.select(".external-link")] for data_dict in data: dict_val[data_dict[0]] = data_dict[1] print(dict_val) Partial output: {'Alagoas': 'http://idg.receita.fazenda.gov.br/orientacao/tributaria/cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/consultas/download/F.K03200UF.D71214AL', 'Pará': 'http://idg.receita.fazenda.gov.br/orientacao/tributaria/cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/consultas/download/F.K03200UF.D71214PA',
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83103420
accepted answer of: http://stackoverflow.com/q/48063165
answers question: http://stackoverflow.com/q/48063165
type: Answer

http://stackoverflow.com/q/48112466
downvote count: 1
has comment: http://stackoverflow.com/comment/83207115
has title: loop through peewee results in flask
tagged with: peewee
has answer: http://stackoverflow.com/a/48116662
has comment: http://stackoverflow.com/comment/83208979
has comment: http://stackoverflow.com/comment/83209575
has comment: http://stackoverflow.com/comment/83206450
has comment: http://stackoverflow.com/comment/83206503
has comment: http://stackoverflow.com/comment/83209069
tagged with: flask
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83208866
has comment: http://stackoverflow.com/comment/83205473
has comment: http://stackoverflow.com/comment/83209141
favorite count: 0
accepted answer: http://stackoverflow.com/a/48116662
has body: based on this reply: cursor = db.execute_sql('select * from tweets;') for row in cursor.fetchall(): print row cursor = db.execute_sql('select count(*) from tweets;') res = cursor.fetchone() print 'Total: ', res[0] from: Python Peewee execute_sql() example how to take it to flask app and then display in a webpage? is this correct: model.py def get_statistics(): cursor = finDB.execute_sql('CALL Allstatistics;') for row in cursor.fetchall(): return row app.py @app.route("/finance") def finance(): stats = model.get_statistics() return render_template('/finance.html', stats=stats) but how to display it in a table?
type: Question
linked to: http://stackoverflow.com/q/18500956
upvote count: 1
tagged with: python
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/83208821

http://stackoverflow.com/comment/83073097
type: Comment
type: QuestionComment
has text: @WilliamPursell It's actually a pythons script that's generating the list but then it's running the command as a bash script. I profiled it at the vast majority of time is consumed by the sed execution itself.
comment on: http://stackoverflow.com/q/48050639
score: 0

http://stackoverflow.com/comment/83139353
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48081813
has text: Can you provide the output of this query?

http://stackoverflow.com/comment/83164281
comment on: http://stackoverflow.com/q/48094708
type: Comment
type: QuestionComment
has text: Sorry Van Peer, should have made that clearer. If present in both lists, then it should show the first list it found in. Lafexlos, it was a typo - thanks for pointing out, will fix now
score: 1

http://stackoverflow.com/comment/83410649
type: AnswerComment
comment on: http://stackoverflow.com/a/48214366
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ No, not really. FWIK, the sparse types were introduced in pandas 0.16 (as I remember). I've been heavily using `SparseDataFrame` without much issues, but I was using old versions of pandas. It seems that only the new versions have a lot of critical bugs.
score: 0

http://stackoverflow.com/comment/83024485
type: QuestionComment
comment on: http://stackoverflow.com/q/48026525
has text: it still doesn't like it :( keep getting keyError: 'department' print(df.set_index('department').values.ravel().tolist())
score: 0
type: Comment

http://stackoverflow.com/comment/83148457
has text: value_counts() just gives 1 corresponding to the event_names.
comment on: http://stackoverflow.com/a/48086669
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48099764
has body: I am trying to get rpy2 to install from source on Linux running on pythonanywhere with the follow: tar -xzf rpy2-2.9.1.tar.gz cd rpy2-2.9.1 python3.6 setup.py build install The problem is I don't have admin rights and the default version of R is too old (R version 3.0.2 (2013-09-25)) for what I need. I therefore have installed a local version of R by following the these steps: downloaded the tar.gz of the development version of R from : ftp://ftp.stat.math.ethz.ch/Software/R/ uncompress it to /home/{username}/R changed into the uncompressed directory /home/{username}/R/R-devel run "./configure" run "make" I can now start R by executing /home/{username}/R/R-devel/bin/R and my R library is located /home/{username}/R/R-devel/library. I am not sure how to set these paths so that python will know where my R installation is when I run 'python3.6 setup.py build install' in the rpy2 package directory. The rpy2 documentation says that you can pass the following parameter into build: --r-home, --r-home-lib, and --r-home-modules. I have yet been successful at doing this. As far as I can tell, these parameters are deprecated. Any help getting this to work is appreicated. Thanks! Here is some information about the Linux distribution on Pythonanywhere. lsb_release --all No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 14.04.5 LTS Release: 14.04 Codename: trusty
tagged with: pythonanywhere
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83256877
type: Question
has title: Install rpy2 on custom R location (Linux)
has comment: http://stackoverflow.com/comment/83291436
tagged with: rpy2
tagged with: http://stackoverflow.com/tag/r
score: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/83205205

http://stackoverflow.com/a/48130441
accepted answer of: http://stackoverflow.com/q/48129540
answers question: http://stackoverflow.com/q/48129540
score: 0
type: AcceptedAnswer
type: Answer
has body: This way I think: First change date format to yyyy-mm-dd in the database Put dates that user wants in an array (y_array) and loop through that array (remember to put every day in it - if user asked from 1.1.2018 to 3.1.2018 you have to put 2018-01-01, 2018-01-02 and 2018-01-03 etc.) in that loop execute following sql: SELECT sum(quantity) sum_quantity FROM hirers WHERE item_id= x and y between start_date and end_date keep maximum value of sum_quantity in a variable in whole loop after the loop you will have maximum quantity of items rented for one day between days user selected to rent

http://stackoverflow.com/comment/83175845
has text: I think you have the desired answer using np.triu. +1
type: Comment
comment on: http://stackoverflow.com/a/48099837
score: 0
type: AnswerComment

http://stackoverflow.com/q/48043033
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48043158
has title: Function returns None despite values not being None
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17974383
tagged with: python
has answer: http://stackoverflow.com/a/48043065
has body: I am writing a lokta volterra algorithm in Python. I've got the following error File "abeille.py", line 73, in affichage_Lotka_Volterra_TL T,L,Y=Lotka_Volterra(l_0,y_0,tmin,tmax,h) TypeError: 'NoneType' object is not iterable and here is the code import numpy as np import matplotlib.pyplot as plt a,b,c,d=1.5,0.05,0.48,0.05 '''a=taux de reproduction des proies (constant, indépendant du nombre de prédateurs) b=taux de mortalité des proies dû aux prédateurs rencontrés c=taux de mortalité des prédateurs (constant, indépendant du nombre de proies) d=taux de reproduction des prédateurs en fonction des proies rencontrées et mangées''' def lapin(l,y): return a*l-b*l*y def lynx(l,y): return d*l*y-c*y def Lotka_Volterra(l_0,y_0,tmin,tmax,h): liste_t=[0] liste_l=[l_0] liste_y=[y_0] t=tmin dy=y_0 dl=l_0 while t&lt;=tmax: t+=h liste_t.append(t) dl+=(a*dl-b*dl*dy)*h dy+=(d*dl*dy-c*dy)*h liste_l.append(dl) liste_y.append(dy) return liste_t,liste_l,liste_y def affichage_Lotka_Volterra_TL(l_0,y_0,tmin,tmax,h): '''Population de lièvres en fonction du temps''' T,L,Y=Lotka_Volterra(l_0,y_0,tmin,tmax,h) plt.plot(T,L) plt.title('Population de lièvres au cours du temps\nConditions initiales : 4 kilolièvres pour 10 lynx sur une durée de 50 ans') plt.xlabel('Temps d-étude (en année)') plt.ylabel('L = Population de lièvres (en kilo)') plt.show() affichage_Lotka_Volterra_TL(4,10,0,50,0.0005) def affichage_Lotka_Volterra_TY(l_0,y_0,tmin,tmax,h): '''Population de lynx en fonction du temps''' T,L,Y=Lotka_Volterra(l_0,y_0,tmin,tmax,h) plt.plot(T,Y) plt.title('Population de lynx au cours du temps\nConditions initiales : 4 kilolièvres pour 10 lynx sur une durée de 50 ans') plt.xlabel('T = Temps d-étude (en année)') plt.ylabel('Y = Population de lynx (en unité)') plt.show() def affichage_Lotka_Volterra_YL(l_0,y_0,tmin,tmax,h): '''Population de lynx en fonction de la population de lièvres''' T,L,Y=Lotka_Volterra(l_0-2,y_0-2,tmin,tmax,h) plt.plot(L,Y, label="L0=2 et Y0=8") T,L,Y=Lotka_Volterra(l_0,y_0…
type: Question
has comment: http://stackoverflow.com/comment/83056799
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83056793

http://stackoverflow.com/comment/101369297
type: Comment
comment on: http://stackoverflow.com/a/57436479
has text: This seems to be so automatic and hand-free in Python 3. We are still using Python 2.7 and I'll try the same.
type: AnswerComment
score: 0

http://stackoverflow.com/q/48052844
tagged with: mean
has comment: http://stackoverflow.com/comment/83078262
has comment: http://stackoverflow.com/comment/83078640
tagged with: statistics
has body: Let's say I have a python list implementation such as &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; lst = [-1.0, 0.0, 1.0] &gt;&gt;&gt; np.std(lst) 0.81649658092772603 &gt;&gt;&gt; np.mean(lst) 0.0 Thus, the standard deviation of above iterable is 0.8164 and mean is 0.0. Now let's say I have an incoming variable 0.5 which I would like to append to this list. &gt;&gt;&gt; incoming_variable = 0.5 &gt;&gt;&gt; lst.append(incoming_variable) &gt;&gt;&gt; print(lst) [-1.0, 0.0, 1.0, 0.5] &gt;&gt;&gt; Now the mean and standard deviation have obviously changed &gt;&gt;&gt; np.std(lst) 0.73950997288745202 &gt;&gt;&gt; np.mean(lst) 0.125 &gt;&gt;&gt; What I want is a method to tweak that incoming variable value such that even after appending to the list, the standard deviation and mean remains 0.8164 and 0.0 respectively. Note I am only allowed to change the value of the incoming variable and not the initial values in the list.
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83078196
has comment: http://stackoverflow.com/comment/83078354
type: Question
tagged with: math
tagged with: standard-deviation
score: 0
has title: Achieving desired standard deviation and mean by tweaking last element of iterable

http://stackoverflow.com/comment/88492182
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48078051
has text: I have the same issue. I used this guide linked below to correctly set the severity of the messages, but I too get a set of duplicates with severity one level higher: https://medium.com/retailmenot-engineering/formatting-python-logs-for-stackdriver-5a5ddd80761c

http://stackoverflow.com/comment/83245378
score: 1
comment on: http://stackoverflow.com/q/48134055
type: QuestionComment
has text: What get's `return`ed if the execution flows through your `if` block instead of your `elif` block? (Keeping in mind that if nothing is explicitly returned then `None` is returned)
type: Comment

http://stackoverflow.com/q/48069013
tagged with: eval
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48069133
type: Question
tagged with: django
tagged with: python
answer count: 1
tagged with: django-templates
score: 0
has title: List in template tag used in javascript file
has body: As title say I want to use list from views.py to javascript file. I read this topic, but in my case it doesn't work: link My views.py: ... arr = ['first', 'second', 'third'] return render(request, "something.html",{"array": arr}) ... something.html: ... &lt;script&gt; array_js = eval(""); &lt;/script&gt; &lt;script src="{% whatever.js %}"&gt;&lt;/script&gt; ... I am using array_js in whatever.js file. It's works fine, but I am using eval function. I don't want to use it, but I don't know how to make it work without eval function. I am beginner, so please be patient. Thank You
accepted answer: http://stackoverflow.com/a/48069133
linked to: http://stackoverflow.com/q/41678583
tagged with: javascript

http://stackoverflow.com/comment/139670795
type: Comment
has text: For those coming from dnspython3 read https://pypi.org/project/dnspython3/
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/75616696

http://stackoverflow.com/comment/83028529
has text: where is your ajax implementation?
type: Comment
comment on: http://stackoverflow.com/q/48029111
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83150074
comment on: http://stackoverflow.com/q/48086951
score: 0
has text: Just skip the header from the file (with `next` or some sort of logic) and insert the replacement text in the stream.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/95844498
type: AnswerComment
score: 0
type: Comment
has text: @RThompson See my previous comment. Instead of maxing the min and max of the identity line depend on the *data*, just draw the line between the min and max of the *axes*. As in, `mn = min(plt.gca().axis())` and `mx = max(plt.gca().axis())`.
comment on: http://stackoverflow.com/a/48122198

http://stackoverflow.com/q/48124389
linked to: http://stackoverflow.com/q/40006395
tagged with: pyspark
answer count: 1
tagged with: apache-spark
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48128037
upvote count: 2
tagged with: python
has body: I have some sensor data that is stored in a table by channel name, rather that sensor name (this is to avoid having very wide tables owing to the fact that many sensors are only used on a few devices - the job for sparse columns, I know, but I am simply a user of the data). Something like this: from functools import reduce import numpy as np import pandas as pd np.random.seed(0) data_df = pd.DataFrame({ 'id': ['a']*5 + ['b']*5 + ['c']*5, 'chan1': range(15), 'chan2': np.random.uniform(0, 10, size=15), 'chan3': np.random.uniform(0, 100, size=15) }) There is a second table that tells us how to map channel names to sensor names according to the particular ID of the device: sensor_channel_df = pd.DataFrame([ {'id': 'a', 'channel': 'chan1', 'sensor': 'weight'}, {'id': 'a', 'channel': 'chan2', 'sensor': 'torque'}, {'id': 'a', 'channel': 'chan3', 'sensor': 'temp'}, {'id': 'b', 'channel': 'chan1', 'sensor': 'weight'}, {'id': 'b', 'channel': 'chan2', 'sensor': 'temp'}, {'id': 'b', 'channel': 'chan3', 'sensor': 'speed'}, {'id': 'c', 'channel': 'chan1', 'sensor': 'temp'}, {'id': 'c', 'channel': 'chan2', 'sensor': 'weight'}, {'id': 'c', 'channel': 'chan3', 'sensor': 'acceleration'}, ]) I can create a renaming dictionary like so: channel_rename_dict = sensor_channel_df.groupby('id')\ .apply(lambda grp: dict(zip(grp['channel'], grp['sensor'])))\ .to_dict() Then rename all the columns with a further groupby/apply: data_df.groupby('id')\ .apply(lambda group: group.rename(columns=channel_rename_dict[group.name]))\ .reset_index(level=0, drop=True) We get a result like this: acceleration id speed temp torque weight 0 NaN a NaN 8.712930 5.488135 0.000000 1 NaN a NaN 2.021840 7.151894 1.000000 2 NaN a NaN 83.261985 6.027634 2.000000 3 NaN a NaN 77.815675 5.448832 3.000000 4 NaN a NaN 87.001215 4.236548 4.000000 5 NaN b 97.861834 6.458941 NaN 5.000000 6 NaN b 79.915856 4.375872 NaN 6.000000 7 NaN b 46.147936 8.917730 NaN 7.000000 8 NaN b 78.052918 9.636628 NaN 8.000000 9 NaN b 11.827443 3…
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48128037
type: Question
tagged with: apache-spark-sql
has title: How can I rename columns by group/partition in a Spark Dataframe?

http://stackoverflow.com/comment/83032876
type: AnswerComment
comment on: http://stackoverflow.com/a/48030727
type: Comment
has text: Your second scenario is completely wrong. If `A` didn't implement `func`, then `B`'s version would be called. The MRO for `C` is `C, A, B, Z`. `Z` will never appear before `B` in any MRO since it's it is `B`'s parent.
score: 0

http://stackoverflow.com/comment/88029431
has text: Ouh, thanks a lot. I missed that typo. After fixing it `pytest -pyargs test_rc_slam_ros` works perfectly fine as well...
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48350323
type: Comment

http://stackoverflow.com/comment/83318547
comment on: http://stackoverflow.com/q/48169582
score: 1
type: Comment
type: QuestionComment
has text: Actually, I get `ord` as `8206`, or `\u200e` (using Python 3), and the `repr` of the string shows `\xe2\x80\x8e` in Python 2, i.e. seems to be a multi-byte unicode character.

http://stackoverflow.com/a/48102726
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48102422
has body: In SAS data want; format A B C D $2.; format combination $8.; do aa=1 to 2; A = catt("A",aa); do bb=1 to 3; B = catt("B",bb); do cc=1 to 3; C = catt("C",cc); do dd=1 to 5; D = catt("D",dd); combination=catt(A,B,C,D); output; end; end; end; end; drop aa bb cc dd; run;
accepted answer of: http://stackoverflow.com/q/48102422

http://stackoverflow.com/comment/83111979
has text: Have a look at the [matplotlib gallery](https://matplotlib.org/gallery.html), it'll probably have something similar to what you need.
type: Comment
comment on: http://stackoverflow.com/q/48068761
score: 0
type: QuestionComment

http://stackoverflow.com/comment/94019501
comment on: http://stackoverflow.com/q/48133838
score: 0
has text: You should consider accepting the answer @mikhail provided.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/59229406
downvote count: 0
type: Answer
has body: I struggled to find a solution because I was working with a dataset with columns in Spanish. As soon as I translated them to "year" "month" and "day" and "hour", the conversion worked perfectl
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48155787

http://stackoverflow.com/q/48107849
has comment: http://stackoverflow.com/comment/83191321
has comment: http://stackoverflow.com/comment/83191220
has body: i am trying to understand how this code works behind the scene , help appreciated explain this part please: MAX = ACCOUNT if len(ACCOUNT) &gt; len(MAX) else MAX ACCOUNT = ACCOUNT + c if c &gt;= ACCOUNT[-1] else c ================================================ S = 'azcbobobegghaklbob' ACCOUNT, MAX = S[0], "" for c in S[1:] + " ": MAX = ACCOUNT if len(ACCOUNT) &gt; len(MAX) else MAX ACCOUNT = ACCOUNT + c if c &gt;= ACCOUNT[-1] else c print('Longest substring in alphabetical order is:', MAX)
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83191258
has answer: http://stackoverflow.com/a/48108051
type: Question
score: 0
answer count: 1
tagged with: edx
accepted answer: http://stackoverflow.com/a/48108051
tagged with: longest-substring
has title: this code in python about finding the longest sub-string , i need explaination
tagged with: python

http://stackoverflow.com/q/48109737
has body: I have written this small code in Python. It should print every character in a string with a small sleeptime between them... import time, sys def writeText(string, t): i = 0 while i &lt; len(string): sys.stdout.write(string[i]) time.sleep(float(t)) i += 1 writeText("Hello World", 0.5) but it only prints the whole string after 0.5 seconds... I often have this issue but I haven't found a solution yet.
downvote count: 1
type: Question
score: 1
tagged with: sleep
has answer: http://stackoverflow.com/a/48109785
tagged with: python-2.7
has title: Python time.sleep method not working properly
answer count: 2
duplicate of: http://stackoverflow.com/q/34365107
favorite count: 0
linked to: http://stackoverflow.com/q/9246076
possible better answer: http://stackoverflow.com/a/48109797
accepted answer: http://stackoverflow.com/a/48109785
tagged with: python
duplicate of: http://stackoverflow.com/q/9246076
has answer: http://stackoverflow.com/a/48109797
type: AnsweredQuestion
upvote count: 2
linked to: http://stackoverflow.com/q/21886233

http://stackoverflow.com/comment/109144255
type: Comment
score: 2
comment on: http://stackoverflow.com/a/48135838
type: AnswerComment
has text: I searched for hours and hours how to make my python code work on vscode, your answer took me all out, thank you so much!

http://stackoverflow.com/q/48083857
tagged with: pygame
has title: Pygame display image in while true loop memory problems
tagged with: memory-management
downvote count: 0
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48098405
accepted answer: http://stackoverflow.com/a/48098405
has comment: http://stackoverflow.com/comment/83155128
has comment: http://stackoverflow.com/comment/83154998
type: Question
has comment: http://stackoverflow.com/comment/83160317
upvote count: 1
answer count: 1
has body: I have a picture that changes constantly. I would like to present these in pygame, like a video. The memory is full and will not be released. Where is the mistake? def showLive(file): picture = pygame.transform.scale(pygame.image.load(file),(width,high)) main_surface.blit(picture, (0, 0)) pygame.display.flip() while True: #takePicture take always a new picture takePicture("test.jpeg") showLive("test.jpeg") Thanks a lot. Update: 04.01.2018 I use https://github.com/alexdu/piggyphoto. To take a preview from my dslr. When I start the program, then I see the "live view". The memory is getting fuller. After about 8 minutes it is full on the Raspberry Pi 3b. import piggyphoto, pygame def showLive(file): C.capture_preview(file) picture = pygame.transform.scale(pygame.image.load(file),(width,high)) display.blit(picture, (0, 0)) pygame.display.flip() width = 1275 high = 850 file = 'preview.jpg' C = piggyphoto.camera() C.leave_locked() C.capture_preview(file) global display pygame.init() picture = pygame.image.load(file) display = pygame.display.set_mode((width,high),pygame.FULLSCREEN) pygame.mouse.set_visible(False) while True: showLive(file)
favorite count: 0
has comment: http://stackoverflow.com/comment/83154785
tagged with: python

http://stackoverflow.com/comment/83153649
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48089161
has text: @NimishBansal I am trying to verify an element exists inside a webpage. But you will need to scroll down the webpage to verify the element exists. So I'm trying to scroll down the page to verify the element exists.
score: 0

http://stackoverflow.com/comment/83015741
has text: Thanks for that but it still has values like 254,253(not a big problem). What file format is good for binary image?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48023161

http://stackoverflow.com/comment/83304404
type: QuestionComment
has text: @e.s. Is it possible to pass article instead of list-of-keywords or both article and pre-defined list of keywords to worker method?
comment on: http://stackoverflow.com/q/48162230
score: 0
type: Comment

http://stackoverflow.com/q/48128520
upvote count: 0
has title: Python float to integer error
has answer: http://stackoverflow.com/a/48128554
favorite count: 0
possible better answer: http://stackoverflow.com/a/48128591
has answer: http://stackoverflow.com/a/48128591
tagged with: python
has body: I'm having a hard time understanding this: &gt;&gt;&gt; 52920*(15303855351918+15303855298999)/2.0 == 809880023823263820 False &gt;&gt;&gt; 52920*(15303855351918+15303855298999)/2.0 == 809880023823263820.0 True &gt;&gt;&gt; (52920*(15303855351918+15303855298999)/2.0) - 809880023823263820 0.0 &gt;&gt;&gt; int(52920*(15303855351918+15303855298999)/2.0) 809880023823263872 &gt;&gt;&gt; int(52920/2.0)*(15303855351918+15303855298999) 809880023823263820 Running Python 3.5.3 The number 809880023823263820 is obviously representable as an integer since it's the sum of an a.p. series with all integer parameters. What is the explanation for the 1st and 4th computations?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48128554
has comment: http://stackoverflow.com/comment/83233651
tagged with: floating-point
downvote count: 1
type: Question
score: -1
tagged with: type-conversion
tagged with: int
answer count: 2

http://stackoverflow.com/q/48072098
favorite count: 0
has answer: http://stackoverflow.com/a/48073492
has body: I'm using a python script to get realtime updates from an orderbook on the cryptocurrency exchange Poloniex. Currently it prints the information pushed by the websocket to stdout, what do I need to do to print it into a file instead? I'm using python-2.7, thanks in advance! Below is the script I'm using: #!/usr/bin/python import sys, getopt import websocket import thread import time import json try: opts, args = getopt.getopt(sys.argv[1:], 'p:', ['parity=']) except getopt.GetoptError: sys.exit(2) for opt, arg in opts: if opt in ('-p', '--paridade'): parity = arg else: sys.exit(2) data = {'command':'subscribe','channel':''+parity+''} def on_message(ws, message): print(message) def on_error(ws, error): print(error) def on_close(ws): print("### closed ###") def on_open(ws): print("ONOPEN") def run(*args): ws.send(json.dumps(data)) while True: time.sleep(1) ws.close() print("thread terminating...") thread.start_new_thread(run, ()) if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("wss://api2.poloniex.com/", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()
tagged with: python
has comment: http://stackoverflow.com/comment/89741945
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48073492
type: Question
score: 4
tagged with: poloniex
upvote count: 4
tagged with: python-2.7
has title: How to write websocket push api output to text file?
downvote count: 0
answer count: 1
tagged with: websocket

http://stackoverflow.com/comment/123181945
comment on: http://stackoverflow.com/a/48057734
score: 0
type: AnswerComment
type: Comment
has text: Yes you need to remove the token.pickle when ever you make any changes to the authorization this will cause the app to request access again.

http://stackoverflow.com/q/48025016
downvote count: 0
has comment: http://stackoverflow.com/comment/83019408
favorite count: 0
tagged with: python
tagged with: regex
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48025083
type: UnansweredQuestion
has title: Regular Expression Matching Stock Ticker
upvote count: 5
has body: I'm having trouble matching stock tickers in a string of text. I want a regular expression to match a space , 3 uppercase letters, and finally a space, period, OR question mark. Below is the sample pattern that I created. &gt; `example = 'These are the tickers that I am trying to find: FAB. APL APL? GJA ADJ AKE EBY ZKE SPR TYL' re.findall('[ ][A-Z]{3}[ .!?]',example)` The regular expression misses quite a few of the matches.
has answer: http://stackoverflow.com/a/48025138
type: Question
answer count: 2
score: 5

http://stackoverflow.com/comment/83044092
has text: nopes it didnt, i was wandering if we could introduce a new IntVar and then in the entry use text variable but its giving the same old value, i hope you understand
score: 0
comment on: http://stackoverflow.com/q/48036468
type: Comment
type: QuestionComment

http://stackoverflow.com/a/71514511
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48053764
score: 1
downvote count: 0
has body: Refresh Cliente Secret File on https://console.cloud.google.com/apis/credentials and delete token pickle folder

http://stackoverflow.com/q/48126065
tagged with: python
answer count: 0
upvote count: 1
type: Question
tagged with: python-imaging-library
tagged with: algorithm
score: 1
has title: Python/NumPy - Tail letter placement algorithm
tagged with: numpy
has body: I'm currently trying to write a program that correctly centers handwritten letters in a similar fashion to Microsoft Word. Using a standard handwriting grid for comparison, the bottom of the letter is placed right on the lowest gridline for most letters: Image. However, there are five tail letters where this doesn't apply: g, j, p, q, and y. For these letters, the bottom of the letter goes below the lowest gridline: Image. I want to find the distance between the bottom of the letter and the lowest gridline for these tail letters. The letter images themselves don't come with gridlines drawn in, and are stored as binary numpy array-files. I need some way to algorithmically determine the vertical location of this lowest gridline, but I'm not sure where to begin.
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48052799
score: 1
tagged with: rsa
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83079722
has answer: http://stackoverflow.com/a/48052915
has comment: http://stackoverflow.com/comment/83078008
tagged with: python
tagged with: cryptography
tagged with: encryption
has comment: http://stackoverflow.com/comment/83077815
upvote count: 1
has title: RSA Encryption and decryption incorrect with large message
accepted answer: http://stackoverflow.com/a/48052915
type: Question
type: AnsweredQuestion
has body: I recently got interested in RSA and tried to implement it. This is a simplified version of my code: def egcd(a, b): if a == 0: return (b, 0, 1) else: g, x, y = egcd(b % a, a) return (g, y - (b // a) * x, x) def modinv(b, n): g, x, _ = egcd(b, n) if g == 1: return x % n p = 89 q = 107 n = p * q phi = (p - 1) * (q - 1) e = 3 d = modinv(e, phi) message = 74 encrypted = (message**e) % n decrypted = (encrypted**d) % n print(message) print(encrypted) print(decrypted) For small of message, 74 is used in this example, it works fine. However, when setting message = 120000 or any other large value, the result is as follows: 120000 147 5724 So, I entered the exact same values into an RSA calculator on this website. This also resulted in an incorrectly decrypted message. What could be the problem here? Is there a problem with the maths or is this a python problem? Thanks in advance.

http://stackoverflow.com/q/48055852
accepted answer: http://stackoverflow.com/a/48159123
has body: How do I install the Pyomo's "Cuenne" optimizer extension? I have downloaded the binaries from: https://www.coin-or.org/download/binary/Couenne/ Here is an official guide from Pyomo's site on how to solve problems, with ASL: The basic work flow that takes place above can be summarized as: Create an ASL solver plugin that uses the ipopt executable appearing in the shell search PATH. Output the Pyomo model as an NL file. Invoke the solver (which produces an SOL file). Check the solver termination condition stored in the results object. Load the solution stored in the results object into the Pyomo model.Construct a Pyomo model. Solve the PyomoRead the SOL file into a Pyomo results object. http://nbviewer.jupyter.org/github/Pyomo/PyomoGallery/blob/master/asl_io/asl_io.ipynb But it doesn't detail how to get Pyomo to recognize the Couenne solver at all.
has title: Installing Couenne solver on Python's Pymo extension
has answer: http://stackoverflow.com/a/56235975
tagged with: pyomo
type: AnsweredQuestion
score: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/56235975
favorite count: 0
type: Question
tagged with: windows
tagged with: python
tagged with: installation
upvote count: 2
has answer: http://stackoverflow.com/a/48159123
answer count: 2

http://stackoverflow.com/q/48143345
linked to: http://stackoverflow.com/q/231767
score: 0
has body: :) I'm crawling through Selenium Webdriver. If not use yield, it works fine, but When using yield, the following error occurs. What should I do? Traceback (most recent call last): File "c:\programdata\anaconda2\lib\site-packages\scrapy\utils\defer.py", line 45, in mustbe_deferred result = f(*args, **kw) File "c:\programdata\anaconda2\lib\site-packages\scrapy\core\spidermw.py", line 49, in process_spider_input return scrape_func(response, request, spider) File "c:\programdata\anaconda2\lib\site-packages\scrapy\core\scraper.py", line 146, in call_spider dfd.addCallbacks(request.callback or spider.parse, request.errback) File "c:\programdata\anaconda2\lib\site-packages\twisted\internet\defer.py", line 303, in addCallbacks assert callable(callback) this is code here : # -*- coding: utf-8 -*- workbook = xlsxwriter.Workbook('arrays.xlsx') worksheet = workbook.add_worksheet() class LgSpider(Spider): name = 'lg' allowed_domains = ['naturecollection.co.kr/product/list.jsp?cate_seq=4'] def start_requests(self): reader = csv.reader(open('urls1.csv')) for row in reader: url = row[0] # self.parse_detail(url) yield Request(url=url, callback=self.parse_detail(url)) def parse_detail(self, url): self.driver = webdriver.Chrome('/webdrivers/chromedriver') self.driver.get(url) sleep(10) sel = Selector(text=self.driver.page_source) # sleep(2) # self.logger.info('Sleeping for 2 seconds.') response = url sub_kor = sel.xpath('//meta[@property="og:title"]/@content').extract() sub_en = sel.xpath('//*[@class="section fr"]//*[@class="subTit"]/text()').extract() highlight_1 = sel.xpath('//meta[@property="og:description"]/@content').extract() main = sel.xpath('//meta[@property="og:image"]/@content').extract() category_1 = sel.xpath('//*[@id="locationArea"]/div/a/text()').extract() category_2 = sel.xpath('//*[@id="locationArea"]/strong/text()').extract() # table = sel.xpath('//*[@id="specInfoLayer"]//td').extract() noop_originpirce = sel.xpath('//*[@class="section fr"]//*[@class="realCost"]/text(…
tagged with: selenium
has answer: http://stackoverflow.com/a/48143577
has answer: http://stackoverflow.com/a/67572820
tagged with: webdriver
type: UnansweredQuestion
tagged with: yield
type: Question
answer count: 2
has title: crawling through Selenium Webdriver, (When using yield), an error occurs
tagged with: python

http://stackoverflow.com/q/48088916
score: 1
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48089338
answer count: 1
has title: Scraping result is different from inspected DOM element
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/83152392
has comment: http://stackoverflow.com/comment/83152624
tagged with: selenium
has body: I want to parse list of price in a web page using Selenium webdriver in Python. So, I try to fetch all the DOM elements using this code url = 'https://www.google.com/flights/explore/#explore;f=BDO;t=r-Asia-0x88d9b427c383bc81%253A0xb947211a2643e5ac;li=0;lx=2;d=2018-01-09' driver = webdriver.Chrome() driver.get(url) print(driver.page_source) The problem is what I got from page_source is different from what I see in the inspected element Here is the difference The difference exist inside the CTPFVNB-f-e class. In the inspected DOM element, this tag hold all the prices that I want to fetch. But, in the result of page_source, this part is missing. Could anyone tell me what is wrong with my code? Or do I need further steps to parse the list of prices?
downvote count: 0
has answer: http://stackoverflow.com/a/48089338
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/83149964
comment on: http://stackoverflow.com/a/48086145
score: 0
type: Comment
has text: Thanks, man! I'm trying both right now. I'll keep you posted. But I think this second approach it better. I think is a good way to do with every html before work with it, isn`t it?
type: AnswerComment

http://stackoverflow.com/q/48045489
tagged with: python
has body: I get the title error when I try to merge two dataframes on the left on the Name column. Here is the DataFrame.info() call on the two data frames. Int64Index: 145 entries, 1 to 162 Data columns (total 13 columns): Quarter 145 non-null float64 Time 145 non-null object Down 145 non-null float64 ToGo 145 non-null float64 Location 145 non-null object Detail 145 non-null object SEA 145 non-null float64 TAM 145 non-null float64 EPB 145 non-null float64 EPA 145 non-null float64 Win% 145 non-null float64 Name 145 non-null object Yards 145 non-null int64 dtypes: float64(8), int64(1), object(4) memory usage: 15.9+ KB None Int64Index: 1567 entries, 0 to 1566 Data columns (total 4 columns): Name 1567 non-null object Team 1567 non-null object Position 1150 non-null object Age 1567 non-null int64 dtypes: int64(1), object(3) memory usage: 61.2+ KB None And also the full traceback of the python stack. Traceback (most recent call last): File "weighted_random_forest.py", line 478, in &lt;module&gt; main() File "weighted_random_forest.py", line 473, in main game = get_third_down_conversion_rate(team, game, files) File "weighted_random_forest.py", line 339, in get_third_down_conversion_rate df = df.merge(roster, on='Name', how='left') File "/usr/local/lib/python2.7/dist-packages/pandas/core/frame.py", line 5370, in merge copy=copy, indicator=indicator, validate=validate) File "/usr/local/lib/python2.7/dist-packages/pandas/core/reshape/merge.py", line 58, in merge return op.get_result() File "/usr/local/lib/python2.7/dist-packages/pandas/core/reshape/merge.py", line 582, in get_result join_index, left_indexer, right_indexer = self._get_join_info() File "/usr/local/lib/python2.7/dist-packages/pandas/core/reshape/merge.py", line 748, in _get_join_info right_indexer) = self._get_join_indexers() File "/usr/local/lib/python2.7/dist-packages/pandas/core/reshape/merge.py", line 727, in _get_join_indexers how=self.how) File "/usr/local/lib/python2.7/dist-packages/pandas/core/reshape/merge.py", …
has comment: http://stackoverflow.com/comment/83062303
answer count: 0
linked to: http://stackoverflow.com/q/45363330
type: Question
tagged with: pandas
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83062673
has title: TypeError: type object argument after * must be an iterable, not itertools.map
favorite count: 0
has comment: http://stackoverflow.com/comment/83062414
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/83104102
score: 0
type: Comment
has text: I hate it when one-line-code shows up like this. I find it hard to read if not at least formatted correctly. You need to have all the information you need to understand the code **on screen**. Your `sorted` function takes 3 argument, and your code could gain great readibility if you would take 1 line per argument there. Your line is 152 characters long, and is BY FAR too long. The usual maximum is in-between 80 to 100. Don't you agree ? + if not for you, it is sad to teach young coders bad manners of coding right ?
comment on: http://stackoverflow.com/a/48065322
type: AnswerComment

http://stackoverflow.com/q/48163641
downvote count: 0
has answer: http://stackoverflow.com/a/73520119
tagged with: django-2.0
has answer: http://stackoverflow.com/a/70611664
upvote count: 62
has answer: http://stackoverflow.com/a/50851125
has answer: http://stackoverflow.com/a/78072700
has answer: http://stackoverflow.com/a/77801024
has answer: http://stackoverflow.com/a/75228842
has answer: http://stackoverflow.com/a/54371174
has answer: http://stackoverflow.com/a/68859388
has answer: http://stackoverflow.com/a/63976047
tagged with: pythonanywhere
answer count: 22
has answer: http://stackoverflow.com/a/73451583
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/34114427
has answer: http://stackoverflow.com/a/77110964
has answer: http://stackoverflow.com/a/64660982
has answer: http://stackoverflow.com/a/73473147
type: UnansweredQuestion
has body: It's my first time trying to deploy a Django app(django 2.0.1)(Python 3.6) to pythonanywhere, it is a simple portfolio app with no models, no bootstrap. Just Django, HTML, CSS &amp; Javascript. After pulling it from the Github repo onto pythnanywhere with their bash console, I run : python manage.py migrate &amp; was hit with this error : Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/core/management/__init__.py", line 216, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/core/management/__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 978, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 961, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 950, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 655, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 205, in _call_with_frames_removed File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site- packages/django/core/management/commands/migrate.py", line 12, in &lt;module&gt; from…
has answer: http://stackoverflow.com/a/75476027
tagged with: django
has answer: http://stackoverflow.com/a/50654136
tagged with: python
has comment: http://stackoverflow.com/comment/84600117
has comment: http://stackoverflow.com/comment/87162803
has answer: http://stackoverflow.com/a/68833003
has answer: http://stackoverflow.com/a/65604362
has title: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. (django 2.0.1)(Python 3.6)
has comment: http://stackoverflow.com/comment/83315990
has answer: http://stackoverflow.com/a/57493455
has answer: http://stackoverflow.com/a/57695682
has answer: http://stackoverflow.com/a/76396232
has answer: http://stackoverflow.com/a/48886816
type: Question
score: 62
has answer: http://stackoverflow.com/a/48168360

http://stackoverflow.com/q/48122076
type: UnansweredQuestion
has body: I am trying to create an object orientated program in Python for a whack-a-mole program. I want to keep this simple where there are just a hammer and a mole and when the hammer turtle makes contact with the mole turtle. I have created 4 classes one for Game which is the superclass, one for sprite which inherits from Turtle and one each for hammer and mole which both inherit from Sprite. What I am asking is how to instantiate the mole and hammer turtles I have made use of inheritance but want to minimize the amount of methods I am using The code I have used is import random import turtle wn=turtle.Screen() wn.addshape("moleSmall.gif") wn.addshape("Mole.gif") wn.addshape("Hammer.gif") turtle.setup(800, 600) class Game(): def __init__(self): self.score=0 self.pointsDisplay=Points() def update_score(self,x,y): self.score = self.score + 2 print("Score:", self.score) self.callDisplayScore() def decrease_score(self,x,y): self.score = self.score -1 print("Score: ", self.score) self.callDisplayScore() def callDisplayScore(self): score = self.score class Sprite(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self) self.x=0 self.y=0 crash =False self.crash=crash def randomMove(self): leftbound = -self.wn.window_width()/2 rightbound = self.wn.window_width()/2 topbound = self.wn.window_height()/2 bottombound = -self.wn.window_height()/2 rand_x = random.randint(leftbound , rightbound) rand_y = random.randint(bottombound, topbound) self.mole.setpos(rand_x,rand_y) def collisionCheck(self,turtle1, turtle2): self.crash = False turtle1X = turtle1.xcor() turtle1Y = turtle1.ycor() turtle2X = turtle2.xcor() turtle2Y = turtle2.ycor() turtle1Pos = (int(turtle1X), int(turtle1Y)) turtle2Pos = (int(turtle2X), int(turtle2Y)) if turtle1Pos == turtle2Pos or turtle1X &lt; turtle2X - 50 and \ turtle1Y &gt; turtle2Y - 50 and turtle1X &lt; turtle2X - 50 and\ turtle1Y &gt; turtle2Y + 50: self.crash = True return self.crash class Mole(Sprite): def __init__(self): Sprite.__init__(self) self.…
tagged with: python
has comment: http://stackoverflow.com/comment/83222955
answer count: 0
has title: Whack a mole Python OOP
has comment: http://stackoverflow.com/comment/83222332
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83222510
tagged with: python-turtle
has comment: http://stackoverflow.com/comment/83235481
tagged with: turtle-graphics

http://stackoverflow.com/q/48019765
has title: Stored Procedure is taking very long to complete
has comment: http://stackoverflow.com/comment/83008736
tagged with: stored-procedures
score: 0
has body: We have a csv file with 2000 rows and a database table1 about 2 million rows and another table2 with 60000 rows. We need to query from table1 based on parameters from the csv file, so each row in csv should execute one select query. Initially we tried to execute the following query within a for loop in the application: SELECT table1.c1, table1.c2, ST_Distance_Sphere(point(csv.c2[i], csv.c3[i]), point(table1.c3, table1.c4))*0.2 AS length, table1.c5 FROM table1 WHERE table1.c1 IN ( SELECT DISTINCT table2.c1 FROM table2 LEFT JOIN table2.c1=table1.c1 WHERE table2.c2=1 AND table2.c3 BETWEEN 1000 AND 2000 ) HAVING length &lt; csv.c4[i] AND table1.c5 BETWEEN date("start_date") AND date("end_date") ORDER BY table.c1 the csv.c1[i] i is actually the loop index. Because of the 2000 round trips to MySQL server, it takes a long time to complete this. It takes about 16 hours just to get through the queries. So, I wrote the SP below to avoid looping and simply call this SP so can do the looping in MySQL server: CREATE PROCEDURE sp() BEGIN DECLARE arg0 VARCHAR(255); DECLARE arg1 FLOAT; DECLARE arg2 FLOAT; DECLARE arg3 FLOAT; DECLARE cur1 CURSOR FOR SELECT * FROM csv_based_table; OPEN cur1; read_loop: LOOP FETCH cur1 INTO arg0, arg1, arg2, arg3; SELECT col0, col1, ST_Distance_Sphere(point(arg1, arg2),point(col3,col4))*2 AS length, arg0 FROM important_table1 WHERE col0 IN ( SELECT DISTINCT c0 FROM important_table2 LEFT JOIN c0 ON col0 = c0 WHERE c1=1 and c2 BETWEEN 1000 AND 2000) HAVING distance &lt; arg3 AND col5 BETWEEN date("start_date") AND date("end_date") ORDER BY arg0, col0; END LOOP; CLOSE cur1; END; So, instead of using the csv file, we create a database table for that csv file and run the above stored procedure. Problem is this turned out to be slower than the original 2000 iterations loop. In a test over 100 csv rows, for loop-based original solution finished in 317.6 seconds while the stored procedure took 321.5 seconds just for the SP itself. Why is this happening and ho…
tagged with: mysql
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83008643
has comment: http://stackoverflow.com/comment/83008600
has comment: http://stackoverflow.com/comment/83008865
answer count: 0
has comment: http://stackoverflow.com/comment/83008779
has comment: http://stackoverflow.com/comment/83009545
has comment: http://stackoverflow.com/comment/83008749
type: Question
tagged with: python

http://stackoverflow.com/comment/83134131
comment on: http://stackoverflow.com/q/48079736
type: QuestionComment
has text: You'll need to create multiple processes if your script does multiple things concurrently. It`s somewhat complex. https://docs.python.org/3/library/multiprocessing.html. You might consider using supervisor to start your servers instead, which will handle starting to services and restarting on failure as well.
score: 0
type: Comment

http://stackoverflow.com/q/48083073
has answer: http://stackoverflow.com/a/60322967
has comment: http://stackoverflow.com/comment/83141038
score: 0
has answer: http://stackoverflow.com/a/48095464
answer count: 2
linked to: http://stackoverflow.com/q/52707456
favorite count: 0
has body: While doing automation, I have to check that email which I am entering is correct one or not. Unfortunately, while creating XPath, UIAutomator is showing me the text of my email address. I want to make XPath dynamic, so, that every time, I use that XPath, It gets the text. Let us suppose: email = 'testqatp@gmail.com' and XPath is: [@text='email'] How is that gonna work?
tagged with: xpath
has title: Add variable in XPath in Python
has comment: http://stackoverflow.com/comment/83142777
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83141002
tagged with: python
tagged with: selenium
upvote count: 1
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/2960772
linked to: http://stackoverflow.com/q/30352671

http://stackoverflow.com/comment/83117688
score: 0
comment on: http://stackoverflow.com/a/48049201
type: AnswerComment
has text: @Jan Seems like multiple answers could work. Choosing just one amongst the many is a real dilemma. I feel like that would be a disservice to those who spent their time in helping me and yet did not get theirs green ticked. Is it mandatory to choose an accepted answer?
type: Comment

http://stackoverflow.com/q/48092985
has answer: http://stackoverflow.com/a/48093108
downvote count: 0
has comment: http://stackoverflow.com/comment/83160446
has comment: http://stackoverflow.com/comment/83160507
has comment: http://stackoverflow.com/comment/83160418
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48101221
has answer: http://stackoverflow.com/a/48093107
has title: Why isn't my time replacing regex working?
favorite count: 0
has comment: http://stackoverflow.com/comment/83160381
type: Question
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/7536755
accepted answer: http://stackoverflow.com/a/48093107
upvote count: 3
answer count: 3
has body: The kind of sentences expected : I will be there at 4:15 later today I will be there at 14:06 later today. Few things to notice there: 1- The hour format is 24h 2- The hour can be one letter or 2 while the minutes is always 2. 3- The time is always mid sentence . what i have tried : import re response = re.sub(r'^(([01]\d|2[0-3]):([0-5]\d)|24:00)$', '7:15', 'I will be there at `4:15` later today') I also tried this regex ^(2[0-3]|[01]?[0-9]):([0-5]?[0-9])$ and it also didn't work.
has comment: http://stackoverflow.com/comment/83160528
possible better answer: http://stackoverflow.com/a/48093108

http://stackoverflow.com/comment/115059025
has text: For me, it worked only if placed it in my unittest function before the read statement where the issue occurred.
comment on: http://stackoverflow.com/a/55411485
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/83178695
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48082725
has text: It is *extremely* unclear what behavior you desire. Please clarify your question.

http://stackoverflow.com/comment/83063335
comment on: http://stackoverflow.com/q/48040545
has text: well, serialization to a transport format is well known to be one of the bottlenecks in performance. Just how many model records are you serializing, and how deep?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83267732
type: Comment
comment on: http://stackoverflow.com/a/48143367
has text: Thank you very much for the answer. However, I got the following error when running this program `new_weight = G.nodes[ele[0]]["weight"] + ele[1] TypeError: 'method' object is not subscriptable` Can you please tell me how to fix this?
score: 0
type: AnswerComment

http://stackoverflow.com/q/48037305
type: Question
tagged with: ssh
has comment: http://stackoverflow.com/comment/83045096
tagged with: python
has comment: http://stackoverflow.com/comment/83045480
has comment: http://stackoverflow.com/comment/83045358
tagged with: python-3.x
upvote count: 1
has comment: http://stackoverflow.com/comment/83052451
type: UnansweredQuestion
has body: I'm trying to import paramiko so I can ssh to machines from my windows 10 machine using a python program. However I receive this error: Traceback (most recent call last): File "population_script.py", line 5, in &lt;module&gt; import paramiko File "C:\Users\bnbih\Envs\crossover_env\lib\site-packages\paramiko\__init__.py", line 22, in &lt;module&gt; from paramiko.transport import SecurityOptions, Transport File "C:\Users\bnbih\Envs\crossover_env\lib\site-packages\paramiko\transport.py", line 57, in &lt;module&gt; from paramiko.ed25519key import Ed25519Key File "C:\Users\bnbih\Envs\crossover_env\lib\site-packages\paramiko\ed25519key.py", line 17, in &lt;module&gt; import bcrypt File "C:\Python27\Lib\site-packages\bcrypt\__init__.py", line 23, in &lt;module&gt; from bcrypt import _bcrypt ImportError: DLL load failed: The specified module could not be found. I tried : pip install bcrypt and pip install --upgrade bcrypt
tagged with: paramiko
has comment: http://stackoverflow.com/comment/83045330
has title: How to use Paramiko with python 3.6 and windows 10?
answer count: 0
downvote count: 0
score: 1
tagged with: windows-10
favorite count: 0

http://stackoverflow.com/a/48143240
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83298243
type: Answer
has body: if entries[0][1].get() == "B": entries[0][1]['bg'] = "BLUE" or if entries[0][1].get() == "B": entries[0][1].config(bg="BLUE") See Entry.config() on effbot.org
accepted answer of: http://stackoverflow.com/q/48143147
answers question: http://stackoverflow.com/q/48143147
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/48136708
downvote count: 0
answers question: http://stackoverflow.com/q/48135843
type: Answer
upvote count: 1
has body: One very clean way to implement this is using rrule from the dateutil library. For example: &gt;&gt;&gt; from dateutil.rrule import rrule, DAILY &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; start_date = datetime.now() &gt;&gt;&gt; {d.strftime("%A"): d for d in rrule(freq=DAILY, count=7, dtstart=start_date)} which will return your desired dict object: { 'Sunday': datetime.datetime(2018, 1, 7, 17, 2, 30), 'Monday': datetime.datetime(2018, 1, 8, 17, 2, 30), 'Tuesday': datetime.datetime(2018, 1, 9, 17, 2, 30), 'Wednesday': datetime.datetime(2018, 1, 10, 17, 2, 30), 'Thursday': datetime.datetime(2018, 1, 11, 17, 2, 30), 'Friday': datetime.datetime(2018, 1, 12, 17, 2, 30), 'Saturday': datetime.datetime(2018, 1, 13, 17, 2, 30) } (Special thanks to Jon Clements for telling me about rrule)
score: 1

http://stackoverflow.com/q/48157899
tagged with: django
tagged with: python
has title: TypeError: __init__() missing 1 required positional argument: 'on_delete'
tagged with: django-models
type: Question
upvote count: 4
downvote count: 5
score: -1
has body: I'm trying to run my code and I'm getting this error: File "C:\Users\JOSHUA\Documents\ypgforum\myproject\boards\models.py", line 13, in &lt;module&gt; class Topic(models.Model): File "C:\Users\JOSHUA\Documents\ypgforum\myproject\boards\models.py", line 16, in Topic board = models.ForeignKey(Board, related_name='topics') TypeError: __init__() missing 1 required positional argument: 'on_delete' This is the models.py it pointed to: class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics') starter = models.ForeignKey(User, related_name='topics') last_updated = models.DateTimeField(auto_now_add=True)
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48158005
type: UnansweredQuestion

http://stackoverflow.com/comment/83157078
type: QuestionComment
comment on: http://stackoverflow.com/q/48057299
score: 0
type: Comment
has text: @SCB I'm trying to create a program that generates playlists in new files to be easily accessible to the user.

http://stackoverflow.com/comment/83309658
has text: `logging.error()` uses the module-level constant `logging.ERROR`, which is set to `40`.
comment on: http://stackoverflow.com/q/48165133
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48134314
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83249724
has comment: http://stackoverflow.com/comment/83251947
has comment: http://stackoverflow.com/comment/83255641
answer count: 0
has comment: http://stackoverflow.com/comment/83245987
has comment: http://stackoverflow.com/comment/83254892
has title: Recursive function on list of dictionaries print results but returns none
type: Question
tagged with: recursion
score: 0
has comment: http://stackoverflow.com/comment/83246019
has comment: http://stackoverflow.com/comment/83249539
has comment: http://stackoverflow.com/comment/83252896
has comment: http://stackoverflow.com/comment/83257672
has body: I wrote a code in order to calculate sentiment of values in a dictionary whose items came from a semantic labeling parser. The dictionaries items are nested in multiple lists I wrote this recursive code (some words are written in portuguese) def walk(lst): sentimentos=[] new_sentiment={} #saida={} for ele in lst: if type(ele) is list: walk(ele) else: if isinstance(ele,dict): for k, v in ele.items(): sentimentos.append(calcula_sentimento(str(ele.values()))) print(sentimentos) flat_sentimentos = [item for sublist in sentimentos for item in sublist] new_sentiment = {i: [j,k] for i, j, k in zip(ele.keys(), ele.values(), flat_sentimentos) } print(new_sentiment) return new_sentiment As this function is executed output is somewhat unstable, but in general the output is None. Data is like this: [[{'A0': 'Up to 140 asylum seekers', 'V': 'overpowered', 'A1': 'security guards', 'AM-LOC': 'at the tunnel s entrance', 'AM-TMP': 'as trains passed by dangerously close'}, {'A0': 'Up to 140 asylum seekers', 'V': 'swarmed on', 'A1': 'to the tracks', 'AM-TMP': 'as trains passed by dangerously close'}, {'A1': 'trains', 'V': 'passed', 'A2': 'by dangerously close'}]] Expeced output is lite this: [{'A0': ['Up to 140 asylum seekers', 0.34], 'V': ['overpowered',-0.034], ...} Code of calcula_sentimentos function adapted from git hub here: def calcula_sentimento(doc): sentences = nltk.sent_tokenize(doc) stokens = [nltk.word_tokenize(sent) for sent in sentences] taggedlist=[] for stoken in stokens: taggedlist.append(nltk.pos_tag(stoken)) wnl = nltk.WordNetLemmatizer() score_list=[] for idx,taggedsent in enumerate(taggedlist): score_list.append([]) for idx2,t in enumerate(taggedsent): newtag='' lemmatized=wnl.lemmatize(t[0]) if t[1].startswith('NN'): newtag='n' elif t[1].startswith('JJ'): newtag='a' elif t[1].startswith('V'): newtag='v' elif t[1].startswith('R'): newtag='r' else: newtag='' if(newtag!=''): synsets = list(swn.senti_synsets(lemmatized, newtag)) score=0 if(len(synsets)&gt;0): for sy…
has comment: http://stackoverflow.com/comment/83286405
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83181363
type: AnswerComment
has text: I'm not aware of (and I'm not sure there exists) an easy tail-recursive version. Except maybe if you use memoization. But it may be very memory-consuming.
type: Comment
comment on: http://stackoverflow.com/a/48099649
score: 0

http://stackoverflow.com/a/48135501
score: 0
answers question: http://stackoverflow.com/q/48135461
has body: As you scroll down, that page making xhr request to load more articles, as the request done, the javascript appends the new data after the already loaded ones. (that's technique called infinite scrolling) If you take a look on the network tab in the browser, you can see it's making request for these urls: https://readwrite.com/category/fintech/?paged1=2 https://readwrite.com/category/fintech/?paged1=3 etc. So you just have to incrementally scrap these urls.
type: Answer

http://stackoverflow.com/a/48103585
has comment: http://stackoverflow.com/comment/83214980
score: 4
type: AcceptedAnswer
has body: An example with networkx package. We will need Weights you provided to build the graph. import matplotlib.pyplot as plt import networkx as nx %matplotlib notebook Weights = {('M', 'C'): 44, ('Q', 'F'): 27, ('Y', 'X'): 42, ('X', 'Y'): 42, ('Y', 'M'): 6, ('M', 'F'): 9, ('M', 'Y'): 6, ('F', 'Q'): 27, ('F', 'M'): 9, ('C', 'M'): 44} G = nx.Graph() # each edge is a tuple of the form (node1, node2, {'weight': weight}) edges = [(k[0], k[1], {'weight': v}) for k, v in Weights.items()] G.add_edges_from(edges) pos = nx.spring_layout(G) # positions for all nodes # nodes nx.draw_networkx_nodes(G,pos,node_size=700) # labels nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif') # edges nx.draw_networkx_edges(G,pos,edgelist=edges, width=6) # weights labels = nx.get_edge_attributes(G,'weight') nx.draw_networkx_edge_labels(G,pos,edge_labels=labels) Layout Code is modified from this Tutorial by Aric Hagberg and answer by Marcus Müller.
has comment: http://stackoverflow.com/comment/83214843
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48103119
answers question: http://stackoverflow.com/q/48103119
downvote count: 0
has comment: http://stackoverflow.com/comment/83214601

http://stackoverflow.com/q/48127217
score: -2
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48127640
has comment: http://stackoverflow.com/comment/83233083
tagged with: pandas
answer count: 1
has body: Here is an example of a dataframe in previous research: It seems that the output number is in the format of at least 3 digits (e.g 1070, 0.073). For now, I can only transform the original float number into the data with same format after the dot str("{:.3f}".format(df['values']) Therefore, how to transform the original data into the table as the figure above? Any advice would be appreciated!
has comment: http://stackoverflow.com/comment/83231572
has comment: http://stackoverflow.com/comment/83231405
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/83231217
has comment: http://stackoverflow.com/comment/83233047
linked to: http://stackoverflow.com/q/12717435
has title: How to reserve at least 3 digits for a float number
type: Question
tagged with: numpy
upvote count: 0

http://stackoverflow.com/comment/83207790
score: 1
type: Comment
type: QuestionComment
has text: Have you tried looking at this page? https://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string
comment on: http://stackoverflow.com/q/48115731

http://stackoverflow.com/a/48151097
upvote count: 1
has body: In Python v2, it's type str, i.e. sequence of bytes. To convert it to a Unicode string, you need to decode this sequence of bytes using a codec. Simply said, it specifies how should bytes be converted to a sequence of Unicode code points. Look into Unicode HOWTO for more in-depth article on this.
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48151017

http://stackoverflow.com/q/48125184
has body: Just started learning python socket programming. I'm trying to send and receive data from a Raspberry Pi 3 using python sockets. I'm running the server program on the Raspberry Pi and the client program on my laptop running Ubuntu. Both are on the same WiFi network. The program runs and the client connects to the server, but there is no data transfer. Both the client and server do nothing. The two programs run properly if I try to run them both on the same device. Here's my code :- Client import socket HOST = '172.16.31.51' PORT = 5000 BUFSIZ = 1024 if __name__ == '__main__': client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = input("Enter hostname [%s]: " %HOST) or HOST port = input("Enter port [%s]: " %PORT) or PORT sock_addr = (host, int(port)) client_sock.connect(sock_addr) payload = 'GET TIME' try: while True: client_sock.send(payload.encode('utf-8')) data = client_sock.recv(BUFSIZ) print(repr(data)) more = input("Want to send more data to server[y/n]:") if more.lower() == 'y': payload = input("Enter payload: ") else: break except KeyboardInterrupt: print("Exited by user") client_sock.close() Server import socket from time import ctime PORT = 5000 BUFSIZ = 1024 ADDR = ('', PORT) if __name__ == '__main__': server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_socket.bind(ADDR) server_socket.listen(5) server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1) while True: print('Server waiting for connection...') client_sock, addr = server_socket.accept() print('Client connected from: ', addr) while True: data = client_sock.recv(BUFSIZ) if not data or data.decode('utf-8') == 'END': break print("Received from client: %s" % data.decode('utf-8')) print("Sending the server time to client: %s" %ctime()) try: client_sock.send(bytes(ctime(), 'utf-8')) except KeyboardInterrupt: print("Exited by user") client_sock.close() server_socket.close() EDIT: The screenshots - https://i.sstatic.net/uFEMR.jpg As soon as I hit Ctrl + C, on …
linked to: http://stackoverflow.com/q/855544
has title: Python sockets connecting but no data transfer
answer count: 1
linked to: http://stackoverflow.com/q/4407835
has comment: http://stackoverflow.com/comment/83234141
type: UnansweredQuestion
tagged with: sockets
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83234301
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/48127661
has comment: http://stackoverflow.com/comment/83227510
score: 0

http://stackoverflow.com/comment/83348711
comment on: http://stackoverflow.com/a/48173892
type: Comment
score: 1
has text: @Nae, `.f.l` means `frame.listbox` where `frame` is the popdown frame and `listbox` is the popdown listbox. As you can see from the code - popdown is actually a `Toplevel` window, with a `frame`, a `listbox` and a `scrollbar` (optionally).
type: AnswerComment

http://stackoverflow.com/comment/83044099
comment on: http://stackoverflow.com/q/48036608
score: 0
type: QuestionComment
type: Comment
has text: Questions to help my own understanding: **1.** What potential widths (`L`) did you use to create these plots? **2.** Why is there a `3` in `h = float(3*L/N)`? As far as I see, this reduces spatial resolution by a factor of 3, same as just reducing `N` or increasing `L` directly. **3.** Why choose `psi[1] = h`? `h` is the spatial step size, so `psi[1]` holds the value of the wavefunction at x = x0 + h, but there's no reason for the value of `psi[1]` to *equal* `h`.

http://stackoverflow.com/comment/83375336
type: Comment
type: QuestionComment
score: 2
has text: I've rolled-back to the version that has existing answers. OP: if you have a different question, please post a new one.
comment on: http://stackoverflow.com/q/48053030

ubuntu-16.04
tags question: http://stackoverflow.com/q/48028185
tags question: http://stackoverflow.com/q/48056297
tags question: http://stackoverflow.com/q/48090141
tag name: ubuntu-16.04
tags question: http://stackoverflow.com/q/48075303
type: Tag
tags question: http://stackoverflow.com/q/48114179

http://stackoverflow.com/comment/83266942
type: Comment
type: QuestionComment
has text: I'm not sure I understand when you want to "dynamically set the rules[]". Both classes are defined up front. There's no new definition of `Xchange` for each instance of `XCEngine`, all instances share the same class (just like they share other class variables). You can of course modify the class variables at any time (such as in `XCEngine.__init__`), but I'm not sure if that's what you want or not.
comment on: http://stackoverflow.com/q/48144173
score: 0

http://stackoverflow.com/q/48134176
has comment: http://stackoverflow.com/comment/83245721
has comment: http://stackoverflow.com/comment/83245713
upvote count: 2
tagged with: save
answer count: 1
score: -6
linked to: http://stackoverflow.com/q/4529815
type: UnansweredQuestion
has body: I️ want to write a program in Python that saves the history of crypto currency purchases/sales I️ make. I️ want to be able to save data such as time of purchase, price of currency at time of transaction, and profit to look for patterns. How would I️ go about saving this data?
has answer: http://stackoverflow.com/a/48321806
has comment: http://stackoverflow.com/comment/83245779
favorite count: 0
has title: What's the best way to save historical data?
type: Question
downvote count: 8
tagged with: python

http://stackoverflow.com/comment/83289954
score: 0
type: Comment
type: QuestionComment
has text: @CristiFati : Yes my gcc is not able to find Python.h file , how to include that ? I tried `gcc -I/usr/include/python2.6 /usr/include/python2.6/Python.h` but that didn't help
comment on: http://stackoverflow.com/q/48154968

http://stackoverflow.com/q/48023433
has body: When I run this code(part of a larger project): def Initialize (event,tk): event.delete("all") parch = tk.PhotoImage(file = "Parchment.png" ) parchment = event.create_image(175, 25, image = parch, anchor = "nw") parchment.place(175, 25)` Which gives the error: parchment.place(175, 25) AttributeError: 'int' object has no attribute 'place' Technically, it all works fine and does its job; but having error messages is not really good either way.
has comment: http://stackoverflow.com/comment/83021330
tagged with: python
has comment: http://stackoverflow.com/comment/83015977
has comment: http://stackoverflow.com/comment/83023673
tagged with: tkinter
linked to: http://stackoverflow.com/q/3359717
downvote count: 2
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83022254
has comment: http://stackoverflow.com/comment/83022194
score: -1
has comment: http://stackoverflow.com/comment/83016313
has answer: http://stackoverflow.com/a/48023492
answer count: 1
has comment: http://stackoverflow.com/comment/83025587
has comment: http://stackoverflow.com/comment/83024884
has comment: http://stackoverflow.com/comment/83064292
has comment: http://stackoverflow.com/comment/83021506
has title: Why does place method give me an error when used on an object in Canvas?
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/48051042
has body: it's written there that mysql-python may not be python-3 compatible : https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python you may rather try, for example: "pip install mysql-connector-python"
downvote count: 1
answers question: http://stackoverflow.com/q/48046440
type: Answer
upvote count: 0
score: -1

http://stackoverflow.com/q/48065772
has answer: http://stackoverflow.com/a/48065850
has comment: http://stackoverflow.com/comment/83104910
linked to: http://stackoverflow.com/q/1523660
duplicate of: http://stackoverflow.com/q/1523660
answer count: 1
has title: trying to separate two sets of information from csv
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I've used a draft code and adapted it to suit my code but I don't know how to split the data. The question might seem a vague so I'll try to be help by saying what I want. My code: import csv with open("scores.csv") as csv_data: reader=csv.reader(csv_data,delimiter=",") number_sorted=sorted(reader,key=lambda x:int(x[0]),reverse=True) print(number_sorted) I get the output: [['25356767', 'tom'], ['443388', 'jin'], ['6744', 'trev'], ['4666', 'ryan'], ['2445', 'jones'], ['536', 'sue'], ['34', 'bob'], ['8', 'hera'], ['1', 'bill'], ['0', 'v']] but I want the print to look like this so it looks like a leader board: `[['25356767', 'tom'], ['443388', 'jin'], ['6744', 'trev'], ['4666', 'ryan'], ['2445', 'jones'], ['536', 'sue'], ['34', 'bob'], ['8', 'hera'], ['1', 'bill'], ['0', 'v']]` I hope that explains my question.
score: 0
has comment: http://stackoverflow.com/comment/83104783
type: Question

http://stackoverflow.com/q/48103144
tagged with: django-staticfiles
has title: Static Root - Django version 2.0.1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has body: Upgraded from Django 1.10 to 2.01. Settings.py (Has not changed) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = os.path.join('/processor/', 'static/') python manage.py collectstatic and python manage.py runserver both return the same errors below: hal@hal:~/CSsite$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Django version 2.0.1, using settings 'CSsite.production' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [ERROR] (Thread-1 ) Internal Server Error: / Traceback (most recent call last): File "/home/hal/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/hal/CSsite/processor/views.py", line 108, in index return render(request, 'processor/select.html', dic) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/backends/django.pstaticfilesy", line 61, in render return self.template.render(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/base.py", line 175, in render return self._render(context) File "/home/hal/anaconda3/lib/python3.6/site-packages/django/template/base.py", line 167, in _render retu…
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/83259466
type: Question
has comment: http://stackoverflow.com/comment/83181759
has comment: http://stackoverflow.com/comment/83208932
tagged with: python-3.6

http://stackoverflow.com/comment/83235994
comment on: http://stackoverflow.com/q/48128268
score: 0
has text: Pythion 3 with py2exe and py2app? They arn't compatable with Python 3 try [pyinstaller](http://www.pyinstaller.org/) or [Cx_Freeze](https://anthony-tuininga.github.io/cx_Freeze/)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48133292
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83249533
tagged with: python
tagged with: file-upload
tagged with: python-3.x
score: 2
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83244179
has title: File upload doesn't terminate (freezes near the end) in Safari
tagged with: django
tagged with: safari
has body: I'm running a test server under the latest Django 2 release (Python3.6) on Mac OS X. My applications seem to work well across both Safari 11.0.2 and Chrome (build 63) except for one anoying detail. I've got this file upload form: class BulkForm(AssemblyForm): # AssemblyForm itself defines a Char field. file = forms.FileField(required=True, label='Input file') That is handled by the following view (I've reduced it to the bare minimum for this example): def formtest(request): if request.method == 'POST': form = BulkForm(request.POST, request.FILES) if form.is_valid(): upload = request.FILES['file'] return HttpResponseRedirect(reverse('submissions')) bulk = BulkForm() return render(request, 'upload.html', {'bulk_form': bulk}) And the template: ... &lt;div class="tab-pane fade" id="bulk"&gt; &lt;div class="container my-4"&gt; &lt;form role="form" method="post" enctype="multipart/form-data"&gt; {% csrf_token %} {{ bulk_form.as_p }} &lt;button type="submit" name="bulk-form" class="btn btn-primary bg-dark"&gt; Submit &lt;/button&gt; &lt;/form&gt; &lt;/div&gt; ... In Safari the upload sometimes freezes even when I try the same file: sometimes it uploads successfully, sometimes it freezes. There is a correlation between file size and its chances of getting stuck. To investigate this issue, I've implemented my own upload handler: class SizeLimitedUploadedFile(uploadedfile.UploadedFile): def __init__(self, name, content_type, size, charset, content_type_extra=None): file = tempfile.NamedTemporaryFile( buffering=settings.FILE_UPLOAD_MAX_MEMORY_SIZE, delete=False, suffix=f'.upload.{name.split(".", 1)[1]}', dir=settings.FILE_UPLOAD_TEMP_DIR ) super().__init__(file, file.name, content_type, 0, charset, content_type_extra) self.error = None def write(self, chunk: bytes) -&gt; int: """ :param chunk: bytes to write :return: the number of bytes written :raises FileSizeLimitReached: if file size reached """ newsize = self.size + len(chunk) if newsize &lt;= settings.FILE_UPLOAD_MAX_MEMO…
type: Question
upvote count: 2

http://stackoverflow.com/comment/83049382
type: Comment
has text: Also, a further though, I would separate out accepting the input from the user too...
score: 0
comment on: http://stackoverflow.com/a/48039481
type: AnswerComment

http://stackoverflow.com/a/69650865
type: Answer
has body: I also had the same problem using FastApi framework. I could solve the problem after add this code to my app.py: scheduler = BackgroundScheduler() pg_job_store = SQLAlchemyJobStore(engine=my_engine) scheduler.add_jobstore(jobstore=pg_job_store, alias='sqlalchemy') scheduler.start() Adding this code, after I restart the application server I could see apscheduler logs searching for jobs: 2021-10-20 14:37:53,433 - apscheduler.scheduler - INFO =&gt; Scheduler started 2021-10-20 14:37:53,433 - apscheduler.scheduler - DEBUG =&gt; Looking for jobs to run Jobstore default: No scheduled jobs Jobstore sqlalchemy: remove_from_db_job (trigger: date[2021-10-20 14:38:00 -03], next run at: 2021-10-20 14:38:00 -03) 2021-10-20 14:37:53,443 - apscheduler.scheduler - DEBUG =&gt; Next wakeup is due at 2021-10-20 14:38:00-03:00 (in 6.565892 seconds) It works for me.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48047118
downvote count: 0

http://stackoverflow.com/a/48104489
upvote count: 4
answers question: http://stackoverflow.com/q/48104449
has comment: http://stackoverflow.com/comment/83185168
downvote count: 0
has comment: http://stackoverflow.com/comment/83184813
score: 4
has comment: http://stackoverflow.com/comment/83184994
has comment: http://stackoverflow.com/comment/83184803
has body: Short circuiting does occur. The in operator calls the __contains__ method, which in turn is implemented differently per class (in your case list). Searching for 999 takes around double the time as searching for 0, since half of the work is creating the list, and the other half is iterating through it, which is short circuited in the case of 0.
type: Answer
has comment: http://stackoverflow.com/comment/83184908

rdd
tags question: http://stackoverflow.com/q/48140510
tags question: http://stackoverflow.com/q/48148840
tag name: rdd
tags question: http://stackoverflow.com/q/48024983
tags question: http://stackoverflow.com/q/48019524
type: Tag

http://stackoverflow.com/q/48170388
has body: I have a gmail account in my g-suite organization for which I want to automatically read its gmail messages. Since this needs to be run periodically with an automated process, the regular OAuth flow is not useful, since someone needs to open a browser and give permission to the automated access. So far I've created a service account with domain-wide authority, as documented here. The code I am using is: import httplib2 from apiclient import discovery SCOPES = ['https://www.googleapis.com/auth/gmail.readonly', ] CLIENT_SECRET_FILE = '/path/to/client_secrets.json' def get_credentials(): from oauth2client.service_account import ServiceAccountCredentials credentials = ServiceAccountCredentials.from_json_keyfile_name(CLIENT_SECRET_FILE, SCOPES) delegated_credentials = credentials.create_delegated('myproject@myproject-123456.iam.gserviceaccount.com') return delegated_credentials def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) results = service.users().messages().list(userId='user_to_impersonate@mycompany.com').execute() if __name__ == '__main__': main() But I get a 400 Bad Request error: Traceback (most recent call last): File "gmail.py", line 77, in &lt;module&gt; main() File "gmail.py", line 65, in main results = service.users().messages().list(userId='user_to_impersonate@mycompany.com').execute() File "/usr/local/lib/python3.6/site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper return wrapped(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/googleapiclient/http.py", line 842, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: &lt;HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/user_to_impersonate%40mycompany.com/messages?alt=json returned "Bad Request"&gt; Is it possible at all to access a specific gmail account without having to grant permission from the browser? Do I need to perf…
tagged with: gmail-api
has comment: http://stackoverflow.com/comment/83321067
upvote count: 3
type: UnansweredQuestion
tagged with: python
score: 3
has title: Accessing the gmail API with delegated domain-wide authority
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/56837893
favorite count: 0
tagged with: google-workspace
answer count: 1

http://stackoverflow.com/comment/83257576
type: Comment
type: QuestionComment
has text: You're not using Python 3.5.2.
score: 1
comment on: http://stackoverflow.com/q/48139949

function
tags question: http://stackoverflow.com/q/48026242
tags question: http://stackoverflow.com/q/48069825
tags question: http://stackoverflow.com/q/48054569
tag name: function
tags question: http://stackoverflow.com/q/48039392
tags question: http://stackoverflow.com/q/48049474
tags question: http://stackoverflow.com/q/48068553
tags question: http://stackoverflow.com/q/48024407
tags question: http://stackoverflow.com/q/48027727
tags question: http://stackoverflow.com/q/48102109
tags question: http://stackoverflow.com/q/48133560
tags question: http://stackoverflow.com/q/48106658
tags question: http://stackoverflow.com/q/48052710
tags question: http://stackoverflow.com/q/48036861
tags question: http://stackoverflow.com/q/48167621
tags question: http://stackoverflow.com/q/48085291
tags question: http://stackoverflow.com/q/48136240
tags question: http://stackoverflow.com/q/48046095
tags question: http://stackoverflow.com/q/48041476
tags question: http://stackoverflow.com/q/48157771
tags question: http://stackoverflow.com/q/48080264
tags question: http://stackoverflow.com/q/48122025
tags question: http://stackoverflow.com/q/48032776
tags question: http://stackoverflow.com/q/48030117
tags question: http://stackoverflow.com/q/48086073
tags question: http://stackoverflow.com/q/48118508
type: Tag
tags question: http://stackoverflow.com/q/48113662
tags question: http://stackoverflow.com/q/48037051
tags question: http://stackoverflow.com/q/48029137
tags question: http://stackoverflow.com/q/48084139
tags question: http://stackoverflow.com/q/48040704
tags question: http://stackoverflow.com/q/48088562
tags question: http://stackoverflow.com/q/48076905
tags question: http://stackoverflow.com/q/48043195
tags question: http://stackoverflow.com/q/48048515
tags question: http://stackoverflow.com/q/48064419
tags question: http://stackoverflow.com/q/48158178
tags question: http://stackoverflow.com/q/48063550

http://stackoverflow.com/comment/83297777
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48104415
type: Comment
has text: @user2423970 Technically speaking, `'<<NotebookT-abChanged>>'` is a valid virtual event identifier. Tkinter has no way of knowing if you created (or are planning to create) an event like that somewhere else in your code.

http://stackoverflow.com/comment/83123534
comment on: http://stackoverflow.com/q/48074091
score: 0
has text: I've figured it out. Open up all the inbound and outbound ports like 8080,80, etc.. for pip to install
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48149980
has title: Anaconda after update: Command propmpt responding very slowly and IPython not loading
upvote count: 1
type: Question
tagged with: anaconda
has comment: http://stackoverflow.com/comment/83282699
has comment: http://stackoverflow.com/comment/83282966
has comment: http://stackoverflow.com/comment/83279093
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has body: I ran the conda update --all command, but unfortunately something went wrong with the update process and windows crashed. Now if I try to redo the update the terminal is responding very slowly, to the point where installing the update is impossible. Even worse I ran conda update ipython, which also executed very slowly and now the ipython console no longer works reporting: ImportError: No module named 'IPython.kernel.zmq.kernelapp'. I tried to update anaconda as I recived the error: line magic function %pyomo not found, when executing one of the basic examples using pyomo. What should be done to restore anaconda? I am using the Spyder IDE.
tagged with: python
answer count: 0
score: 1

http://stackoverflow.com/a/48030894
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48030850
answers question: http://stackoverflow.com/q/48030850
score: 1
has body: The first mail=Mail(app) is not needed. The primary fuctionality in the Mail() constructor is to read the app configuration. So since the appropriate app config variables are not set before line 5, the first Mail() object would likely not even work.
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/48208282
type: AcceptedAnswer
has body: Sorry for the delay - the answer was indeed to use the code as per the edit import numpy as np def cos_sim(a, b): """Takes 2 vectors a, b and returns the cosine similarity according to the definition of the dot product """ dot_product = np.dot(a, b) norm_a = np.linalg.norm(a) norm_b = np.linalg.norm(b) return dot_product / (norm_a * norm_b) vector1 = [0.6666666666666666, 0.3333333333333333, 0, 0, 0, 0] vector2 = [0.4, 0.1, 0.1, 0.2, 0.1, 0.1] vector3 = [0.4, 0.1, 0.1, 0.2, 0.1, 0.1] print(cos_sim(vector1,vector2)) print(cos_sim(vector1,vector3)) print(cos_sim(vector2,vector3)) 0.821583836258 0.821583836258 1.0
type: Answer
accepted answer of: http://stackoverflow.com/q/48139441
score: 0
answers question: http://stackoverflow.com/q/48139441

http://stackoverflow.com/comment/83328367
type: AnswerComment
comment on: http://stackoverflow.com/a/48156129
score: 0
type: Comment
has text: This is a *greatly* simplified version of their example. I do not even have access to the hardware to test it on multiple gpus, which their example is capable of running on. Maybe if I find that I have a week to spare and find a few dozen grand on the sidewalk to buy a server with a handful of Teslas in it I'll submit a PR. :p

http://stackoverflow.com/comment/83006722
has text: Even when your post, answers OP's question. Please provide not only a snippet that works. But explain what's happening, why it does what it should to etc.
comment on: http://stackoverflow.com/a/48018392
score: 3
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48092637
has comment: http://stackoverflow.com/comment/83160338
favorite count: 0
accepted answer: http://stackoverflow.com/a/48093087
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83160497
type: AnsweredQuestion
tagged with: amazon-s3
has body: I am using pyspark and I am having trouble writing to S3, but reading from S3 is not a problem. this is my code: dic = {'a': {'c1(%)': 0.0, 'c2': 0, 'c3($)': 260, 'c4(%)': 4.79, 'c5': 78, 'c6': 352}, 'b': {'c1(%)': 0.0, 'c2': 0, 'c3($)': 5, 'c4(%)': 0.09, 'c5': 2, 'c6': 280}, 'c': {'c1(%)': 0.0, 'c2': 0, 'c3($)': 0, 'c4(%)': 0.0, 'c5': 0, 'c6': 267}} df = pd.DataFrame(dic) df.to_csv("s3://work/.../filename_2018-01-04_08:50:45.csv") this is the error: IOError: [Errno 2] No such file or directory: 's3://work/.../filename_2018-01-04_08:50:45.csv' what is the problem?
score: 1
has title: pyspark writing csv file to S3 error
has comment: http://stackoverflow.com/comment/83160390
linked to: http://stackoverflow.com/q/43661660
type: Question
has answer: http://stackoverflow.com/a/48093087
answer count: 1
downvote count: 0

http://stackoverflow.com/a/48127014
has comment: http://stackoverflow.com/comment/83233282
answers question: http://stackoverflow.com/q/48126924
type: Answer
upvote count: 1
has body: Learning rate: that code does not use a learning rate, or rather it uses a learning rate of 1. Lines 48,49 just add the adjustment (gradient) value without any rate. That is an uncommon choice and can sometimes work in practice, though in general it is not advised. Technically this is the simplest version of gradient descent, and there are many elaborations to simple gradient descent, most of which involve a learning rate. I won't elaborate further as this comment answers the question that you are asking, but you should know that building an optimizer is a big area of research, and there are lots of ways to do this more elaborately or with more sophistication (in the hopes of better performance). Error threshold: instead of stopping optimization when an error threshold is reached, this algorithm stops after a fixed number of iterations (60,000). That is a common choice, particularly when using something like stochastic gradient descent (again, another big topic). The basic choice here is valid though: instead of optimizing until a performance threshold is reached (error threshold), optimize until a computational budget is reached (60,000 iterations).
has comment: http://stackoverflow.com/comment/83232504
score: 1
accepted answer of: http://stackoverflow.com/q/48126924
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83230687
has comment: http://stackoverflow.com/comment/83232071

http://stackoverflow.com/a/48175993
has body: Step 1 with any such loop is to try to make it a list comprehension: att = [j for i in range(original_data.shape[0]) for j in range(unique_rows.shape[0]) if np.array_equal(original_data[i], unique_rows[j])] After that, re-think what you're trying to accomplish and how else it might be done. In this case, if you used the following dictionary comprehension, you'd get what you're looking for (assuming you don't need the unique rows to be ordered in the same order they were found in your original data): data = [tuple(row) for row in original_data] unique_rows = set(data) unique_row_map = {row: i for i, row in enumerate(unique_rows)} att = [unique_row_map[row] for row in data]
type: Answer
has comment: http://stackoverflow.com/comment/83340222
answers question: http://stackoverflow.com/q/48173041
score: 0

http://stackoverflow.com/q/48140510
favorite count: 0
accepted answer: http://stackoverflow.com/a/48140895
tagged with: python
tagged with: rdd
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48140895
downvote count: 0
score: 1
has title: Pyspark directStreams foreachRdd always has empty RDD
has body: I have been trying to read my data from a Kafka topic and writing it to a parquet file. So far I have everything working, except the foreachRdd function. I can see the data when I use the map on the dstream, but the next step of using the foreachRdd, the Rdd is always empty and I don't know why. My environment is Ubuntu running both Kafka and Spark standalone. I am using the pyspark shell. I'm new to python, so there is a lot that I am still stumbling on with the syntax and am not sure if that is where my problem is. Any help or insight would be greatly appreciated. Here's a copy of my code that I have been pasting in the pyspark shell from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils from pyspark.sql.types import * import json kafkaBroker = 'localhost:9092' consumer_group = 'spark-streaming' topic = 'test' batchTimeDur=5 ssc = StreamingContext(sc, batchTimeDur) directKafkaStream = KafkaUtils.createDirectStream(ssc, [topic], {"metadata.broker.list": kafkaBroker}) #change string to json string lines = directKafkaStream.map(lambda v: json.loads(v[1])) # show what is in the stream lines.map(lambda x: 'rec in this line: %s\n' % x).pprint() # save lines to file lines.foreachRDD(lambda x: saveAsParquet(x)) def saveAsParquet(rdd): print('in save a parquet') if not rdd.isEmpty: df = sqlContext.createDataFrame(rdd, buildSchema()) #df.write.parquet('file:///vagrant/streamed-parquet', mode='overwrite') print(' writing file') df.write.parquet('file:///vagrant/streamed-parquet', mode='append') print('return save as parquet') return rdd ssc.start()
type: Question
tagged with: pyspark
tagged with: apache-spark
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/105662916
type: AnswerComment
comment on: http://stackoverflow.com/a/48087047
score: 0
type: Comment
has text: Yes, you can. Checkout [this answer](https://stackoverflow.com/a/59758489/4913143)

http://stackoverflow.com/q/48162098
has title: How to open multiple doc file in python and parse email ID from them and write in csv?
type: Question
has answer: http://stackoverflow.com/a/59548503
tagged with: dataframe
score: 0
has body: I want to extract email id from 1000 word document files and produce a csv file in python.
answer count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83342533
has comment: http://stackoverflow.com/comment/83303564

http://stackoverflow.com/a/48094815
answers question: http://stackoverflow.com/q/48094687
score: 0
type: Answer
has body: use index: a = ['a', 'b', 'c'] dict_a = {} for x in a: dict_a[a.index(x)] = x print(dict_a)

http://stackoverflow.com/q/48110186
has title: Python Idle Starts With "No Subprocess" so running script freeze
score: 1
type: Question
upvote count: 1
has body: I had no problems selecting "run" from a script opened with idle before Windows Update made updates. For some reason, now when I select "run", the new live idle window freezes up and the script window freezes up. This did not occur before updates but from what I can see, none of the updates would effect idle or python. The script seems to run but the windows (both) are frozen...this never happened before. I now get this message when using sys.exit to close the running script, "do you want to exit altogether?" I NEVER got that message before something is really messed up. If I select yes, then all idle windows close and that's not what I want! I noticed idle says "No Subprocess" when the live window opens....but my script indeed creates threads and "chit" (lol, excuse the pun) IDLE: 2.7, python 2.7 Windows 7 64 bit AMD chipset Nivida Graphics HP Desktop Quadcore ---------------------------UPDATE-------------------------------------- When I open my script by right clicking and selecting "open with idle", I get the above issues. I just opened idle from a shortcut instead, which opened the live window. From there I selected New File from the top menu and opened my script file. Everything ran like before the issues....? So why all of a sudden selecting "edit with idle" is acting like I'm opening idle with the "-n" argument or something?
has comment: http://stackoverflow.com/comment/83226247
tagged with: windows
tagged with: python
tagged with: python-idle
tagged with: shell
favorite count: 0
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83226101

http://stackoverflow.com/comment/83269504
score: 1
comment on: http://stackoverflow.com/q/48142203
type: Comment
type: QuestionComment
has text: @sKwa: that isn't the sense of "nondeterministic" the question is using. they are asking if the same regex applied to the same string can be expected to always match in the same way or not

http://stackoverflow.com/comment/83105592
type: Comment
has text: @user9080591: the `{i} if i else 'p'` expression replaced the `{i}` version in the answers here; if `i` is a true value (so not `0` or an empty string, etc.) then a set with the value is created, otherwise the string `'p'` is used. For every value in the inner lists.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48065686

http://stackoverflow.com/comment/83191123
type: AnswerComment
comment on: http://stackoverflow.com/a/48107806
type: Comment
has text: I thought OP was trying to sort the columns giving the names, didn't realise he was trying to change the names
score: 1

http://stackoverflow.com/comment/83031335
score: 0
type: Comment
type: QuestionComment
has text: you're using pure Javascript? not using jQuery or similar libraries?
comment on: http://stackoverflow.com/q/48030474

http://stackoverflow.com/comment/83177231
has text: @gravitypulling: Where would you like to add it? In the plot itself?
comment on: http://stackoverflow.com/a/48099268
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48098432
favorite count: 0
tagged with: postgresql
type: Question
accepted answer: http://stackoverflow.com/a/49145257
tagged with: python
has comment: http://stackoverflow.com/comment/83173638
upvote count: 1
tagged with: sqlalchemy
answer count: 1
has comment: http://stackoverflow.com/comment/83193725
has title: comparing two uuid in sqlalchemy core
has comment: http://stackoverflow.com/comment/83176279
has answer: http://stackoverflow.com/a/49145257
has comment: http://stackoverflow.com/comment/83172964
has comment: http://stackoverflow.com/comment/83173194
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83178526
score: 1
has body: I'm using sqlalchemy 1.2 In short what produces errors is this : uuidvar = uuid4() mytable.select().where(mytable.c.uuidColumn == uuidvar) #where mytable is of type sqlalchemy.Table Error : File "/Users/remi/PycharmProjects/my_venv/lib/python3.6/site-packages/sqlalchemy/dialects/postgresql/psycopg2.py", line 448, in process value = _python_UUID(value) File "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/uuid.py", line 137, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') sqlalchemy.exc.StatementError: (builtins.AttributeError) 'UUID' object has no attribute 'replace' [SQL: 'SELECT col1, col2, col3 FROM myTable \nWHERE uuidColumn = '%(uuidColumn_1)s'] With a table like this : CREATE TABLE myTable ( uuidColumn uuid primary key default uuid_generate_v4() col1 text, col2 text, col3 text ) and table generate in python : metadata = MetaData(engine=db) # db is created by "create_engine", nothing fancy myTable = Table('myTable', metadata, autoload=True)

http://stackoverflow.com/a/48023201
has body: pyodbc uses some native libs. Therefore you cannot just copy the contents of your site-packages to Lambda, as your OS is likely not Amazon Linux. So you need to install pyodbc on an Amazon Linux instance and use the generated libs: https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html Or you can get from here, if available there: https://github.com/Miserlou/lambda-packages
has comment: http://stackoverflow.com/comment/83043091
has comment: http://stackoverflow.com/comment/103029652
downvote count: 0
answers question: http://stackoverflow.com/q/48016091
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85573786
has comment: http://stackoverflow.com/comment/83022004
upvote count: 2

http://stackoverflow.com/comment/83003716
has text: Test the parts? What happens if you only do `(holiday['transferred']=='False',1,0)`? Or only `holiday['transferred']=='False'`? Or only `holiday['transferred']`? Locate the problem.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48017236

http://stackoverflow.com/comment/83036820
has text: This is scraping protection, they don't want you to scrape it. You need to either use proxies and also use some other user agent, scrapy shell will use the default scrapy user agent
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48033398

http://stackoverflow.com/q/48147254
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/83273031
has title: The view didn't return an HttpResponse object when I run new_topic(), though there is a return
tagged with: django-views
score: 1
type: Question
has body: def new_topic(request): """add new topic""" if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) The error I got: The view learning_logs.views.new_topic didn't return an HttpResponse object. It returned None instead. And I have searched many related problems as well as tested them, yet they did not work.Could you please give me some help,thanks.
answer count: 1
has answer: http://stackoverflow.com/a/48150243
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83279458

http://stackoverflow.com/comment/110330373
has text: Should the `feature_columns` be initialized with some values before training?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48099304

http://stackoverflow.com/comment/83041122
comment on: http://stackoverflow.com/q/48035586
has text: Please give me a suggestion for this. I m trying to train my own model for object detection
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48044108
has comment: http://stackoverflow.com/comment/83059226
tagged with: django
tagged with: unit-testing
type: Question
has comment: http://stackoverflow.com/comment/83059171
has body: I have a dictionary which is a class variable. One test will run methods which populates this dictionary in the course of the test. There is an if statement in the code(not the tests) which basically says if dict do this. Else do this. However when i run another test which does not populate this dict the dict is already populated with the old data,and hence the if code is executed. How can i wipe the old data from the class variables
score: 0
tagged with: python
tagged with: dictionary
has title: Python django test case - one test failing when all tests are ran - Class variable data remaining during test
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/83193396
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48099525
has text: Prazak How can we pass argument to second container or docker,
score: 0

http://stackoverflow.com/comment/83240186
score: 0
comment on: http://stackoverflow.com/q/48131371
type: QuestionComment
type: Comment
has text: Where does this task come from? I'm wondering if that's really what you need or already some attempt to speed something up (e.g. get all within distance vs. get all where decomposed single-dim distances are within range)?

pygobject
type: Tag
tags question: http://stackoverflow.com/q/48063590
tags question: http://stackoverflow.com/q/48135506
tags question: http://stackoverflow.com/q/48030433
tag name: pygobject

http://stackoverflow.com/q/48100497
has body: I'm trying to build a small interactive shell in Python using the cmd module. Is there an easy way to allow for multi-word commands? For example, it's easy to process the hello command class FooShell(Cmd): def do_hello(self, args): print("Hi") But what if I wanted something more complicated. Let's say I'm trying to implement an SQL shell and want to write show tables. The show command can take multiple targets such as show track_counts or show bonjour. If I wanted to process something like this in the cmd module, it looks like I would have to write the following: class FooShell(Cmd): def do_show(self, line): args = line.strip().split(" ") if args == []: print("Error: show command requires arguments") else: if args[0] == "tables": pass # logic here elif args[0] == "bonjour": pass # logic here elif args[0] == "track_counts": pass # logic here else: print("{} is not a valid target for the 'show' command".format(args[0])) print("Valid targets are tables, bonjour, track_counts") There are a few problems with this approach: I have to write the error message myself. As I add additional commands in the if statements, I have to manually update the list of valid commands. There is no tab-completion here after the user types show This is just really ugly. Another way of writing the above would be like this: class FooShell(Cmd): def do_show_tables(self, args): pass def do_show_bonjour(self, args): pass def do_show_track_counts(self, args): pass def do_show(self, line): args = line.strip().split(" ") if args == []: print("Error: show command requires arguments") else: handlers = { "tables": self.do_show_tables, "bonjour": self.do_show_bonjour, "track_counts": self.do_show_track_counts } handler = handlers.get(args[0], None) if handler: handler(args[1:]) else: print("{} is not a valid target for the 'show' command".format(args[0])) targets = ", ".join([key for key in handlers]) print("Valid targets are: {}".format(targets)) But this still does not give tab completion after the 's…
favorite count: 0
has comment: http://stackoverflow.com/comment/121072594
has comment: http://stackoverflow.com/comment/83176170
tagged with: python-cmd
has title: multi-word commands in custom python interactive shell
possible better answer: http://stackoverflow.com/a/71426680
tagged with: python
has answer: http://stackoverflow.com/a/71426680
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/76384004
accepted answer: http://stackoverflow.com/a/76384004
has comment: http://stackoverflow.com/comment/83178018
answer count: 2
has comment: http://stackoverflow.com/comment/83178236

http://stackoverflow.com/comment/83243319
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48133041
has text: Like this? https://stackoverflow.com/questions/14781895/running-python-multiprocess-for-image-processing
score: 0

http://stackoverflow.com/comment/83147195
comment on: http://stackoverflow.com/a/48085920
type: AnswerComment
type: Comment
score: 0
has text: Brilliant answer - thank you! Incidentally for `$ type python2.7` I got `python2.7 is hashed (/usr/local/bin/python2.7)` - no idea what hashed means in this context, but using that path as recommended worked.

http://stackoverflow.com/q/48119355
type: Question
score: 0
tagged with: bash
has answer: http://stackoverflow.com/a/48119540
answer count: 1
tagged with: gunicorn
tagged with: django
tagged with: python
has body: I tried putting all my environment variables for my Django project inside ~/.bash_profile and then use it in gunicorn.service with EnvironmentFile=/home/user/.bas... but with no luck. Eventually I had to put everything in ExecStart with -e in front of every variable, also with SECRET_KEY and everything in plain text. Is it safe, is it possible to access this externally or how else could I do this?
type: UnansweredQuestion
has title: How to store env variables other than inside gunicorn.service for a Django project?

http://stackoverflow.com/q/48099026
tagged with: curve-fitting
tagged with: python
has title: Exponential curve fit will not fit
type: AnsweredQuestion
upvote count: 3
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/83173149
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48099268
has body: When attempting to plot an exponential curve to a set of data: import matplotlib import matplotlib.pyplot as plt from matplotlib import style from matplotlib import pylab import numpy as np from scipy.optimize import curve_fit x = np.array([30,40,50,60]) y = np.array([0.027679854,0.055639098,0.114814815,0.240740741]) def exponenial_func(x, a, b, c): return a*np.exp(-b*x)+c popt, pcov = curve_fit(exponenial_func, x, y, p0=(1, 1e-6, 1)) xx = np.linspace(10,60,1000) yy = exponenial_func(xx, *popt) plt.plot(x,y,'o', xx, yy) pylab.title('Exponential Fit') ax = plt.gca() fig = plt.gcf() plt.xlabel(r'Temperature, C') plt.ylabel(r'1/Time, $s^-$$^1$') plt.show() Graph for the above code: However when I add the data point 20 (x) and 0.015162344 (y): import matplotlib import matplotlib.pyplot as plt from matplotlib import style from matplotlib import pylab import numpy as np from scipy.optimize import curve_fit x = np.array([20,30,40,50,60]) y = np.array([0.015162344,0.027679854,0.055639098,0.114814815,0.240740741]) def exponenial_func(x, a, b, c): return a*np.exp(-b*x)+c popt, pcov = curve_fit(exponenial_func, x, y, p0=(1, 1e-6, 1)) xx = np.linspace(20,60,1000) yy = exponenial_func(xx, *popt) plt.plot(x,y,'o', xx, yy) pylab.title('Exponential Fit') ax = plt.gca() fig = plt.gcf() plt.xlabel(r'Temperature, C') plt.ylabel(r'1/Time, $s^-$$^1$') plt.show() The above code generates the error 'RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 800.' If maxfev is set to maxfev = 1300 popt, pcov = curve_fit(exponenial_func, x, y, p0=(1, 1e-6, 1),maxfev=1300) The graph is plotted but does not fit the curve correctly. Graph from above code change, maxfev = 1300: I think this is because points 20 and 30 a too close to each other? For comparison, excel plots the data like this: How can I plot this curve correctly?
score: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/83173386
accepted answer: http://stackoverflow.com/a/48099268

http://stackoverflow.com/comment/83159719
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48092594
has text: It forward fills even on row 2, where there is a nan (which I don't want) - i'll update the question to show this "edge case"
type: AnswerComment

http://stackoverflow.com/q/48156213
tagged with: python
possible better answer: http://stackoverflow.com/a/48414553
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83294326
has comment: http://stackoverflow.com/comment/83291443
has answer: http://stackoverflow.com/a/48156257
type: Question
linked to: http://stackoverflow.com/q/17063458
has comment: http://stackoverflow.com/comment/83294428
score: 1
has body: Is there a way to read an excel table in python - when the table you're reading is actually an excel table connected to SQL Server? In theory - i'm asking if you can go from a data linked excel file to a python pandas dataframe, pd.read_excel() doesn't seem to work for this.
has comment: http://stackoverflow.com/comment/83291485
has answer: http://stackoverflow.com/a/48414553
answer count: 2
tagged with: pandas
tagged with: sql
upvote count: 1
favorite count: 0
tagged with: sql-server
has title: SQL Server to Excel to Python - pd.read_excel()
accepted answer: http://stackoverflow.com/a/48156257

http://stackoverflow.com/comment/83100938
has text: @Marc-AntoineGiguère It is bit confusing to implement what i said in your code, so i update a piece of class that serve the best for you.
score: 0
comment on: http://stackoverflow.com/q/48051192
type: Comment
type: QuestionComment

scikit-learn
tags question: http://stackoverflow.com/q/48052570
tags question: http://stackoverflow.com/q/48114750
tags question: http://stackoverflow.com/q/48067726
tags question: http://stackoverflow.com/q/48139582
tags question: http://stackoverflow.com/q/48063266
tags question: http://stackoverflow.com/q/48052426
tags question: http://stackoverflow.com/q/48088699
tags question: http://stackoverflow.com/q/48058044
tags question: http://stackoverflow.com/q/48121763
tags question: http://stackoverflow.com/q/48162279
tags question: http://stackoverflow.com/q/48103882
tags question: http://stackoverflow.com/q/48029870
tags question: http://stackoverflow.com/q/48050998
tags question: http://stackoverflow.com/q/48046052
tags question: http://stackoverflow.com/q/48100173
tags question: http://stackoverflow.com/q/48152829
tags question: http://stackoverflow.com/q/48046646
tags question: http://stackoverflow.com/q/48070346
tags question: http://stackoverflow.com/q/48028706
tags question: http://stackoverflow.com/q/48121628
tags question: http://stackoverflow.com/q/48130160
tags question: http://stackoverflow.com/q/48043891
tags question: http://stackoverflow.com/q/48074462
tags question: http://stackoverflow.com/q/48170405
tags question: http://stackoverflow.com/q/48126771
tags question: http://stackoverflow.com/q/48130196
tags question: http://stackoverflow.com/q/48114054
tags question: http://stackoverflow.com/q/48090658
tags question: http://stackoverflow.com/q/48065601
tags question: http://stackoverflow.com/q/48043661
tags question: http://stackoverflow.com/q/48019843
tag name: scikit-learn
tags question: http://stackoverflow.com/q/48121950
type: Tag
tags question: http://stackoverflow.com/q/48051891
tags question: http://stackoverflow.com/q/48032852
tags question: http://stackoverflow.com/q/48111602
tags question: http://stackoverflow.com/q/48079973
tags question: http://stackoverflow.com/q/48135848
tags question: http://stackoverflow.com/q/48100939
tags question: http://stackoverflow.com/q/48101897
tags question: http://stackoverflow.com/q/48053433
tags question: http://stackoverflow.com/q/48081020
tags question: http://stackoverflow.com/q/48022187
tags question: http://stackoverflow.com/q/48133645
tags question: http://stackoverflow.com/q/48070697
tags question: http://stackoverflow.com/q/48048776
tags question: http://stackoverflow.com/q/48050953
tags question: http://stackoverflow.com/q/48026206
tags question: http://stackoverflow.com/q/48040346
tags question: http://stackoverflow.com/q/48064517
tags question: http://stackoverflow.com/q/48034035
tags question: http://stackoverflow.com/q/48066306

http://stackoverflow.com/a/48144270
type: Answer
has comment: http://stackoverflow.com/comment/83296077
score: 0
has body: Based on Amazons blog and documentation, it seems you're missing "type": "AudioPlayer.Play"in your directives.
answers question: http://stackoverflow.com/q/48144214

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

http://stackoverflow.com/q/48066406
has answer: http://stackoverflow.com/a/48066557
favorite count: 0
has title: Python-Django error when importing data from settings.py
has body: I am trying to import DB settings from settings.py but I am getting an error: Traceback (most recent call last): File "Read_Data.py", line 12, in read_bbg dbHost = settings.DATABASES['default']['HOST'] KeyError: 'default' import psycopg2 import csv from django.conf import settings import sys def read_bbg(file): """ read from csv and insert into db table """ settings.configure(DEBUG=True) dbHost = settings.DATABASES['default']['HOST'] dbUsername = settings.DATABASES['default']['USER'] dbPassword = settings.DATABASES['default']['PASSWORD'] dbName = settings.DATABASES['default']['NAME'] conn_string = """host='{0}' dbname='{1}' user='{2}' password='{3}' sslmode='require' """.format(dbHost,dbName,dbUsername,dbPassword) print(conn_string) conn=None """ ##rest of the code## """ the settings.py is located in ./cf_proj directory and the read_bbg function is in ./coveredfunds/Read_Data.py Could anyone help me with this error?
tagged with: python
score: 1
type: UnansweredQuestion
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/48067511
has comment: http://stackoverflow.com/comment/83106465
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/q/48063772
has answer: http://stackoverflow.com/a/67732341
score: 4
has comment: http://stackoverflow.com/comment/83100794
favorite count: 0
has comment: http://stackoverflow.com/comment/83100741
has answer: http://stackoverflow.com/a/48063922
answer count: 5
tagged with: python
has title: Unexpected output from list comprehension
possible better answer: http://stackoverflow.com/a/48063922
has comment: http://stackoverflow.com/comment/83100673
tagged with: python-3.x
has answer: http://stackoverflow.com/a/67732449
has comment: http://stackoverflow.com/comment/83100851
has answer: http://stackoverflow.com/a/48063876
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/83100689
has answer: http://stackoverflow.com/a/48064754
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/83100906
has body: I have an input list as follows: test_list = ['a', ('abc', 'd'), ['efgh', 'i'], 'jkl'] which I need to flatten, so getting rid of the tuple and list as respective second and third element of test_list Expected output: ['a', 'abc', 'd', 'efgh', 'i', 'jkl'] I have a problem finding the correct list comprehension for this. I have tried the following 2 examples: result = [xs if type(xs) is str else x for xs in test_list for x in xs] print('result', result) # this outputs: # ['a', 'abc', 'd', 'efgh', 'i', 'jkl', 'jkl', 'jkl'] result = [x if ((type(xs) is list) or (type(xs) is tuple)) else xs for xs in test_list for x in xs] print('result',result) #this also outputs: # ['a', 'abc', 'd', 'efgh', 'i', 'jkl', 'jkl', 'jkl'] as you can see, it does "flatten" the list, but it repeats the last element based on the number of characters in the last element. Example if the last element of the test_list is 'jklm' then the in the result the last element is repeated 4 times. I would like to know if there is a list comprehension which flatten my input list to the expected output without repeating the last element.
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/48063876
downvote count: 0

http://stackoverflow.com/a/48031713
accepted answer of: http://stackoverflow.com/q/48029461
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48029461
upvote count: 2
type: Answer
score: 2
has body: In order to achieve this you'll have to hook into the Emitter and have it insert a newline and appropriate indentation when processing a mapping value. This can be done with the old style API that you use, but is better done with the new ruamel.yaml API, which gives you e.g. the possibility to indent sequences and mappings with different values: import sys import ruamel.yaml from ruamel.yaml.emitter import Emitter class MyEmitter(Emitter): def expect_block_mapping_simple_value(self): # type: () -&gt; None if getattr(self.event, 'style', None) != '?': # prefix = u'' if self.indent == 0 and self.top_level_colon_align is not None: # write non-prefixed colon c = u' ' * (self.top_level_colon_align - self.column) + self.colon else: c = self.prefixed_colon self.write_indicator(c, False) # the next four lines force a line break and proper indent of the value self.write_line_break() self.indent += self.best_map_indent self.write_indent() self.indent -= self.best_map_indent self.states.append(self.expect_block_mapping_key) self.expect_node(mapping=True) in_str='''\ Pets: Cat: Tom Mouse: - Jerry - 'Mickey' Dog: Scooby ''' yaml = ruamel.yaml.YAML() yaml.Emitter = MyEmitter yaml.indent(mapping=4, sequence=2, offset=0) yaml.preserve_quotes = True results = yaml.load(in_str) results['Pets']['Bird']='Tweety' yaml.dump(results, sys.stdout) this gives: Pets: Cat: Tom Mouse: - Jerry - 'Mickey' Dog: Scooby Bird: Tweety Things to note: You only have to handle simple scalar values (as opposed to mappings/sequences, which are already "pushed" to the next line in block sequence "mode") The expect_block_mapping_simple_value is copied from the source and a few lines added. There is currently no "hook" to do this without duplicating some code. You can play with the sequence and offset values for yaml.indent() if you have sequences and need different indentation for that. All of this assumes consistent indenting, individual indentation is not preserved (i.e. if some values are indented with mo…

http://stackoverflow.com/comment/83327418
comment on: http://stackoverflow.com/q/48172881
type: QuestionComment
type: Comment
has text: Of course the points are the same. Unless you tell how the logic of showing many very close points on a large scale should work out, there is no solution to this.
score: 0

http://stackoverflow.com/comment/83049007
has text: Man, forget about it... that was it. I set the empty delegate to the column and it worked, my mistake,, I knew something was off with that emptyDelegate.. i forgot the set it at the tableView. Well. thank you for guiding me thru this! Now i just gotta align that checkbox and do the remove row button! But I guess I can figure that out !! Thank you and Happy new year!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48037043

http://stackoverflow.com/a/48123076
downvote count: 0
has comment: http://stackoverflow.com/comment/83325940
has comment: http://stackoverflow.com/comment/83222989
answers question: http://stackoverflow.com/q/48054531
score: 10
has comment: http://stackoverflow.com/comment/83319148
upvote count: 10
type: AcceptedAnswer
type: Answer
has body: Seems like this is due to pandas version higher than 0.21.0 and numpy version 1.13.3 that is pulled by TensorFlow not playing well together. Here is how I fixed it in my end: # ipython Python 2.7.6 (default, Nov 23 2017, 15:49:48) Type "copyright", "credits" or "license" for more information. IPython 4.2.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]: import tensorflow as tf --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb In [2]: !pip install pandas==0.21.0 Collecting pandas==0.21.0 /usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning. SNIMissingWarning /usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLC ontext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to f ail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest /security.html#insecureplatformwarning. InsecurePlatformWarning Downloading pandas-0.21.0-cp27-cp27mu-manylinux1_x86_64.whl (24.3MB) 100% |################################| 24.3MB 52kB/s Requirement already satisfied: pytz>=2011k in /usr/local/lib/pyth…
has comment: http://stackoverflow.com/comment/112996942
accepted answer of: http://stackoverflow.com/q/48054531

http://stackoverflow.com/a/48162391
has body: What you get as a result of the export is the deployed unit. Yes, there is some metadata added/modified as a result of the deployment on the OSB runtime (deployment could also mean creating/editing components directly on the servicebus console). To get it back as "source code" from the exported jar, you can simply import it back into JDeveloper (12c) or Eclipse with OEPE (11g)
answers question: http://stackoverflow.com/q/48161583
downvote count: 0
has comment: http://stackoverflow.com/comment/83305653
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83304608

http://stackoverflow.com/comment/83267035
type: QuestionComment
has text: @user9099 that does not look like a full path, e.g. try this: https://bitbucket.org/Tysondogerz/dwaddwadaw/src/master
comment on: http://stackoverflow.com/q/48047296
score: 0
type: Comment

http://stackoverflow.com/a/48036735
has comment: http://stackoverflow.com/comment/83047935
score: 9
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48036695
has comment: http://stackoverflow.com/comment/83043797
upvote count: 9
answers question: http://stackoverflow.com/q/48036695
has comment: http://stackoverflow.com/comment/83043587
type: Answer
has body: You can run a cell with this at the beginning of the notebook: from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" This will run all the expressions in each cell. If you want to return to the default behavior, you can write: InteractiveShell.ast_node_interactivity = "last_expr"

http://stackoverflow.com/comment/83174782
type: Comment
comment on: http://stackoverflow.com/a/48099729
type: AnswerComment
has text: I did both steps you mentioned. It does not solve the problem!
score: 0

http://stackoverflow.com/q/48016160
tagged with: calculation
type: Question
tagged with: dataframe
has comment: http://stackoverflow.com/comment/83002334
score: 0
has title: Python Dictionary: Simple division with massive DataFrame values in each indexes
has comment: http://stackoverflow.com/comment/83002490
has comment: http://stackoverflow.com/comment/83005757
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
answer count: 0
has body: So I have a two Dictionaries which are composed with 10 of 3000 by 3000 Dataframe in each index(0~9). All the values in the Dataframe is int, and I just want to simply divide each values. The first loop below is only replacing index=column values into 0, and personally I do not think this loop is slowing the process. The second loop is the problem with run time (I believe) since there are too many data to compute. Please see the code below. for a in range(10): for aa in range(len(dict_cat4[a])): dict_cat4[a].iloc[aa,aa] = 0 dict_amt4[a].iloc[aa,aa] = 0 for b in range(10): temp_df3 = dict_amt4[b] / dict_cat4[b] temp_df3.replace(np.nan,0.0,inplace=True) dict_div4[b] = temp_df3 One problem is that the process takes forever to compute this loop since the data set is very big. Is there a efficient way to convert my code into other loops? Now its been 60+ minutes and still computing. Please let me know! Thanks -----------------edit------------------ Below is sample input and output of first loop Output:dict_amt4[0] DNA Cat2 ... Func Item A B C D E F F H I J ... ZDF11 ZDF12 ZDF13 ZDF14 ZDF15 ZDF16 ZDF17 ZDF18 ZDF19 ZDF20 DNA Item Cat2 A 0 62 174 0 4 46 46 7 2 15 ... 4 17 45 1 2 0 0 0 0 0 B 62 0 27 0 0 12 61 2 4 11 ... 6 9 14 1 0 0 0 0 0 0 C 174 27 0 0 0 13 22 5 2 4 ... 0 2 8 0 0 0 0 0 0 0 D 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 E 4 0 0 0 0 10 57 33 4 5 ... 0 0 0 0 0 0 2 0 0 0 F 46 12 13 0 10 0 4 5 0 0 ... 0 33 2 0 0 0 2 3 0 0 ............. And second loop is below Input:dict_amt4[0] DNA Cat2 ... Func Item A B C D E F F H I J ... ZDF11 ZDF12 ZDF13 ZDF14 ZDF15 ZDF16 ZDF17 ZDF18 ZDF19 ZDF20 DNA Item Cat2 A 0 186 174 0 4 46 46 14 2 15 ... 4 17 45 1 2 0 0 0 0 0 B 186 0 27 0 0 12 61 2 4 11 ... 6 9 14 1 0 0 0 0 0 0 C 174 27 0 0 0 130 22 5 2 4 ... 0 2 8 0 0 0 0 0 0 0 D 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0 E 4 0 0 0 0 10 57 33 4 5 ... 0 0 0 0 0 0 2 0 0 0 F 46 12 13 0 10 0 4 5 0 0 ... 0 33 2 0 0 0 2 3 0 0 ............. Input:dict_cat4[0] DNA Cat2 ... Func Item A B C D E…
has comment: http://stackoverflow.com/comment/83002514
tagged with: division

http://stackoverflow.com/a/48062429
accepted answer of: http://stackoverflow.com/q/48061659
type: Answer
upvote count: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/116867024
has body: Documentation is not really up-to-date, try with mprof run --python python3 test1.py (having import commented out), it seems to work for me, but generates output to file only and does not write to stdout at all.
answers question: http://stackoverflow.com/q/48061659
has comment: http://stackoverflow.com/comment/83112671
score: 5

http://stackoverflow.com/comment/83195803
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48109598
has text: I think you can drop `apply` which should make the solution a bit faster and easier to read like so `df.groupby("id")["company"].shift().bfill().ne(df["company"]).astype(int)`

http://stackoverflow.com/comment/83209493
type: Comment
comment on: http://stackoverflow.com/a/48116431
score: 0
type: AnswerComment
has text: Ok, youre right ! The file goes to its final destination, everything is ok, but django wait until the file is deleted from the tmp dir to send the 201 code. Which is a bit of problem for me in terms of performance

http://stackoverflow.com/q/48048515
tagged with: function
tagged with: nltk
has answer: http://stackoverflow.com/a/48048655
has title: Rewrite NLTK code to a function which can be used multiple times in Python
downvote count: 4
tagged with: pandas
answer count: 1
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48049087
score: -3
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83068557
linked to: http://stackoverflow.com/q/20109391
type: Question
linked to: http://stackoverflow.com/q/47769818
has body: How to rewrite my code into a function which can be called again My code stopwords=nltk.corpus.stopwords.words('english') user_defined_stop_words=['st','rd','kwun tong','kwai chung','kwun','tong'] new_stop_words=stopwords+user_defined_stop_words data['Clean_addr'] = data['Adj_Addr'].apply(lambda x: ' '.join([item.lower() for item in x.split()])) data['Clean_addr']=data['Clean_addr'].apply(lambda x:"".join([item.lower() for item in x if not item.isdigit()])) data['Clean_addr']=data['Clean_addr'].apply(lambda x:"".join([item.lower() for item in x if item not in string.punctuation])) data['Clean_addr'] = data['Clean_addr'].apply(lambda x: ' '.join([item.lower() for item in x.split() if item not in (new_stop_words)])) cv = CountVectorizer( max_features = 200,analyzer='word',ngram_range=(1, 3)) cv_addr = cv.fit_transform(data.pop('Clean_addr')) for i, col in enumerate(cv.get_feature_names()): data[col] = pd.SparseSeries(cv_addr[:, i].toarray().ravel(), fill_value=0) Any help appreciated.

http://stackoverflow.com/a/48087645
answers question: http://stackoverflow.com/q/48087613
score: 0
type: Answer
has body: import is a command from imagemagick and graphicsmagick, you are trying to import a module python in you terminal, but, you should import in python shell: $ python Python 3.6.3 (default, Oct 9 2017, 12:11:29) [GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import cv2 &gt;&gt;&gt; code_here &gt;&gt;&gt; exit() OVERVIEW from import from imagemagick. The `import` program is a member of the ImageMagick(1) suite of tools. Use it to capture some or all of an X server screen and save the image to a file. For more information about the import command, point your browser to file:///usr/share/doc/ImageMagick-6/www/import.html or http://www.imagemag‐ ick.org/script/import.php.

http://stackoverflow.com/q/48149903
has body: I need some help with the Google Assistant on Raspberry Pi 3 model B. I have followed a tutorial and done everything right. At the end I tried to start it with: (env) pi@raspberrypi:~ $ python -m googlesamples.assistant.grpc.pushtotalk But then I got: INFO:root:Connecting to embeddedassistant.googleapis.com Traceback (most recent call last): File "/usr/lib/python3.5/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/grpc/pushtotalk.py", line 434, in &lt;module&gt; main() File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 722, in __call__ return self.main(*args, **kwargs) File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 697, in main rv = self.invoke(ctx) File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 895, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/pi/env/lib/python3.5/site-packages/click/core.py", line 535, in invoke return callback(*args, **kwargs) File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/grpc/pushtotalk.py", line 332, in main flush_size=audio_flush_size File "/home/pi/env/lib/python3.5/site-packages/googlesamples/assistant/grpc/audio_helpers.py", line 187, in __init__ blocksize=int(block_size/2), # blocksize is in number of frames. File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 1256, in __init__ **_remove_self(locals())) File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 772, in __init__ 'Error opening {0}'.format(self.__class__.__name__)) File "/home/pi/env/lib/python3.5/site-packages/sounddevice.py", line 2563, in _check raise PortAudioError(errormsg, err) sounddevice.PortAudioError: Error opening RawStream: Invalid sample rate [PaErrorCode -9997] UPDATE: I now type in: (env) pi@raspberrypi:~ $ python -m googlesamples.assistant.grpc.pushtotalk INFO…
has comment: http://stackoverflow.com/comment/83309198
has comment: http://stackoverflow.com/comment/83284242
answer count: 0
has title: Google Assistant on raspberry pi
has comment: http://stackoverflow.com/comment/95262124
has comment: http://stackoverflow.com/comment/83291678
has comment: http://stackoverflow.com/comment/83278844
type: Question
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/83309470
score: 0
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/83292032
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83290858

http://stackoverflow.com/q/48016370
has answer: http://stackoverflow.com/a/48016841
has answer: http://stackoverflow.com/a/48017448
favorite count: 0
has comment: http://stackoverflow.com/comment/83002927
answer count: 3
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/48016467
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83002503
accepted answer: http://stackoverflow.com/a/48017448
upvote count: 1
has body: I have a CSV with a column like LABEL a b a a c n o ye s I want to split it into something like: LABEL_a LABEL_b LABEL_c LABEL_n_o LABEL_ye_s 1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 How to do such thing with pandas?
type: Question
has title: How to split a CSV column with repeated text into split 0-1 columns for each possible text variant?
score: 1
possible better answer: http://stackoverflow.com/a/48016841
downvote count: 0

http://stackoverflow.com/a/60813446
has body: The easiest way to solve this would be to Replace the CuDNN layers with regular keras layer, ie. convert CudNNLSTM to LSTM ,etc If using Google Colab go to Runtime>Change Runtime Settings and set the accelerator to GPU
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48086014

http://stackoverflow.com/a/48046684
has comment: http://stackoverflow.com/comment/83068204
score: 2
has comment: http://stackoverflow.com/comment/83075508
has comment: http://stackoverflow.com/comment/83077157
downvote count: 0
has comment: http://stackoverflow.com/comment/83070172
has comment: http://stackoverflow.com/comment/83075840
has body: I tried several methods and this is one that seems to work. This method use a counter to count all occurances first and then build the dictionary. Thanks @Stefan Pochmann to provide benchmark scripts. One I used is from ideone.com/ckF0X5 I am using Python 3.6 and the result is tested on my computer. from timeit import timeit from collections import defaultdict, Counter from random import shuffle from itertools import product def f(): # OP's method modified with Tom Karzes' answer above. d = {} for i, j in edges: if i not in d: d[i] = {j: 1} elif j in d[i]: d[i][j] += 1 else: d[i][j] = 1 def count_first(): d = dict() for (v, w), c in Counter(edges).items(): if v not in d: d[v] = {w: c} else: d[v][w] = c # Alternatively, (Thanks to Jean-François Fabre to point it out.) # d = defaultdict(lambda : defaultdict(int)) # for (v, w), c in Counter(edges).items(): # d[v][w] = c edges = list(product(range(300), repeat=2)) * 10 shuffle(edges) # %timeit f() 270 ms ± 23.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # %timeit count_first() 180 ms ± 15.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) Declaimer: The results of count_first() that I get from the ideone.com is, however, slower than the OP's answer, f() here. Stefan Pochmann did a benchmark experiment to compare different approaches in both Python 2 and 3. His result in Python 2 can be found here. For Python 3, check this. Credits to him and thanks his code review.
upvote count: 2
answers question: http://stackoverflow.com/q/48046242
has comment: http://stackoverflow.com/comment/83070359
type: Answer

http://stackoverflow.com/comment/83464277
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48149624
has text: hi @jezrael , I 've a follow-up question on last week's thread. I also want to capture missing data in my bins such as [-np.inf, "", 100, 300, np.inf] and label them as labels=['missing_data',1,2,3] . How can I do that?
type: Comment

http://stackoverflow.com/a/48170947
has body: Not sure what you want, but using any as value is wrong unless it's correct to call validate with any as second parameter: validate(msg, any) To check if topic is not None use topic is not None. def validate(message, topic=None): if topic is not None or topic == message.topic: accept() else: reject() ... It's possible that you want and instead or.
answers question: http://stackoverflow.com/q/48170638
score: 0
type: Answer

http://stackoverflow.com/q/48055894
has body: So i got my dataframe (df1): Number Name Gender Hobby 122 John Male - 123 Patrick Male - 124 Rudy Male - I want to add data to hobby based on number column. Assuming i've got my list of hobby based on its number on different dataframe. Like Example (df2): Number Hobby 124 Soccer ... ... ... ... and df3 : Number Hobby 122 Basketball ... ... ... ... How can i achieve this dataframe: Number Name Gender Hobby 122 John Male Basketball 123 Patrick Male - 124 Rudy Male Soccer So far i've already tried this following solutions : Select rows from a DataFrame based on values in a column in pandas but its only selecting some data. How can i update the 'Hobby' column ? Thanks in advance.
has comment: http://stackoverflow.com/comment/83084070
answer count: 1
score: 0
tagged with: pandas
duplicate of: http://stackoverflow.com/q/36413993
has answer: http://stackoverflow.com/a/48055990
linked to: http://stackoverflow.com/q/36413993
has comment: http://stackoverflow.com/comment/83084128
type: UnansweredQuestion
has title: Add data from multiple dataframe by its index using pandas
tagged with: python
has comment: http://stackoverflow.com/comment/83084035
linked to: http://stackoverflow.com/q/17071871
has comment: http://stackoverflow.com/comment/83084085
type: Question

http://stackoverflow.com/comment/83187881
type: Comment
has text: i updated the question. i am still running into the same problem. I also have a question about you mentioning "install for user running x11" what does this mean?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48105487

http://stackoverflow.com/a/48069359
has comment: http://stackoverflow.com/comment/83112712
type: Answer
answers question: http://stackoverflow.com/q/48069241
has body: You didn't slice data_processed properly. I think that you have redundant space between int(val_split) and :. I'm not sure what were your intentions, but this answer should cover probable scenarios.
has comment: http://stackoverflow.com/comment/83112694
has comment: http://stackoverflow.com/comment/83112773
has comment: http://stackoverflow.com/comment/83112579
has comment: http://stackoverflow.com/comment/83112517
has comment: http://stackoverflow.com/comment/83127717
score: 0

http://stackoverflow.com/q/48053768
has answer: http://stackoverflow.com/a/48061869
type: AnsweredQuestion
tagged with: discord.py
downvote count: 3
accepted answer: http://stackoverflow.com/a/48061869
has title: How can I make my Discord bot respond to mentions?
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83096456
has comment: http://stackoverflow.com/comment/83079820
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/48053853
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48053853
upvote count: 3
has body: I'm trying to make my Discord bot respond to mentions like "@TLG-bot#5376 how old are you?" I'm using Discord.py to achieve this. I was trying to turn my bot into a conversation bot, but no need now :)
score: 0
has comment: http://stackoverflow.com/comment/83101001

http://stackoverflow.com/comment/83267437
score: 0
type: Comment
has text: Awesome. Thanks a lot!
type: AnswerComment
comment on: http://stackoverflow.com/a/48144545

ajax
tags question: http://stackoverflow.com/q/48082720
tags question: http://stackoverflow.com/q/48095677
tags question: http://stackoverflow.com/q/48097297
type: Tag
tags question: http://stackoverflow.com/q/48152431
tags question: http://stackoverflow.com/q/48032772
tags question: http://stackoverflow.com/q/48152574
tags question: http://stackoverflow.com/q/48126969
tags question: http://stackoverflow.com/q/48117752
tags question: http://stackoverflow.com/q/48102595
tags question: http://stackoverflow.com/q/48131317
tags question: http://stackoverflow.com/q/48018281
tags question: http://stackoverflow.com/q/48015074
tag name: ajax

http://stackoverflow.com/comment/83083825
score: 0
type: Comment
type: QuestionComment
has text: I assume shells parse parameters in some way and handle escaped sequences. I was stating that I'm looking for a similar function.
comment on: http://stackoverflow.com/q/48055752

http://stackoverflow.com/q/48028274
has answer: http://stackoverflow.com/a/48028345
has answer: http://stackoverflow.com/a/48028363
answer count: 2
upvote count: 0
favorite count: 0
has title: ValueError: invalid literal for int() with base 10 : '1 2 3 4 5'
has comment: http://stackoverflow.com/comment/83026520
has comment: http://stackoverflow.com/comment/83026630
tagged with: python
accepted answer: http://stackoverflow.com/a/48028363
has body: this is the code just to find some sort of product :print the product of all the number in this array Modulo 10^9+7 n=int(input()) answer=1 b=10**9 array_1=[] for i in range(n): array_1.append(int(input())) for j in range(n): answer=(answer*array_1[j])% (b+7) print(answer) this my code in python 3 working properly in jupyter notebook, but on python (3.5.2) it is showing error for input 5 and then 1 2 3 4 5 Execution failed. ValueError: invalid literal for int() with base 10 : '1 2 3 4 5' Stack Trace: Traceback (most recent call last): File "/hackerearth/PYTHON3_46/s_ad.py3", line 16, in array_1.append(int(input())) ValueError: invalid literal for int() with base 10: '1 2 3 4 5' please some one help me to solve this error as i m newbie in python
type: AnsweredQuestion
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/48028345
has comment: http://stackoverflow.com/comment/83026649
score: -1

http://stackoverflow.com/q/48053979
has answer: http://stackoverflow.com/a/72034124
favorite count: 0
has answer: http://stackoverflow.com/a/77039918
has body: I'm trying to output the values of 2 lists side by side using list comprehension. I have an example below that shows what I'm trying to accomplish. Is this possible? code: #example lists, the real lists will either have less or more values a = ['a', 'b', 'c,'] b = ['1', '0', '0'] str = ('``` \n' 'results: \n\n' 'options votes \n' #this line is the part I need help with: list comprehension for the 2 lists to output the values as shown below '```') print(str) #what I want it to look like: ''' results: options votes a 1 b 0 c 0 '''
has answer: http://stackoverflow.com/a/48054026
has answer: http://stackoverflow.com/a/48054050
possible better answer: http://stackoverflow.com/a/48054025
has answer: http://stackoverflow.com/a/48054025
has comment: http://stackoverflow.com/comment/83080308
tagged with: python
has comment: http://stackoverflow.com/comment/83080277
has title: Print 2 lists side by side
score: 14
type: AnsweredQuestion
upvote count: 14
accepted answer: http://stackoverflow.com/a/48054026
has answer: http://stackoverflow.com/a/76090447
type: Question
downvote count: 0
answer count: 6

http://stackoverflow.com/q/48108031
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 1
upvote count: 1
tagged with: django-upgrade
type: Question
tagged with: django-migrations
has body: While upgrading django version from 1.7 to 1.8, I got a new migration called 0002_remove_content_type_name, after that I migrated that file, then I run my project, after that, it shows below error. (1054, "Unknown column 'django_content_type.name' in 'field list'") Then I checked the ContentType model in django.contrib files in packages, there I found the below code, class ContentType(models.Model): name = models.CharField(max_length=100) app_label = models.CharField(max_length=100) model = models.CharField(_('python model class name'), max_length=100) objects = ContentTypeManager() Due to the available of name field, I got the unknown column error, We should not edit the package file(like commenting the name field list in the model file), also we have to migrate the changes given when upgrading django version 1.7 to 1.8. Give me the best solution to resolve this issue. Thanks.
has answer: http://stackoverflow.com/a/48108447
answer count: 1
downvote count: 0
favorite count: 0
has title: Django version upgrade 1.7 to 1.8 - content type issue

http://stackoverflow.com/q/48015101
has answer: http://stackoverflow.com/a/48015138
score: 0
answer count: 1
has title: Neural Network: Extra features used for training but not for predicting new data
tagged with: recurrent-neural-network
has body: I want to do a neural network to predict who is going to win a soccer game. I have several features (like the team, the physical shape of the team, etc.) and an output, telling which team won (or if there was a die). In my training, I want to add features like the number of goals these teams scored. The problem is that I won't be able to include these features when predicting the final result of a future game. Is there a way to do it ? I'm using Keras in Python as a library to easily build neural networks.
tagged with: neural-network
type: UnansweredQuestion
tagged with: keras
type: Question
tagged with: python

http://stackoverflow.com/comment/83180140
type: QuestionComment
has text: @MartijnPieters: the parenthesized part hinted at a possible solution. Would that not work, then?
comment on: http://stackoverflow.com/q/48102126
score: 0
type: Comment

http://stackoverflow.com/a/48120862
type: AcceptedAnswer
type: Answer
has body: The neo4django repository hasn't been updated in years. The requirements file shows that it doesn't support Django 1.6, let alone Django 2.0. Even if you changed that so that Django wasn't downgraded, the two libraries aren't going to work together.
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48120696
answers question: http://stackoverflow.com/q/48120696
upvote count: 1

http://stackoverflow.com/comment/83328766
type: Comment
type: QuestionComment
has text: Good question, but should be `vmax = 11` for plot provided. :)
comment on: http://stackoverflow.com/q/48172928
score: 0

http://stackoverflow.com/a/48099068
downvote count: 0
has body: A straightforward solution is to use string Templates. They're safe and designed for this purpose. In this snippet, we create a template with all our html code using the string.Template constructor, and then the .substitute() method returns our html code when we specify values for the placeholders in the template. from string import Template html_template = Template("""My name is $name""") html = html_template.substitute(name='Pepito') Alternatively, for Python 3.6+, f-strings aren't necessarily bad either. They essentially allow you to execute arbitrary python code inside your strings. In this case, we have some sort of name defined ahead of time, we specify the string is an f-string by appending an f to the front, and everything in curly braces is executed as raw python code -- in this case replacing {name} with the contents of the name variable. name = 'Pepito' html = f"""My name is {name}""" One advantage these methods have over normal string formatting is that in longer html documents, you are likely to reuse each variable more than once, and it is convenient to be able to call them by name rather than trying to recall the exact order you placed them into whatever you're calling a template string. This makes it more maintainable in the future as well, should you ever decide to change what the html code will look like.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48098901
has comment: http://stackoverflow.com/comment/83202960
has comment: http://stackoverflow.com/comment/83208154
type: Answer
accepted answer of: http://stackoverflow.com/q/48098901
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83218167

http://stackoverflow.com/q/48099934
tagged with: pandas
answer count: 1
has body: Right now I create a multi-column DataFrame as following: column1 = ["A","B","C"] column2 = ["a","b","c"] tuples = [] for c1 in column1: for c2 in column2: tuples += [(i1,i2)] columns = pd.MultiIndex.from_tuples(tuples, names=['Large index', 'Small index']) q = pd.DataFrame(index = t, columns = columns ) q.loc[:, ("A","a")] = 1 Now I wonder: Is there an easier syntax to deliver the same? Cheers! edit: Corrected typos.
accepted answer: http://stackoverflow.com/a/48099998
has comment: http://stackoverflow.com/comment/83174960
tagged with: python
has answer: http://stackoverflow.com/a/48099998
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83174923
type: Question
has title: Easier way to create pandas multi-column Dataframe?
has comment: http://stackoverflow.com/comment/83174885
score: 0
has comment: http://stackoverflow.com/comment/83175048

http://stackoverflow.com/a/48083250
score: 0
has comment: http://stackoverflow.com/comment/83141552
type: Answer
has comment: http://stackoverflow.com/comment/83191065
has comment: http://stackoverflow.com/comment/83141510
has comment: http://stackoverflow.com/comment/83141598
has comment: http://stackoverflow.com/comment/83141835
answers question: http://stackoverflow.com/q/48069247
has body: As hinted in my OP comment, if there are only {}s in there with no characters in between then the following works (tested with Python 3.6) import binascii import os random_string = """ asdasdasd23123asdnos{}n asdnoiaf{}aosndiasdasd asd{}1239i123nig hpodpfh{}askmdiasd {}asdasdasd """ def get_random(n): out = set() while len(out) &lt; n: out.add(binascii.b2a_hex(os.urandom(1)).decode()) return list(out) print(random_string.format(*get_random(random_string.count('{}')))) Output: asdasdasd23123asdnos51n asdnoiaf50aosndiasdasd asdf91239i123nig hpodpfhb6askmdiasd 87asdasdasd

http://stackoverflow.com/a/48068887
has comment: http://stackoverflow.com/comment/83130947
has comment: http://stackoverflow.com/comment/83134858
has comment: http://stackoverflow.com/comment/83137670
answers question: http://stackoverflow.com/q/48068584
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48068584
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83136279
has body: Wow! Absolutely loved your code. It worked like a charm improving the total efficiency by 400x. I'll try to read more about numba and jit compilers, but can you write briefly of why it is so efficient. Thanks once again for all the help! – Ram Jan 3 '18 at 20:30 We can quite easily get somewhere under 77 [ms], but it takes mastering a few steps to get there, so let's start: Q: why parallel operations are taking more time? Because the proposed step with joblib creates that many full-scale process copies - so as to escape from the GIL-stepped pure-[SERIAL] dancing ( one-after-another ) but (!) this includes add-on costs of all the memory transfers ( very expensive / sensitive for indeed large numpy arrays ) of all variables and the whole python interpreter and its internal state, before it gets to start doing a first step on the "usefull" work on your "payload"-calculation strategy, so the sum of all these instantiation overheads can easily become larger, than an overhead-agnostic expectation of an inversely proportional 1 / N factor, where you set the N ~ num_cores. For details, read the mathematical formulation in the tail part of Amdahl's Law re-formulation here. Q:can help improve the efficiency of the above code? Save as much as possible on all overhead costs: - where possible: - on process spawn-side, try to use n_jobs = ( num_cores - 1 ) to let more space for the "main" process going forward and benchmark if performance goes up - on process termination-side, avoiding to collect-and-construct a new ( possibly great in size ) object from returning values, but rather pre-allocate a just-enough large process-local data structures and return some efficient, serialised for easy and non-blocking coalescing of the per-partes returned results' alignments. Both of these "hidden" costs are your main design enemies, as they get linearly added to the pure-[SERIAL] part of the computing-path of the whole problem solution ( ref.: the effects of both of these in the overhead-s…
has comment: http://stackoverflow.com/comment/83144157
type: Answer

http://stackoverflow.com/comment/83320633
has text: I think passing a string is more safe.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48170638
type: Comment

http://stackoverflow.com/comment/83314448
score: 0
type: Comment
type: QuestionComment
has text: I think the problem occurs because `numpy` uses c-type integers internally, while the regular multiplication uses `python` integers, which have a much larger [maximum value](https://stackoverflow.com/a/7604981/2454357).
comment on: http://stackoverflow.com/q/48167361

http://stackoverflow.com/comment/83236185
has text: It is currently the same as list, but I will be adding some more methods to it later. Are there any other ways of getting an object to have list-like behaviour? (eg. myList[3] = "bacon")
type: QuestionComment
comment on: http://stackoverflow.com/q/48129617
score: 0
type: Comment

http://stackoverflow.com/q/48073980
tagged with: python
has answer: http://stackoverflow.com/a/48081972
has answer: http://stackoverflow.com/a/48074645
score: 4
tagged with: robo3t
type: UnansweredQuestion
tagged with: pymongo
type: Question
tagged with: performance
linked to: http://stackoverflow.com/q/35140183
has title: Pymongo read much slower than mongo client(robomongo)
upvote count: 4
tagged with: mongodb
answer count: 2
has body: It is very quick to query in robomongo, below pic show I do retrieve 500 doc back: I have created index at result.type, my test code: def get_test_data(limit): return collection.find({'result.type':'detail'})[:limit] def test_one_read_multi_process(): print('mongodb read') t = Timer() TASKS = list(get_test_data(500)) print(t.elapsed_time, '\n') pymongo takes 21.716s , it is too slow. test on mongodb 3.6, pymongo latest, python 2&amp;3 Maybe relate to Pymongo significantly slower than mongo shell? But I want a solution .
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48154081
has comment: http://stackoverflow.com/comment/83287135
has body: This for loop should take the entered input and convert the character into an integer. input = a output = [] for char in input: num = ord(char) - 96 output.append(num) The problem is that at the end the output is equal to "[1]". &gt;&gt;&gt;print(output) &gt;&gt;&gt;[1] I need it to be an int to multiply it.
has comment: http://stackoverflow.com/comment/83287446
type: Question
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/83288130
favorite count: 0
has answer: http://stackoverflow.com/a/48154651
has comment: http://stackoverflow.com/comment/83287134
has title: Python For Loop Output Integer
downvote count: 4
tagged with: integer
upvote count: 0
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/48154280
tagged with: python
has comment: http://stackoverflow.com/comment/83287213

http://stackoverflow.com/q/48152279
has comment: http://stackoverflow.com/comment/83283935
has comment: http://stackoverflow.com/comment/83284834
type: Question
has comment: http://stackoverflow.com/comment/83283989
has comment: http://stackoverflow.com/comment/83284017
has title: Tensorflow won't import in my Python
has comment: http://stackoverflow.com/comment/83283062
answer count: 1
has comment: http://stackoverflow.com/comment/83282940
score: 0
has comment: http://stackoverflow.com/comment/83283683
has comment: http://stackoverflow.com/comment/83283901
tagged with: python
has body: I followed the tutorial on Tensorflow's web site, when I type Pip3 list I can see Tensorflow 1.4 in the list but when I start the Python terminal I can't import it, it says that there is No module named 'tensorflow' even when I type Pip3 show tensorflow I can notice that it exists
has answer: http://stackoverflow.com/a/48152532
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83283123
has comment: http://stackoverflow.com/comment/83285362
tagged with: pip
linked to: http://stackoverflow.com/q/46820625
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/83283576
has comment: http://stackoverflow.com/comment/83282998

http://stackoverflow.com/comment/83050841
type: Comment
comment on: http://stackoverflow.com/a/48036169
score: 0
type: AnswerComment
has text: I recommended you run it in python3 but you ran it in python2. And suffered from the symptom described in slide 68. You didn't specify a suitable `encode=` parameter in the course of calling `open()` or `io.open()`. I wasn't kidding about python3 easing certain aspects of writing python reporting code. https://docs.python.org/3/library/io.html#io.open

http://stackoverflow.com/comment/83267850
has text: Considering Sunday is the first day of the week, I would like to add all the values that reflects to first week of 2016 which would be 20160103,20160104,20160105,20160106,20160107,20160108,20160109 into 201601 and make a new dictionary with weekly data. Did this help?
score: 0
comment on: http://stackoverflow.com/q/48144727
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83020284
has text: `datetime.datetime.now()` is not a literal. `literal_eval()` is only supposed to evaluate literals -- this is a security measure, ensuring that code can't be sneaked in in places where data is expected.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48025389
score: 0

http://stackoverflow.com/comment/112558228
has text: Please: what does "CTR" stand for? (Some other person asked in a stack over flow. It's not defined in the documentation as far as I can tell.). Thanks in advance.
type: Comment
comment on: http://stackoverflow.com/a/48694422
score: 0
type: AnswerComment

http://stackoverflow.com/q/48044353
has body: The question explains it, but what is the time complexity of the set difference operation in Python? EX: A = set([...]) B = set([...]) print(A.difference(B)) # What is the time complexity of the difference function? My intuition tells me O(n) because we can iterate through set A and for each element, see if it's contained in set B in constant time (with a hash function). Am I right? (Here is the answer that I came across: https://wiki.python.org/moin/TimeComplexity)
linked to: http://stackoverflow.com/q/7351459
tagged with: python
favorite count: 0
upvote count: 12
has comment: http://stackoverflow.com/comment/83059698
has comment: http://stackoverflow.com/comment/83059742
possible better answer: http://stackoverflow.com/a/53899538
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83059662
has answer: http://stackoverflow.com/a/53899538
downvote count: 0
tagged with: set
has comment: http://stackoverflow.com/comment/83059681
score: 12
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48044412
accepted answer: http://stackoverflow.com/a/48044412
linked to: http://stackoverflow.com/q/3949310
has title: What is the run time of the set difference function in Python?
has comment: http://stackoverflow.com/comment/83059743

http://stackoverflow.com/q/48059994
downvote count: 1
type: Question
tagged with: dataframe
has title: Mark Empty values in Pandas DataFrame Multi-Row Header
has answer: http://stackoverflow.com/a/48060654
score: 0
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/48061197
favorite count: 0
has comment: http://stackoverflow.com/comment/83093990
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83092489
possible better answer: http://stackoverflow.com/a/48061138
tagged with: python
has answer: http://stackoverflow.com/a/48062170
has answer: http://stackoverflow.com/a/48061138
type: AnsweredQuestion
has body: I have a CSV file called mrh.csv which has first two rows representing the header: Name,Height,Age "",Metres,"" A,-1,25 B,95,-1 I am using the following code to read it into DataFrame: import pandas as pd pd.read_csv('mrh.csv', header=[0,1], na_values=[-1,'']) This results in a Data Frame with the following contents: Name Height Age Unnamed: 0_level_1 Metres Unnamed: 2_level_1 0 A NaN 25.0 1 B 95.0 NaN Using the na_values parameter of read_csv I can mark the missing values marked as -1 in the file, but the missing header row values, when marked as "" (I also tried -1) are displayed as Unnamed: x_level_y (or -1 if it is used instead). Is there a way to not display the missing values - to remove the Unnamed: x_level_y or substitute it with a meaningful value? Desired output 1: Name Height Age Metres 0 A NaN 25.0 1 B 95.0 NaN Desired output 2: Name Height Age - Metres - 0 A NaN 25.0 1 B 95.0 NaN
accepted answer: http://stackoverflow.com/a/48062170
upvote count: 1

http://stackoverflow.com/q/48107754
tagged with: layer
tagged with: maya
favorite count: 0
possible better answer: http://stackoverflow.com/a/48113466
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/48113679
accepted answer: http://stackoverflow.com/a/48113679
type: AnsweredQuestion
has body: I'm trying to creat locators on selected vertices and make them a group. And then creat a new display layer with that group. But this doesn't work after form and I don't know why. Can I get some help? import maya.cmds as cmds sel = cmds.ls(sl=True, fl=True) for i in range(len(sel)): pos = cmds.pointPosition(sel[i]) c = cmds.spaceLocator(n="loc01" , p=(0, 0, 0) ) d = cmds.xform(c, a=True, t=(pos[0], pos[1], pos[2]) ) cmds.select(d[0]) g = cmds.group(d, n = 'loc') cmds.select(g[0]) cmds.createDisplayLayer( noRecurse=True, name='LocLayer' )
has answer: http://stackoverflow.com/a/48113466
type: Question
answer count: 2
has title: How to make a new group and display layer with selected locators? Maya Python
score: 0

http://stackoverflow.com/comment/83202856
type: QuestionComment
comment on: http://stackoverflow.com/q/48111026
has text: I've already read that, dude. [Read this](https://github.com/python-escpos/python-escpos) or [this](https://github.com/benoitguigal/python-epson-printer/blob/master/epson_printer/test/printable_image.py)
score: 0
type: Comment

http://stackoverflow.com/a/48151552
has body: You can try editing you except to: def parse_date(d): try: date = dt.timedelta(seconds=int(d)) + dt.datetime(1960, 1, 1) return date except ValueError: return pd.NaT
has comment: http://stackoverflow.com/comment/83288899
has comment: http://stackoverflow.com/comment/83285384
has comment: http://stackoverflow.com/comment/83283361
accepted answer of: http://stackoverflow.com/q/48151024
answers question: http://stackoverflow.com/q/48151024
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83281912
has comment: http://stackoverflow.com/comment/83287395
has comment: http://stackoverflow.com/comment/83285483
has comment: http://stackoverflow.com/comment/83284388
type: Answer

http://stackoverflow.com/q/48102585
has comment: http://stackoverflow.com/comment/83192797
tagged with: django
tagged with: python
has title: Django login_required decorator does not work with ip 127.0.0.1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48102890
type: Question
has answer: http://stackoverflow.com/a/48102890
score: 0
answer count: 1
has body: I have created a login system. The view is as follows: def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request,user) return redirect('home:index') else: form = AuthenticationForm() return render(request,'accounts/login.html',{'form':form}) And I added a login_required decorator to the home page as follows: @login_required(login_url="/login/") def index(request): return render(request, 'home/index.html', context) The problem is that when I access the index page with localhost:8000/home/, the page is redirected correctly to the login page. But with 127.0.0.1:8000/home/ the home page is rendered and I am not redirected to the login page! Any solution? Thanks in advance!
has comment: http://stackoverflow.com/comment/83181486

lambda
tags question: http://stackoverflow.com/q/48148840
tags question: http://stackoverflow.com/q/48038974
tags question: http://stackoverflow.com/q/48079425
tags question: http://stackoverflow.com/q/48142574
tag name: lambda
tags question: http://stackoverflow.com/q/48038562
tags question: http://stackoverflow.com/q/48142102
tags question: http://stackoverflow.com/q/48126428
type: Tag
tags question: http://stackoverflow.com/q/48153715
tags question: http://stackoverflow.com/q/48105486
tags question: http://stackoverflow.com/q/48039730
tags question: http://stackoverflow.com/q/48030198
tags question: http://stackoverflow.com/q/48104577

arrays
tags question: http://stackoverflow.com/q/48116298
tags question: http://stackoverflow.com/q/48054870
tags question: http://stackoverflow.com/q/48065403
tags question: http://stackoverflow.com/q/48046028
type: Tag
tags question: http://stackoverflow.com/q/48157435
tags question: http://stackoverflow.com/q/48080480
tags question: http://stackoverflow.com/q/48037197
tags question: http://stackoverflow.com/q/48045772
tags question: http://stackoverflow.com/q/48131371
tags question: http://stackoverflow.com/q/48139239
tags question: http://stackoverflow.com/q/48159331
tags question: http://stackoverflow.com/q/48070668
tags question: http://stackoverflow.com/q/48134598
tags question: http://stackoverflow.com/q/48137724
tags question: http://stackoverflow.com/q/48068011
tags question: http://stackoverflow.com/q/48040687
tags question: http://stackoverflow.com/q/48116971
tags question: http://stackoverflow.com/q/48080414
tags question: http://stackoverflow.com/q/48105256
tags question: http://stackoverflow.com/q/48095508
tags question: http://stackoverflow.com/q/48142780
tags question: http://stackoverflow.com/q/48061184
tags question: http://stackoverflow.com/q/48135088
tags question: http://stackoverflow.com/q/48083608
tags question: http://stackoverflow.com/q/48044980
tags question: http://stackoverflow.com/q/48141267
tags question: http://stackoverflow.com/q/48108467
tags question: http://stackoverflow.com/q/48070388
tags question: http://stackoverflow.com/q/48057845
tags question: http://stackoverflow.com/q/48163799
tags question: http://stackoverflow.com/q/48078489
tags question: http://stackoverflow.com/q/48118345
tags question: http://stackoverflow.com/q/48125610
tags question: http://stackoverflow.com/q/48036861
tags question: http://stackoverflow.com/q/48117288
tags question: http://stackoverflow.com/q/48045185
tags question: http://stackoverflow.com/q/48085507
tags question: http://stackoverflow.com/q/48072007
tags question: http://stackoverflow.com/q/48065878
tags question: http://stackoverflow.com/q/48038577
tags question: http://stackoverflow.com/q/48104401
tags question: http://stackoverflow.com/q/48082090
tag name: arrays
tags question: http://stackoverflow.com/q/48053572
tags question: http://stackoverflow.com/q/48079421
tags question: http://stackoverflow.com/q/48105979
tags question: http://stackoverflow.com/q/48146072
tags question: http://stackoverflow.com/q/48081672
tags question: http://stackoverflow.com/q/48071144
tags question: http://stackoverflow.com/q/48157476
tags question: http://stackoverflow.com/q/48131560
tags question: http://stackoverflow.com/q/48118872
tags question: http://stackoverflow.com/q/48069701
tags question: http://stackoverflow.com/q/48030280
tags question: http://stackoverflow.com/q/48130160
tags question: http://stackoverflow.com/q/48123817
tags question: http://stackoverflow.com/q/48161132
tags question: http://stackoverflow.com/q/48066662
tags question: http://stackoverflow.com/q/48117118
tags question: http://stackoverflow.com/q/48053512
tags question: http://stackoverflow.com/q/48099697
tags question: http://stackoverflow.com/q/48118831
tags question: http://stackoverflow.com/q/48139549
tags question: http://stackoverflow.com/q/48037294
tags question: http://stackoverflow.com/q/48106028
tags question: http://stackoverflow.com/q/48103802
tags question: http://stackoverflow.com/q/48055971
tags question: http://stackoverflow.com/q/48068584
tags question: http://stackoverflow.com/q/48031622
tags question: http://stackoverflow.com/q/48080163
tags question: http://stackoverflow.com/q/48054473
tags question: http://stackoverflow.com/q/48077655
tags question: http://stackoverflow.com/q/48159608
tags question: http://stackoverflow.com/q/48034593
tags question: http://stackoverflow.com/q/48157001
tags question: http://stackoverflow.com/q/48066816
tags question: http://stackoverflow.com/q/48038535
tags question: http://stackoverflow.com/q/48085171
tags question: http://stackoverflow.com/q/48092288

http://stackoverflow.com/q/48129942
accepted answer: http://stackoverflow.com/a/48130152
favorite count: 0
has body: I made a program that asks you at the end for a restart. I import os and used os.execl(sys.executable, sys.executable, * sys.argv) but nothing happened, why? Here's the code: restart = input("\nDo you want to restart the program? [y/n] &gt; ") if str(restart) == str("y"): os.execl(sys.executable, sys.executable, * sys.argv) # Nothing hapens else: print("\nThe program will be closed...") sys.exit(0)
upvote count: 8
has answer: http://stackoverflow.com/a/78432582
has comment: http://stackoverflow.com/comment/83237326
has answer: http://stackoverflow.com/a/72959759
tagged with: restart
tagged with: python
has comment: http://stackoverflow.com/comment/83236813
type: AnsweredQuestion
downvote count: 3
type: Question
tagged with: python-os
has answer: http://stackoverflow.com/a/48130152
has title: Python restart program
has answer: http://stackoverflow.com/a/48130340
has comment: http://stackoverflow.com/comment/83237352
has comment: http://stackoverflow.com/comment/83236753
score: 5
has comment: http://stackoverflow.com/comment/83237196
possible better answer: http://stackoverflow.com/a/48130340
has answer: http://stackoverflow.com/a/48130256
answer count: 6
has answer: http://stackoverflow.com/a/70148443

http://stackoverflow.com/comment/83112087
has text: Well you need to create your locale in your root project, next to templates and static, then you need to run the command from your project root where manage.py is. Check the notes here https://docs.djangoproject.com/en/2.0/topics/i18n/translation/#message-files
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48067894

http://stackoverflow.com/comment/83125413
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48074925
type: AnswerComment
has text: So, basically, you're saying: go for the unicodedata solution? Thanks for your thorough reply. I'm neither an expert with Unicode nor with CJK languages.

http://stackoverflow.com/comment/83239795
type: Comment
has text: @Info-Screen, I know. He wrote: " it shows in terminal that the message is being sent"...Maybe he is seeing it because of the console setting as EMAIL_BACKEND...
score: 0
comment on: http://stackoverflow.com/q/48023948
type: QuestionComment

http://stackoverflow.com/comment/83276602
comment on: http://stackoverflow.com/a/48149010
has text: It's for a school project and I can't use libraries or existing code. So I do not know if using http://web.archive.org/web/20131017130434/http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ is a good idea.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83134050
has text: @Ryan you are looking for where i.e `np.where(arr!=-1024,arr,0)`
type: Comment
comment on: http://stackoverflow.com/a/48079944
score: 0
type: AnswerComment

http://stackoverflow.com/comment/112501789
has text: i am trying to use something similar. is there a way for the client to timeout if the server is not running(flask_socketio)(usually the server powers off/disconnects) right now my client just waits for the server, i would want it to return if there is no connection available.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48160130

http://stackoverflow.com/q/48055678
score: 4
answer count: 2
tagged with: crtp
accepted answer: http://stackoverflow.com/a/48055788
possible better answer: http://stackoverflow.com/a/48055785
has body: I want to access a member (variable) of a derived class from a base class in python. In c++ I can use the CRTP design pattern for this. In c++, for example, I would do something like this: #include &lt;iostream&gt; template &lt;class derived&gt; class Base { public: void get_value() { double value = static_cast&lt;derived *&gt; (this) -&gt; myvalue_; std::cout&lt;&lt; "This is the derived value: " &lt;&lt; value &lt;&lt; std::endl; } }; class derived:public Base&lt;derived&gt;{ public: double myvalue_; derived(double &amp;_myvalue) { myvalue_ = _myvalue; } }; Usage: int main(){ double some_value=5.0; derived myclass(some_value); myclass.get_value(); // This prints on screen "This is the derived value: 5" }; Any way I can implement this functionality in python? What I want to do is to have a single base class that has a common set of functions that are based on derived class member variables. I want to avoid rewriting/repeating this common set of functions in all derived classes.
has answer: http://stackoverflow.com/a/48055785
upvote count: 4
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48055788
linked to: http://stackoverflow.com/q/46007544
type: Question
has title: How to implement CRTP functionality in python?
tagged with: python
tagged with: c++

http://stackoverflow.com/comment/83313315
has text: You need to clear each button individually. To do this you need to keep a list of the buttons you create. I have updated the answer to show you how.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48149989

http://stackoverflow.com/a/48073098
downvote count: 0
has comment: http://stackoverflow.com/comment/83124727
type: Answer
has comment: http://stackoverflow.com/comment/83121512
score: 7
accepted answer of: http://stackoverflow.com/q/48063047
answers question: http://stackoverflow.com/q/48063047
has comment: http://stackoverflow.com/comment/83126216
has body: Just ran into this issue. Downgrading the pandas version seem to work (tested on Airflow v1.8.0): pip install pandas==0.18.1 For more details: https://issues.apache.org/jira/browse/AIRFLOW-1179 Or if you are using Airflow 1.8.2 or above. pip install pandas-gbq
upvote count: 7
type: AcceptedAnswer

http://stackoverflow.com/a/48118457
upvote count: 1
has comment: http://stackoverflow.com/comment/83213964
score: 1
answers question: http://stackoverflow.com/q/48118009
downvote count: 0
has comment: http://stackoverflow.com/comment/83221156
type: Answer
has comment: http://stackoverflow.com/comment/83214123
has body: You are working with screen coordinates. You only move the walls while checking for keypresses; you should move the enemies at the same time. But there is a far better way; more expandable if you add more classes, and less confusing. Remove the keypresses check out of Wall and put them into Player. This will change the player's position in world coordinates, the same coordinates as the walls are (static) and the enemies move in (dynamic). Then draw both walls and enemies at world_position - players_position, adjusted for the player's relative position in the center. Technically even the player itself is drawn at that position – the calculation for him amounts to zero movement relative to the screen. For even more flexibility you could consider a separate Camera class, which is set up to follow the player by default. That allows you to let the camera move 'elsewhere', or if the player is near the edge of your world, let him walk off the screen center.

http://stackoverflow.com/q/48043090
tagged with: python
tagged with: c++
tagged with: opencv
answer count: 0
type: Question
has title: Generating noisy image in OpenCv-C++, corrupted by Poisson and Speckle noise
has comment: http://stackoverflow.com/comment/83058861
score: 0
has body: I tried to google a lot but could not find any C++ code to generate noisy image with poisson and speckle noise. Although, I got a code in python and tried to convert it into C++. https://stackoverflow.com/a/30624520/3465857 Please have a look, I am not sure if it is correctly done or not. Mat&amp; addPoissonNoiseIntoImage(Mat&amp; src){ unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); static Mat noisyImg = src.clone(); std::default_random_engine generator (seed); std::vector&lt;float&gt; uniqueValsOfMat = BasicAlgo::getInstance()-&gt;uniqueValuesInMat(src); unsigned long int val = uniqueValsOfMat.size(); float vals = pow(2, (ceil(log2(val)))); for(int i = 0; i &lt; src.rows; i++) { for(int j = 0; j &lt; src.cols; j++){ float pixelVal = (double)(src.at&lt;uchar&gt;(i,j)); pixelVal = pixelVal * vals; std::poisson_distribution&lt;int&gt; distribution (pixelVal); float generatedVal = distribution(generator) / float(vals); noisyImg.at&lt;uchar&gt;(i,j) = generatedVal; } } return noisyImg; } Mat&amp; addSpeckleNoiseIntoImage(Mat&amp; src, float mean, float std ){ unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); static Mat noisyImg = src.clone(); std::default_random_engine generator (seed); std::normal_distribution&lt;double&gt; distribution (mean,std); for(int i = 0; i &lt; src.rows; i++) { for(int j = 0; j &lt; src.cols; j++){ float pixelVal = (double)(src.at&lt;uchar&gt;(i,j)); while(true){ float vals = distribution(generator); pixelVal = pixelVal + pixelVal * vals; if( (pixelVal &gt; 0) &amp;&amp; (pixelVal &lt; 256) ) break; // you got the right pixel value, so break } noisyImg.at&lt;uchar&gt;(i,j) = pixelVal; } } return noisyImg; } For finding the unique values in Mat: std::vector&lt;float&gt; uniqueValuesInMat(const cv::Mat&amp; rawData, bool sort = false) { Mat input; rawData.convertTo(input, CV_32F); if (input.channels() &gt; 1 || input.type() != CV_32F) { std::cerr &lt;&lt; "unique !!! Only works with CV_32F…
has comment: http://stackoverflow.com/comment/83057493
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/14435632

pymysql
tags question: http://stackoverflow.com/q/48061068
tags question: http://stackoverflow.com/q/48039515
type: Tag
tags question: http://stackoverflow.com/q/48145283
tag name: pymysql
tags question: http://stackoverflow.com/q/48161984

http://stackoverflow.com/a/48123834
score: 1
has comment: http://stackoverflow.com/comment/83224661
has body: df_new = df.groupby(["donorID", "recipientID"])["year"].nunique().reset_index(name="year_count") df_for_query = df_new.groupby(["donorID", "year_count"]).size().reset_index(name='numb_recipient') donorID year_count numb_recipient 0 101 2 2 1 102 1 2 2 103 2 1 The third column is how many patients that fit the year condition. The line 0 says donor 101 has 2 patients that he/she donates in exactly two years. This is not exactly your output, but you can query it easily from this df. If you want to find that the number of patients a donor donates for some number of year, say 2, run df_for_query.query("year_count == 2") donorID year_count numb_recipient 0 101 2 2 2 103 2 1 Thanks for Wen's inspiration for using nunique!
upvote count: 1
answers question: http://stackoverflow.com/q/48123740
type: Answer
has comment: http://stackoverflow.com/comment/83224623
downvote count: 0

http://stackoverflow.com/q/48030350
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48030360
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48030538
has title: Dynamically Add Rows to DataFrame
has body: Let's say I have an empty dataframe, already set up with columns, but no rows. I'm scraping some data from the web so let's say I need to add an index '2176' to the empty dataframe. How could I automatically add this row to the database when I try to assign it? Is this even pandas purpose or should I use something else?
type: Question
upvote count: 4
possible better answer: http://stackoverflow.com/a/48030538
linked to: http://stackoverflow.com/q/37216485
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48030360
score: 4

http://stackoverflow.com/comment/83065661
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48043412
has text: i thought the matching principal was to test those patterns one by one. e.g. `1` matches `(\d+)`,`a` matches `(?<=a)` which is righter before the dot `.` as matched `(\.)`. so i thought the expression should return something: `.` or `1 .`(`(?<=a)` would not return values).

http://stackoverflow.com/q/48135736
score: 92
possible better answer: http://stackoverflow.com/a/48138599
answer count: 6
has answer: http://stackoverflow.com/a/50140132
favorite count: 0
has body: I have read the documentation for np.unravel_index and played around with the function, but I can't figure out what it is doing.
upvote count: 92
tagged with: tensor
linked to: http://stackoverflow.com/q/38674027
tagged with: python
tagged with: indexing
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/73434076
has title: What is an intuitive explanation of np.unravel_index?
has comment: http://stackoverflow.com/comment/83248786
has answer: http://stackoverflow.com/a/48138599
has answer: http://stackoverflow.com/a/54704820
has answer: http://stackoverflow.com/a/62795427
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48136499
tagged with: numpy-ndarray
accepted answer: http://stackoverflow.com/a/48136499

http://stackoverflow.com/a/48029293
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48029204
type: Answer
has body: You have to work through the steps. Say we pass 3 to the function. When the function first runs, j > 1. So instead of returning 1, it returns j * [the function called with one less than j). But it can't actually return that until the function it called has returned. It keeps on doing that until j is 1. That's the base condition. When j is 1, 1 gets returned to the function above it. So. Starting with j == 3: (1) j == 3, returning j * the result of (2) (2) j ==2, returning j * the result of (3) (3) j == 1, returning 1 So the functions are called in order (1), (2), (3), but return in order (3), (2), (1). (3) returns 1 (2) takes the 1 from (3) and multiplies it by (2), resulting in 2. Then it returns that. (1) takes the 2 from (2) and multiplies it by 3, resulting in 6. It returns that as a final value. Recursive statements mean that the functions all collapse back into themselves, not that only the last statement runs.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83028720
accepted answer of: http://stackoverflow.com/q/48029204

http://stackoverflow.com/a/63077797
upvote count: 1
has body: The only way I found to pass Parameters to Databricks Python script/job from Azure Data Factory was to use shlex: import argparse, shlex parser = argparse.ArgumentParser() parser.add_argument('--arg1', type=str, required=True) parser.add_argument('--arg2', type=str, required=True) args = parser.parse_args(shlex.split(" ".join(sys.argv[1:]))) Arguments are passed by Databicks as: ["script", "--arg1 val", "--arg1 val"] while argparse expects argument names and values splitted: ["script", "--arg1", "val", "--arg1", "val"]. We first concatenate all arguments as one string and then split it with shlex to get the correct list to pass to the parse_args.
type: Answer
answers question: http://stackoverflow.com/q/48142978
downvote count: 0
score: 1

http://stackoverflow.com/a/48114758
upvote count: 4
answers question: http://stackoverflow.com/q/48114494
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/83209015
has body: You can simply provide, absolute or relative path as an argument to compile method in py_compile. For more info, read up this implementation of compile method Here . As an example you can start with this: import py_compile py_compile.compile('test.py','/Users/User/Desktop/test.pyc')
type: Answer

http://stackoverflow.com/q/48036365
answer count: 0
tagged with: javascript
tagged with: jquery
has title: Assigning variable a value in $.getJSON then accessing outside
has comment: http://stackoverflow.com/comment/83042801
type: Question
tagged with: python
tagged with: getjson
linked to: http://stackoverflow.com/q/14220321
has comment: http://stackoverflow.com/comment/83042852
has comment: http://stackoverflow.com/comment/83042813
score: 0
has body: I'm pretty new to js. I'm using flask in python to create a website. What I want to do is generate a chart using googlecharts and data from an sql database. In one of my urls, I'm "jsonifying" the data and attempting to access it in js via "$.getJSON" as follows: var males; var females; $.getJSON("/getstats", function(data){ for (obj of data){ males=obj.males; females=obj.females; } }); But the variables' values aren't changing to equal obj.females and obj.males. They do change to anything I assign them outside the $getJSON brackets. I stumbled upon Variables set during $.getJSON function only accessible within function which seemed to be similar to my question; but I tried the solution within the question's "UPDATE #2" and it still didn't work. How can I reach the values of obj.females and obj.males?
has comment: http://stackoverflow.com/comment/83043118
has comment: http://stackoverflow.com/comment/83042804
has comment: http://stackoverflow.com/comment/83042947
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/1739800
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83042906
has comment: http://stackoverflow.com/comment/83042817

http://stackoverflow.com/comment/82999763
has text: You are not copying - you are aliasing . You give a second name to the same array (which is a list btw). try `b = a[:]` this will copy it - only works if the lists content is immutable. if your list contains other lists it will "copy" the reference to that list but not the nested lists contents - that would be a deepcopy(). search SO for python + list + deep copy
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48015295
score: 1

http://stackoverflow.com/q/48075061
has body: I am having difficulty deleting a specific record from a text file when using Python. I have a customer CSV file which has four records. What I would like to do is ask the user to select a record by typing in the customer ID and then using that to find and delete the record, however, the code I have currently deletes any line with the entered number. This is the code: def deleteCustomer(login): print("\n***********\n Delete a customer\n*************\n") with open ("customers.txt") as f: print("CustID\t Name \t\t\t Customer Town \t Customer Tel Number") for row in f: field = row.split(",") custID = field[0] custFName = field[1] custLName = field[2] custTown = field[3] custTelNum = field[4] print(custID,"\t" ,custFName,custLName,"\t\t" ,custTown,"\t" ,custTelNum) while True: with open ("customers.txt","r+") as f: new_f = f.readlines() f.seek(0) searchID = input("Please enter the CustID you wish to delete :") for line in new_f: if searchID not in line: f.write(line) f.truncate() sleep(2) viewCustomers(login) When I run the code it will do the following: *********** Delete a customer ************* CustID Name Customer Town Customer Tel Number 1 Jamie John London 01792883844 2 Jim Jones Paris 01792885877 3 Bob Jones New York 01523654785 4 Alf Fisher Cardiff 01452365896 Please enter the CustID you wish to delete : If I enter 4 then it will remove every record apart from Jim Jones as he does not have a '4' in the field. ***************** View Customers ***************** CustID Name Customer Town Customer Tel Number 2 Jim Jones Paris 01792885877 Returning to the main menu in 3 seconds... Where have I gone wrong?
linked to: http://stackoverflow.com/q/4710067
type: UnansweredQuestion
tagged with: python
tagged with: text
answer count: 0
has title: Deleting specific line from a text file in Python
has comment: http://stackoverflow.com/comment/83124214
type: Question
duplicate of: http://stackoverflow.com/q/4710067
has comment: http://stackoverflow.com/comment/83124146
score: 0

http://stackoverflow.com/q/48155084
linked to: http://stackoverflow.com/q/37993175
upvote count: 1
type: Question
has title: Python - ModuleNotFound error using Anaconda
tagged with: dymola
has answer: http://stackoverflow.com/a/48157284
has body: I am trying to run this program: #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from io import open from multiprocessing import Pool import buildingspy.simulate.Simulator as si # Function to set common parameters and to run the simulation def simulateCase(s): ''' Set common parameters and run a simulation. :param s: A simulator object. ''' s.setStopTime(86400) # Kill the process if it does not finish in 1 minute s.setTimeOut(60) s.showProgressBar(False) s.printModelAndTime() s.simulate() def main(): ''' Main method that configures and runs all simulations ''' import shutil # Build list of cases to run li = [] # First model model = 'Buildings.Controls.Continuous.Examples.PIDHysteresis' s = si.Simulator(model, 'dymola', 'case1') s.addParameters({'con.eOn': 0.1}) li.append(s) # second model s = si.Simulator(model, 'dymola', 'case2') s.addParameters({'con.eOn': 1}) li.append(s) # Run all cases in parallel po = Pool() po.map(simulateCase, li) # Clean up shutil.rmtree('case1') shutil.rmtree('case2') # Main function if __name__ == '__main__': main() and I keep getting this error: File "C:/Users/Toshiba/.spyder-py3/temp.py", line 11, in &lt;module&gt; import buildingspy.simulate.Simulator as si ModuleNotFoundError: No module named 'buildingspy' I already installed the package using pip more than one time and nothing changes. What am I missing? This is the source of this code.
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83291709
has comment: http://stackoverflow.com/comment/83290975
type: UnansweredQuestion
tagged with: python
tagged with: modelica
tagged with: anaconda
score: 1

http://stackoverflow.com/a/48164477
type: Answer
answers question: http://stackoverflow.com/q/48164372
has comment: http://stackoverflow.com/comment/83344429
has comment: http://stackoverflow.com/comment/83350165
has comment: http://stackoverflow.com/comment/83344885
has comment: http://stackoverflow.com/comment/83345046
has comment: http://stackoverflow.com/comment/83344607
upvote count: 1
has comment: http://stackoverflow.com/comment/83350462
score: 1
has comment: http://stackoverflow.com/comment/83344151
has comment: http://stackoverflow.com/comment/83350110
downvote count: 0
has comment: http://stackoverflow.com/comment/83344101
has body: Since both are running in same port 80. You need to add different ServerName in each VirtualHost For more doc Require all granted WSGIDaemonProcess MyApp python-path=/home/bic/MyApp:/usr/lib/python2.7/dist-packages WSGIProcessGroup MyApp WSGIScriptAlias /MyApp /home/bic/MyApp/MyApp/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html ServerName myapp.com Alias /static /home/bic/pep_web/protocol/static Require all granted Require all granted WSGIDaemonProcess pep_web python-path=/home/bic/pep_web:/usr/lib/python2.7/dist-packages WSGIProcessGroup pep_web WSGIScriptAlias /pep_learn /home/bic/pep_web/pep_learn/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html ServerName mypepapp.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Then in /etc/hosts 127.0.0.1 localhost ::1 localhost #your local domains 127.0.0.1 myapp.com 127.0.0.1 mypepapp.com
has comment: http://stackoverflow.com/comment/83350524

http://stackoverflow.com/a/63549380
answers question: http://stackoverflow.com/q/48030567
type: Answer
downvote count: 0
has body: Suppose you are working in your users app, and the name of your custom user model is CustomUser, which is inside users/models.py. If you don't want to allow @, ., -, + in username, then create a forms.py, which will look like this: users/forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = ('username', 'first_name', 'last_name', 'email') def clean(self): cleaned_data = super(CustomUserCreationForm, self).clean() username = cleaned_data.get('username') if ('@', '.', '-', '+') in username: self.add_error('username', 'Symbols @/./-/+ are not allowed in username.') return cleaned_data # same for UserChangeForm class CustomUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = CustomUser fields = ('username', 'first_name', 'last_name') # Removed email field. Anyone won't want to change email after registering. Go as you like. def clean(self): cleaned_data = super(CustomUserChangeForm, self).clean() username = cleaned_data.get('username') if ('@', '.', '-', '+') in username: self.add_error('username', 'Symbols @/./-/+ are not allowed in username.') return cleaned_data Your custom error messages will be displayed if anyone tries to signup with @, ., -, + in username. To change the Django default description Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only., your models.py should look like this: users/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth import get_user_model from django.contrib.auth.validators import UnicodeUsernameValidator User = get_user_model class CustomUser(AbstractUser): username_validator = UnicodeUsernameValidator() username = models.CharField( "Username", max_length = 150, unique = True, help_text = ("Required. 150 characters or fewer. Letters, and digits only."), # customize the a…
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/122417700

http://stackoverflow.com/comment/83114553
has text: Yes you can make a new column using this and it takes time to understand the concept of vectorizing a solution give it some time
comment on: http://stackoverflow.com/a/48061972
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/137030602
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48168379
score: 0
has text: upstream issue: [add aiohttp.MozillaCookieJar to load/save cookies.txt files](https://github.com/aio-libs/aiohttp/issues/7998)

http://stackoverflow.com/q/48047118
has comment: http://stackoverflow.com/comment/83066168
answer count: 1
tagged with: flask
upvote count: 3
tagged with: cron
tagged with: apscheduler
has comment: http://stackoverflow.com/comment/83065828
has comment: http://stackoverflow.com/comment/83066257
favorite count: 0
has comment: http://stackoverflow.com/comment/84246241
has title: Restarting The Jobs In ApScheduler Python When the Wsgi Server is Restarted
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84265721
tagged with: python
has answer: http://stackoverflow.com/a/69650865
has body: I'm using python Apscheduler to schedule my jobs. All my jobs are stored as a cron job and use the BackgroundScheduler. I've the following codes: def letschedule(): jobstores = { 'default': SQLAlchemyJobStore(url=app_jobs_store) } executors = { 'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5) } job_defaults = { 'coalesce': False, 'max_instances': 1, 'misfire_grace_time':1200 } scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc) #jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc return scheduler And I start the job scheduler as follow in the app: sch = letschedule() sch.start() log.info('the scheduler started') And I've the following add job function. def addjobs(): jobs = [] try: sch.add_job(forecast_jobs, 'cron', day_of_week=os.environ.get("FORECAST_WEEKOFDAY"), id="forecast", replace_existing=False,week='1-53',hour=os.environ.get("FORECAST_HOUR"), minute=os.environ.get("FORECAST_MINUTE"), timezone='UTC') jobs.append({'job_id':'forecast', 'type':'weekly'}) log.info('the forecast added to the scheduler') except BaseException as e: log.info(e) pass try: sch.add_job(insertcwhstock, 'cron', id="cwhstock_data", day_of_week='0-6', replace_existing=False,hour=os.environ.get("CWHSTOCK_HOUR"), minute=os.environ.get("CWHSTOCK_MINUTE"), week='1-53',timezone='UTC') jobs.append({'job_id':'cwhstock_data', 'type':'daily'}) log.info('the cwhstock job added to the scheduler') except BaseException as e: log.info(e) pass return json.dumps({'data':jobs}) I use this in the flask application, I call the /activatejobs and the jobs are added to the scheduler and it works fine. However when I restart the wsgi server, the jobs aren't started again, I've to remove the .sqlite file and add the jobs again. What I want is the jobs are supposed to be restarted automatically once the scheduler is started (if there are already jobs in the database.) I tried to get such result tryi…
score: 3
has comment: http://stackoverflow.com/comment/83065872
tagged with: mod-wsgi
has comment: http://stackoverflow.com/comment/83065939
has comment: http://stackoverflow.com/comment/83066155
type: Question

http://stackoverflow.com/comment/83064892
type: Comment
type: QuestionComment
score: 8
comment on: http://stackoverflow.com/q/48046729
has text: you can use `if not os.path.getsize(book)` but what you've done is not necessarily unpythonic.

http://stackoverflow.com/q/48124483
downvote count: 0
type: AnsweredQuestion
score: 3
tagged with: sqlite
accepted answer: http://stackoverflow.com/a/48199130
has body: I'm trying to run a script I wrote to move some data from json files into my database, and keep getting the same error. Traceback: Traceback (most recent call last): File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: clan_participant.completed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "participant_updater.py", line 32, in &lt;module&gt; message = participant_updater() File "/home/jamtime/clansite/database_updaters.py", line 548, in participant_updater update_db() File "/home/jamtime/clansite/database_updaters.py", line 512, in update_db character=char_obj File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 653, in create return super(RelatedManager, self.db_manager(db)).create(**kwargs) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/home/jamtime/.virtualenvs/clansite/lib/python3.6/site-packages/django/db/models/base.py", li…
favorite count: 0
type: Question
tagged with: django
tagged with: python
has title: NOT NULL constraint failed error when populating foreign key field
answer count: 1
upvote count: 3
tagged with: django-models
has answer: http://stackoverflow.com/a/48199130

http://stackoverflow.com/comment/83200114
has text: @SebastianH Yes, see my edited answer. That graph collection is the one used by optimizers to select the variables they need to optimize (unless otherwise stated).
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48112248

http://stackoverflow.com/a/48081973
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48081688
has body: Charles' answer is absolutely correct. However, I'm assuming that you don't want with the shortest binary encoding of the SHA256 bash - the 32-octet string - and want something printable and somewhat human-readable. Note: However, this does not exactly apply to barcodes. At least QR codes encode binary data, so just use digest() method of your hash - that would be the most efficient encoding you can use there. Your QR code generation library should most likely support generating codes for "raw" binary strings - check your library docs and find the correct method/invocation. SHA hashes (and other hashes) don't produce or operate on characters, they work with binary data. SHA-256 produces 256 bits of data, commonly represented with 32 bytes. In particular, in Python 3 you should notice that hashlib.sha256("...").digest() returns bytes and not str. There is a convenience method hexdigest, that produces hexadecimal (base16) string that represents those bytes. You can use base32, base58, base64, baseEmoji or any other encoding that fits your requirements. Basically, your problem is actually "I have a number and want a short encoding of it". Decide on how many distinct characters you can use (encoding base) and use that. There are many libraries on PyPI that could help. python-baseconv may come handy.
type: Answer

http://stackoverflow.com/a/48054584
has comment: http://stackoverflow.com/comment/83081853
score: 0
has body: I'm not 100% sure what you're after, but maybe this will help: new_arrays = [] for index, row in dft.iterrows(): if row['a'] == 'NW': new_arrays.append(row[1:].values.reshape(3, 3)) With itertuples(), as requested in the comments: for index, row in enumerate(dft.itertuples(), 1): if row[1] == 'NW': new_arrays.append(np.array(row[2:]).reshape(3, 3)) Now you have each of the two arrays in new_arrays, and you can print them together or access individually: new_arrays[0] array([[1, 5, 11], [9, 4, 15], [13, 5, 9]], dtype=object) new_arrays[1] array([[2, 6, 12], [10, 3, 14], [14, 4, 8]], dtype=object)
has comment: http://stackoverflow.com/comment/83081740
type: Answer
has comment: http://stackoverflow.com/comment/83082368
has comment: http://stackoverflow.com/comment/83082508
answers question: http://stackoverflow.com/q/48054473

http://stackoverflow.com/q/48092184
type: Question
score: 0
answer count: 1
has title: Huge gap between two methods of measuring request time via python-requests
has body: I am trying to measure the respone time of a certain request using python-requests. import requests import time start = time.time() r = requests.get("https://www.dl.soc.i.kyoto-u.ac.jp/index.php/members/") end = time.time() print(end - start) print(r.elapsed.seconds) It gave me a result of 64.67747116088867 0.631163 Could anyone please explain the reason of this huge gap? Thanks. By the way, when I was trying the same request on Google-Chrome, actually the first result is what I want.
has comment: http://stackoverflow.com/comment/83158774
has answer: http://stackoverflow.com/a/48093218
has comment: http://stackoverflow.com/comment/83159560
tagged with: python
type: AnsweredQuestion
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83159475
tagged with: http
accepted answer: http://stackoverflow.com/a/48093218

http://stackoverflow.com/comment/83095096
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48061280
score: 1
has text: the way you use count provokes the failure. As soon as count is 4 or above, you'll be out of range in signature ...you have to handle it another way ///

http://stackoverflow.com/comment/83283482
type: QuestionComment
has text: It is hard to say what is going there. I believe you should check logs on your server (i.e. by putting there some logger string before and after the execution to track what had happened).
comment on: http://stackoverflow.com/q/48152431
score: 0
type: Comment

http://stackoverflow.com/comment/83200799
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48109650
score: 0
has text: I don't speak Python, but normally you would make mask for each colour and OR them together.

http://stackoverflow.com/comment/83067828
comment on: http://stackoverflow.com/q/48046121
score: 0
has text: You can't do this with the built-in parser - see the [note here](https://docs.djangoproject.com/en/2.0/topics/i18n/formatting/#locale-aware-input-in-forms).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83001968
type: QuestionComment
comment on: http://stackoverflow.com/q/48015368
type: Comment
score: 1
has text: @xyres Well my idea behind this is that a Product has similar and non-similar attributes. A ```Car``` and a ```CellPhone``` both have the attr 'name', 'price', etc. - but a ```CellPhone``` does not have 'number_of_wheels' (for example), and a ```Car``` does not have a 'screen_width' attr. You know?

http://stackoverflow.com/q/48075495
tagged with: http://stackoverflow.com/tag/json
upvote count: 2
downvote count: 2
linked to: http://stackoverflow.com/q/1132941
has body: I am looking for an elegant way to invert a JSON object's structure with variable depth like described below from a to b in Javascript ES6. var a = { "cookie": { "CookieMessage": { "DE": "Nachricht", "EN": "Message" } }; var b = { "DE": { "cookie": { "CookieMessage": "Nachricht" } }, "EN": { "cookie": { "CookieMessage": "Message" } } }; In Python i would do something like this, which is not very elegant as well: def find(root=[], obj=None): ret = [] for k, v in obj.items(): if isinstance(v, dict): newroot = [] newroot.extend(root) newroot.append(k) ret.extend(find(root=newroot, obj=v)) else: copy = [k] copy.extend(root) ret.append((copy, v)) return ret def invert(obj=None): ret = {} f = find(obj=obj) for p, v in f: old = ret for n in p[:-1]: if n not in old: old[n] = {} old = old[n] old[p[-1]] = v return ret a = { "cookie": { "CookieMessage": { "DE": "Nachricht", "EN": "Message" }, "CookieSorte": { "DE": "Keks", "EN": "Coook" } } } print(invert(a)) Which results in: { 'DE': { 'cookie': { 'CookieSorte': 'Keks', 'CookieMessage': 'Nachricht' } }, 'EN': { 'cookie': { 'CookieSorte': 'Coook', 'CookieMessage': 'Message' } } }
answer count: 1
accepted answer: http://stackoverflow.com/a/48075818
tagged with: javascript
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/48075818
tagged with: python
has comment: http://stackoverflow.com/comment/83124629
has comment: http://stackoverflow.com/comment/83125040
type: Question
type: AnsweredQuestion
has title: Looking for a good way to invert a JSON tree with variable depth in Javascript ES6

http://stackoverflow.com/a/48097699
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48097400
downvote count: 0
has comment: http://stackoverflow.com/comment/96658341
type: Answer
has body: I would solve it as this: #decorator def login_required(func): def wrapper(*args, **kwargs): if not args[0]: return print('not valid') return func(*args, **kwargs) return wrapper @login_required def index(request): print('1') @login_required def detail(request, id): print('2') index(True) index(False) detail(True, 1) detail(False, 1)

http://stackoverflow.com/q/48127434
has comment: http://stackoverflow.com/comment/83231492
has body: I parsed log file and now I have regexped result for every status: '/status1' '/status2' '/status3' For every result I need to keep some info : num1, num2, num3 What data structure to use in Python that I could use array of statuses in format: /status1, num1, num2, num3 /status2, num1, num2, num3 /status3, num1, num2, num3 that I could use some calculation later with these nums for every status
type: UnansweredQuestion
tagged with: struct
upvote count: 0
has comment: http://stackoverflow.com/comment/83232328
tagged with: data-structures
has answer: http://stackoverflow.com/a/48128417
favorite count: 0
type: Question
tagged with: python
tagged with: regex
score: -1
has title: What data structure to use for regexped result in Python?
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/84236231
type: AnswerComment
type: Comment
has text: My bad! `process_request` was overridden for dynamic user-agent for every request. I made the suggested changes there and boom! now it is working.
comment on: http://stackoverflow.com/a/48147130
score: 0

http://stackoverflow.com/comment/83246366
has text: @DejanDozet got it to work using your idea. Thanks again
type: QuestionComment
comment on: http://stackoverflow.com/q/48129540
type: Comment
score: 0

http://stackoverflow.com/q/48088220
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48088339
type: Question
answer count: 2
has body: I am trying to get all the paths in a python package (for example numpy) that you can use pydoc on. Ideally, this list would contain elements like: numpy numpy.linalg numpy.linalg.det ... So, ideally one would recurse into submodules and classes inside the package, and these paths would be what tab completion would give you in an enabled editor. I would prefer to get this list from the installed packages for consistency. The purpose of this list is to feed it to a fuzzy completion engine to select items to then send to pydoc, eg. by typing "det", the engine would select all entries containing that string (so I don't have to remember the full path to it), and I could choose the one I want from there. That part is easy, once I have the list of paths! It doesn't matter if this is slow, I only need to do it once and can save it to file for use later. It also doesn't matter if the list is very long. The completion engine can handle very large lists. Is there a straightforward way to do this? I have tried a few variations with the inspect module, recursing through the dict attributes, even one with rlcompleter, but so far I have either not had much success with the recursion, or the paths are not useful in pydoc.
has title: How do you get a list of pydoc accessible paths for a python package, e.g. numpy or tensorflow?
has answer: http://stackoverflow.com/a/70146937
score: 0
tagged with: pydoc

http://stackoverflow.com/a/48113457
downvote count: 0
type: Answer
upvote count: 4
has body: Yes, you need to multiply those values by 255. Actually, every cmap has parameter 'bytes': bytes : bool If False (default), the returned RGBA values will be floats in the interval [0, 1] otherwise they will be uint8s in the interval [0, 255]. def _cmap2rgb(cmap, step): from matplotlib import cm return getattr(cm, cmap)(step, bytes=True)
accepted answer of: http://stackoverflow.com/q/48112755
answers question: http://stackoverflow.com/q/48112755
has comment: http://stackoverflow.com/comment/83311493
score: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/83515864
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48248532
has text: Not necessarily in binary mode. Ok, I need to read contents from a file anyhow and set tags for the sentences (lines in file). But do you mean a tag for each line? What about if I have lines having sentences that are similar?

http://stackoverflow.com/a/48050941
score: 0
answers question: http://stackoverflow.com/q/48050884
has body: You can use the function min. It might solve your problem out. #!/usr/bin/python var list = [5.00000009, 5.000007, 5.0000075] print "min value element : ", min(list) https://www.tutorialspoint.com/python/list_min.htm
type: Answer
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/48162539
answers question: http://stackoverflow.com/q/48159051
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83325203
type: Answer
accepted answer of: http://stackoverflow.com/q/48159051
has body: This answer continues with the example provided in my answer to your earlier question Loading the same library mutiple times is indeed possible using the Library xxx WITH NAME xxxyyy format. Then you can access all of it's objects properties using the same syntax as the original. In the below example you'll find an example where the IP attribute holds a different value in each object: *** Settings *** Library one Library one WITH NAME two Library Collections *** Test Cases *** Test Case ${dict1}= Create Dictionary device=auto1 ip=192.38.19.21 secret=${EMPTY} uname=Adrija password=Hello port=22 ${dict2}= Create Dictionary device=auto2 ip=192.38.19.22 secret=${EMPTY} uname=Adrija password=Hello port=22 one.connects to ${dict1} connect=${True} two.connects to ${dict2} connect=${True} ${one} Get Library Instance one ${two} Get Library Instance two Should Be Equal As Strings ${one.ip} 192.38.19.21 Should Be Equal As Strings ${two.ip} 192.38.19.22

http://stackoverflow.com/q/48144228
has comment: http://stackoverflow.com/comment/83268743
has answer: http://stackoverflow.com/a/48145723
tagged with: python
has comment: http://stackoverflow.com/comment/83281234
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48145723
has comment: http://stackoverflow.com/comment/83269321
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48146599
has answer: http://stackoverflow.com/a/48146599
has title: How to create a Python tkinter Frame with button-like functionality?
score: 0
has body: I am looking to create a tile in tkinter that will have text in each of the corners, similar to this image: _______ |a b| |c_____d| I also want it to have the functionality of when it is clicked, to run a command function. My current idea is to create a frame which can hold four text labels, then allow that frame to be clicked. import tkinter as tk newFrame = tk.Frame() newFrame.grid(row=0,column=0) tk.Label(newFrame, text="a").grid(row=0,column=0) tk.Label(newFrame, text="b").grid(row=0,column=1) tk.Label(newFrame, text="c").grid(row=1,column=0) tk.Label(newFrame, text="d").grid(row=1,column=1) newFrame.config(command = makeFruity) Obviously, the last line doesn't work. And after searching online and reading documentation, I still have absolutely no idea how to then get that frame to hold a command. And so, I am reaching out to the experts, if anyone could help I would be very thankful!
tagged with: tkinter

http://stackoverflow.com/comment/83161483
comment on: http://stackoverflow.com/a/48093108
has text: @user9127040 I adapted my solution can you validate it again.
score: 0
type: AnswerComment
type: Comment

html-parsing
tags question: http://stackoverflow.com/q/48079366
tags question: http://stackoverflow.com/q/48054837
tags question: http://stackoverflow.com/q/48085980
tags question: http://stackoverflow.com/q/48136660
tag name: html-parsing
type: Tag
tags question: http://stackoverflow.com/q/48125988
tags question: http://stackoverflow.com/q/48057296

mean
tags question: http://stackoverflow.com/q/48038958
tags question: http://stackoverflow.com/q/48052844
tag name: mean
type: Tag

http://stackoverflow.com/a/48065474
answers question: http://stackoverflow.com/q/48065268
accepted answer of: http://stackoverflow.com/q/48065268
score: 0
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/83105257
has body: Obviously, it will print 30 at the end because your this code for i in pref_network_find: splitlines = i.split() for word in splitlines: if word in mydict: i = i.replace(word,str(mydict[word])) pref = print (i) i is 30 after execution. And you are using old variable 'i' like this for line in pref_network_find: listi.append(i) So yes the code is doing its job well, i is 30 and it is appending 30 to your result. Correct code goes like this. import re data = ['network 10.185.16.64 255.255.255.224','network 55.242.33.0 255.255.255.0','network 55.242.154.0 255.255.255.252'] pref_network_find = re.findall('(\S+\s+255.255.255.\w+)',str(data)) mydict = {"255.255.255.0":24,"255.255.255.128":25,"255.255.255.192":26,"255.255.255.224":27,"255.255.255.240":28,"255.255.255.248":29,"255.255.255.252":30} listi = [] for i in pref_network_find: splitlines = i.split() for word in splitlines: if word in mydict: i = i.replace(word,str(mydict[word])) pref = print (i) listi.append(i) print (listi) Correct me if I am wrong here, maybe you want something else, however, this is what I understood by your question.

http://stackoverflow.com/q/48023955
has comment: http://stackoverflow.com/comment/83017206
has comment: http://stackoverflow.com/comment/83017625
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83017848
type: Question
has comment: http://stackoverflow.com/comment/83017161
has comment: http://stackoverflow.com/comment/83017050
has comment: http://stackoverflow.com/comment/83017553
has comment: http://stackoverflow.com/comment/83017901
has title: Know whether a point is above the sea
tagged with: python-3.x
score: 0
tagged with: geolocation
has comment: http://stackoverflow.com/comment/83017469
tagged with: python
has comment: http://stackoverflow.com/comment/83017497
has comment: http://stackoverflow.com/comment/83017278
has body: How do I check whether a point is above the sea or not with python ? I've already tried to do it with mpl_toolkits.basemap (Basemap.is_land(x, y)) but I can't install it on windows. Is this library too old and is there any other way to do this ?
has comment: http://stackoverflow.com/comment/83017947
has comment: http://stackoverflow.com/comment/83017115
has comment: http://stackoverflow.com/comment/83017594

http://stackoverflow.com/comment/83097834
comment on: http://stackoverflow.com/q/48062522
type: Comment
type: QuestionComment
has text: Also, you have to make `splc` an explicit argument to `integrand`.
score: 0

http://stackoverflow.com/a/48080415
has comment: http://stackoverflow.com/comment/83135283
type: Answer
upvote count: 7
has comment: http://stackoverflow.com/comment/83135280
has comment: http://stackoverflow.com/comment/83135306
answers question: http://stackoverflow.com/q/48080245
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/83135224
has body: Around 1993, Python got lambda, reduce(), filter() and map(), courtesy of a Lisp hacker who missed them and submitted working patches. These Lisp-flavored constructs are considered a little alien in Python specially after the introduction of list comprehensions in 2000. So no, you don't need map, you can use list comprehensions or generator expressions. You can let your hypotenuse function take extra arguments and ignore them: def hypotenuse(base, height, **kwargs): hyp_sq=base**2+height**2 return hyp_sq**(1.0/2.0) Then you can use a list comprehension: hypotenuse_results = [(t['name'], hypotenuse(**t)) for t in triangles] hypotenuse_results.sort(key=lambda pair: pair[1]) This should perform well enough even for large len(triangles). The generator expression version is: unsorted_results = ((t['name'], hypotenuse(**t)) for t in triangles) hypotenuse_results = sorted(unsorted_results, key=lambda pair: pair[1]) Profiling both solutions and posting here would be a great exercise. thanks. is there a way to this without modifying the hypotenuse function? – canecse Sure! Just call it with both arguments: hypotenuse_results = [(t['name'], hypotenuse(t['base'], t['height'])) for t in triangles] hypotenuse_results.sort(key=lambda pair: pair[1]) Note that the accepted solution is allocating an actual list and trowing it away so you may want to use a generator expression instead of a list comprehension if you are concerned about memory footprint (specially useful if len(triangles) is big but always a good habit): hypotenuse_results = sorted( ((t['name'], hypotenuse(t['base'], t['height'])) for t in triangles), key=lambda x: x[1] )

http://stackoverflow.com/q/48052969
tagged with: plot
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48055205
tagged with: matplotlib
has body: Using: [python] [numpy] [matplotlib] So I have a 3D array to create a scatter plot making a n * n * n cube. Those points have different values of potential represented by colors. size = 11 z = y = x = size potential = np.zeros((z, y, x)) Positive = 10 Negative = -10 """ ------- Positive Polo --------- """ polox = poloy = poloz = [1,2] polos=[polox,poloy,poloz] polop = [list(x) for x in np.stack(np.meshgrid(*polos)).T.reshape(-1,len(polos))] # Positive polos list for coord in polop: potential[coord] = Positive """ ------- Negative Polo --------- """ polo2x = polo2y = polo2z = [size-3,size-2] polos2=[polo2x,polo2y,polo2z] polon = [list(x) for x in np.stack(np.meshgrid(*polos2)).T.reshape(-1,len(polos2))] # Negative polos list for coord in polon: potential[coord] = Negative I have 2 polos of values -10 and 10 at the start and the rest of the points are calculated like this: (the mean of the surrounding points, no diagonals): for z in range(1,size): for y in range(1,size): for x in range(1,size): if [z,y,x] in polop: potential[z,y,x] = Positive # If positive polo, keeps potential elif [z,y,x] in polon: potential[z,y,x] = Negative # If negative polo, keeps potential elif z!=size-1 and y!=size-1 and x!=size-1: # Sets the potential to the mean potential of neighbors potential[z][y][x] = (potential[z][y][x+1] + potential[z][y][x-1] + potential[z][y+1][x] + potential[z][y-1][x] + potential[z+1][y][x] + potential[z-1][y][x]) / 6 And for the outer cells: for z in range(0,size): for y in range(0,size): for x in range(0,size): potential[z,y,0] = potential[z,y,2] potential[z,0,x] = potential[z,2,x] potential[0,y,x] = potential[2,y,x] if z == size-1: potential[size-1,y,x] = potential[size-3,y,x] elif y == size-1: potential[z,size-1,x] = potential[z,size-3,x] elif x == size-1: potential[z,y,size-1] = potential[z,y,size-3] What I need is to show a surface connecting the points that have the same value interval 'same colors' (like from 0 to 2.5). I know that there are a lot of questi…
type: Question
upvote count: 2
tagged with: numpy
answer count: 1
linked to: http://stackoverflow.com/q/44544617
has title: Python - 2/3D scatter plot with surface plot from that data
linked to: http://stackoverflow.com/q/28687367
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48165739
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48165710
type: Answer
has comment: http://stackoverflow.com/comment/83310586
upvote count: 2
has body: Use get_dummies with replace for N and Y: df = df.join(pd.get_dummies(df['state']).replace({0:'N', 1:'Y'})) print (df) name state postcode act nsw vic 0 coles vic 2501 N N Y 1 woolworth nsw 3409 N Y N 2 big w act 3201 Y N N 3 target vic 1089 N N T Or convert to bool: df = df.join(pd.get_dummies(df['state']).astype(bool)) print (df) name state postcode act nsw vic 0 coles vic 2501 False False True 1 woolworth nsw 3409 False True False 2 big w act 3201 True False False 3 target vic 1089 False False True Or if possible 0 and 1 values: df = df.join(pd.get_dummies(df['state'])) print (df) name state postcode act nsw vic 0 coles vic 2501 0 0 1 1 woolworth nsw 3409 0 1 0 2 big w act 3201 1 0 0 3 target vic 1089 0 0 1
answers question: http://stackoverflow.com/q/48165710
score: 2
type: AcceptedAnswer

http://stackoverflow.com/a/48023381
has comment: http://stackoverflow.com/comment/83037247
accepted answer of: http://stackoverflow.com/q/48021333
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48021333
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: with the lasso_select tool you can work it like this: from bokeh.io import curdoc from bokeh.plotting import figure from bokeh.models import ColumnDataSource, Button from bokeh.layouts import column # setup plot tools = "pan,wheel_zoom,lasso_select,reset" fig = figure(title='Select points', plot_width=300, plot_height=200,tools=tools) import numpy as np x = np.linspace(0,10,100) y = np.random.random(100) + x import pandas as pd data = pd.DataFrame(dict(x=x, y=y)) # define data source src = ColumnDataSource(data) # define plot fig.circle(x='x', y='y', source=src) # define interaction def print_datapoints(): indices=src.selected['1d']['indices'] results=data.iloc[indices] resultsDict=results.to_dict()['x'] resultString=str(resultsDict) with open('tmp/datapoints.json', 'w') as f: import json json.dump(resultString, f) btn = Button(label='Selected points', button_type='success') btn.on_click(print_datapoints) curdoc().add_root(column(btn,fig)) To make the json.dump work i had to remove the first '/' from '/tmp/datapoints.json' .

http://stackoverflow.com/comment/93104355
has text: same here (on v 1.1.0)...and I cannot import it either, as suggested here https://stackoverflow.com/questions/51227745/importerror-install-xlrd-0-9-0-for-excel-support-when-using-pd-readexcel-to/51286813
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48066577

http://stackoverflow.com/comment/83153993
type: Comment
comment on: http://stackoverflow.com/a/48089764
type: AnswerComment
has text: Okay I'll try that.
score: 0

http://stackoverflow.com/comment/83083821
has text: Thank you for pointing me in the right direction. I ended up using the Flask framework to route incoming urls. For others, in the same predicament if you will be calling the url from a cross domain url you need to allow cross domain calls as well. This post helped me out: https://stackoverflow.com/questions/7023052/configure-flask-dev-server-to-be-visible-across-the-network
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48019707
type: AnswerComment

http://stackoverflow.com/a/48128417
has body: There are no "arrays" in Python, often when we talk of an "array" in Python context, we refer to NumPy array (this is not what you want here). But Python has lists that can hold objects of different types, thus it is feaseable to have e.g.: [[str, int, int, int],[str, int, int, int],...] which might be what you need. Not sure if it helps, I'd rather add it in a comment, but my account is not allowed to add comments yet.
score: 0
answers question: http://stackoverflow.com/q/48127434
type: Answer

event-handling
tag name: event-handling
tags question: http://stackoverflow.com/q/48141393
type: Tag
tags question: http://stackoverflow.com/q/48039660

http://stackoverflow.com/q/48103065
tagged with: tika-server
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83184456
tagged with: apache-tika
possible better answer: http://stackoverflow.com/a/52862362
has answer: http://stackoverflow.com/a/48153647
has answer: http://stackoverflow.com/a/52862362
type: Question
answer count: 2
has title: Python-Tika returning "None" content for PDF's, but works with TIFF's
has comment: http://stackoverflow.com/comment/83184191
downvote count: 0
has body: I have a PDF that i'm trying to get Tika to parse. The PDF is not OCR. Tesseract is installed on my machine. I used ImageMagik to convert the file.tiff to file.pdf, so the tiff file I am parsing is a direct conversion from the PDF. Tika parses the TIFF with no problems, but returns "None" content for the PDF. What gives? I'm using Tika 1.14.1, tesseract 3.03, leptonica-1.70 Here is the code... from tika import parser # This works print(parser.from_file('/from/file.tiff', 'http://localhost:9998/tika')) # This returns "None" for content print(parser.from_file('/from/file.pdf', 'http://localhost:9998/tika'))
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83194388
accepted answer: http://stackoverflow.com/a/48153647
favorite count: 0
upvote count: 2
tagged with: python
tagged with: tesseract

http://stackoverflow.com/a/48051599
has body: In Python, your mentioned data structure is known as dictionary (dict in terms of code) and is syntactically represented as: files = { 'Input.txt': 'Randy', 'Code.py': 'Stan', 'Output.txt': 'Randy' } In order to swap the key and values of your dict, you may use collections.defaultdict as: from collections import defaultdict swapped_dict = defaultdict(list) for key, value in files.items(): swapped_dict[value].append(key) where swapped_dict is a dict object holding the value: { 'Randy': ['Output.txt', 'Input.txt'], 'Stan': ['Code.py'] } Note: Ruby maintains the order, but in Python version &lt; 3.6, the dict objects are unordered in nature. However, from Python version >= 3.6, dict objects are now ordered in nature. For Python versions &lt; 3.6, we have collections.OrderedDict which maintains the order in which keys are inserted. Here's an example to show the swapping of key/value pairs: from collections import OrderedDict # for maintaining the order, your initial list # should also be of the type `OrderedDict` old_dict = OrderedDict([('Input.txt', 'Randy'), ('Code.py', 'Stan'), ('Output.txt', 'Randy')]) for k, v in old_dict.items(): new_dict.setdefault(v, []).append(k) # You may use `setdefault` on normal dictionaries too which will return dict object as: &gt;&gt;&gt; new_dict OrderedDict([('Randy', ['Input.txt', 'Output.txt']), ('Stan', ['Code.py'])]) It is just represented like this, you can access new_dict like a normal dictionary object.
has comment: http://stackoverflow.com/comment/83076978
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83075250
has comment: http://stackoverflow.com/comment/83075178
score: 1
has comment: http://stackoverflow.com/comment/83077318
answers question: http://stackoverflow.com/q/48051564
upvote count: 1
has comment: http://stackoverflow.com/comment/83075367

http://stackoverflow.com/q/48027047
has comment: http://stackoverflow.com/comment/83023962
tagged with: python
has comment: http://stackoverflow.com/comment/83024103
tagged with: wpf
tagged with: visual-studio
has comment: http://stackoverflow.com/comment/83024126
has title: Changing ControlTemplate when button clicked Wpf
tagged with: xaml
type: Question
has body: I have the following simple XAML file: <Window.Resources> <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T1" /> <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T2" /> <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T3" /> <TextBox Margin="10,10,10,5" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" Text="T4" /> </Window.Resources> <ContentControl.Style> </ContentControl.Style> What it does is that it changes the template when the button is pressed. However, I want it to happen once I clicked, without the need of holding it pressed. 1) Is there any trigger from the click style so the moment I clicked it will call the trigger? 2) In the code-behind file, I had like it to run a function the moment I clicked the button and only afterwards to change the template since it is using data from the first template. import wpf from System.Windows import Application, Window from scores import score class MyWindow(Window): def __init__(self): self.ui = wpf.LoadComponent(self, 'WpfApplication1.xaml') def Button_Click1(self, sender, e): x = score(name) if __name__ == '__main__': Application().Run(MyWindow()) So eventually my goal is to click Button, to calculate the function score and only then to change the template. Thank you for the help.
has answer: http://stackoverflow.com/a/48028278
score: 0
has comment: http://stackoverflow.com/comment/83023923
answer count: 1
has comment: http://stackoverflow.com/comment/83026522
type: UnansweredQuestion
tagged with: mvvm

http://stackoverflow.com/a/48130210
has comment: http://stackoverflow.com/comment/83258912
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48125674
has body: Here is my code to solve your problem, made it robust so you can understand better what is going on. Also you can analyze many other files, like .txt for example. Also, in some cases you might find that the CSV file is separated with ';' which is not correct since that is not what a CSV file should be, but however, you can analyze that file too. Just be sure what the separator is between every value and you can change that character in the second line of code below. For example, in the data you gave the separator is ' ' (an space between each value). See the code below so you know what I mean: numFiles = 2 #Number of CSV files in your directory separator = "," #Character that separates each value inside file fExtension = ".csv" #Extension of the file storing the data def MultiplePlots(xValues, allYValues): 'Method to plot multiple times in one figure.' for yValues in allYValues: plt.plot(list(map(int, xValues)), list( map(float, yValues) ), label = "file" + str(i)) plt.legend(loc = 'best') plt.show() return def GetXandYValues(coordinates): 'Method to get all coordinates from all CSV files.' xValues = [] yValues = [] allYValues = [] fst = False for file in coordinates: for coordinate in file: if (fst == False): xValues.append(coordinate[0]) yValues.append(coordinate[1]) fst = True allYValues.append( yValues ) yValues = [] return xValues, allYValues def GetCoordinates( n , separator , fExtension ): 'Iterates through multiple CSV files and storing X values and Y values in different Lists' coordinates = [] #coordinates[0] = x values --- coordinates[1] = y values for i in range(n): coordinates.append( FillList( ReadFile("file" + str(i+1) + fExtension), separator ) ) return coordinates def ReadFile(path): 'Function to read CSV file and store file data rows in list.' try: fileCSV = open(path,"r") #Opens file data = fileCSV.read() #Save file data in string listData = data.splitlines() #Split lines so you have List of all lines in file fileCSV.close() #Close file finally: re…
answers question: http://stackoverflow.com/q/48125674
type: AcceptedAnswer
score: 5
type: Answer
upvote count: 6

http://stackoverflow.com/q/48055704
upvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/48056152
tagged with: conv-neural-network
accepted answer: http://stackoverflow.com/a/48056152
has title: Do Keras Conv2d filters have a depth of three if the input has a depth of three?
type: AnsweredQuestion
downvote count: 0
tagged with: neural-network
tagged with: keras
has body: I've noticed that Conv2d layers are used in code where the input image has three dimensions. However, since we only enter two dimensions for the filter, how does the matrix multiplication take place? Does the two-dimensional filter convolve each input channel separately (or use broadcasting) (and then just add up the results)? Or does the depth of the filter automatically match the depth of the input (3 if color images)? If this is the case, 3x3x3 filter should have 27 weights that can be trained as opposed to 9 in the former case. Tensorflow is more explicit about the filter dimensions for conv2d (you have to input height, width, channels, output_channel) https://www.tensorflow.org/api_docs/python/tf/nn/conv2d
favorite count: 0
type: Question
tagged with: deep-learning
score: 3
tagged with: python

http://stackoverflow.com/q/48147189
type: Question
has comment: http://stackoverflow.com/comment/83272596
linked to: http://stackoverflow.com/q/44755458
has body: I have a (numpy) array of pixels acquired as: ''' import numpy and matplotlib ''' image = Image.open('trollface.png', 'r') width, height = image.size pixel_values = list(image.getdata()) pixel_values = np.array(pixel_values).reshape((width, height, 3)) # 3 channels RGB #height, width = len(pixel_values), len(pixel_values[0]) I need to compute digital negative of this image - for y in range(0,height): for x in range(0,width): R,G,B = pixel_values[x,y] pixel_values[x,y] =(255 - R, 255 - G, 255 - B) tried displaying image from above pixels with the help of this thread plt.imshow(np.array(pixel_values).reshape(width,height,3)) plt.show() But it just displays a blank (white) window, with this error in CLI:
has answer: http://stackoverflow.com/a/48147763
has comment: http://stackoverflow.com/comment/83272963
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83272537
tagged with: python
has comment: http://stackoverflow.com/comment/83272847
has title: Errow displaying image from array of pixels in python
score: 1
tagged with: image-processing
upvote count: 1

http://stackoverflow.com/a/50690729
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48139899
upvote count: 47
has comment: http://stackoverflow.com/comment/93218186
has comment: http://stackoverflow.com/comment/133499513
has comment: http://stackoverflow.com/comment/101532195
has body: An alternative solution would be import matplotlib.pyplot as plt import seaborn as sns def corrdot(*args, **kwargs): corr_r = args[0].corr(args[1], 'pearson') corr_text = f"{corr_r:2.2f}".replace("0.", ".") ax = plt.gca() ax.set_axis_off() marker_size = abs(corr_r) * 10000 ax.scatter([.5], [.5], marker_size, [corr_r], alpha=0.6, cmap="coolwarm", vmin=-1, vmax=1, transform=ax.transAxes) font_size = abs(corr_r) * 40 + 5 ax.annotate(corr_text, [.5, .5,], xycoords="axes fraction", ha='center', va='center', fontsize=font_size) sns.set(style='white', font_scale=1.6) iris = sns.load_dataset('iris') g = sns.PairGrid(iris, aspect=1.4, diag_sharey=False) g.map_lower(sns.regplot, lowess=True, ci=False, line_kws={'color': 'black'}) g.map_diag(sns.distplot, kde_kws={'color': 'black'}) g.map_upper(corrdot) Now, if you really want to imitate the look of that R plot, you can combine the above with some of the solutions you provided: import matplotlib.pyplot as plt from scipy import stats import seaborn as sns import numpy as np def corrdot(*args, **kwargs): corr_r = args[0].corr(args[1], 'pearson') corr_text = round(corr_r, 2) ax = plt.gca() font_size = abs(corr_r) * 80 + 5 ax.annotate(corr_text, [.5, .5,], xycoords="axes fraction", ha='center', va='center', fontsize=font_size) def corrfunc(x, y, **kws): r, p = stats.pearsonr(x, y) p_stars = '' if p &lt;= 0.05: p_stars = '*' if p &lt;= 0.01: p_stars = '**' if p &lt;= 0.001: p_stars = '***' ax = plt.gca() ax.annotate(p_stars, xy=(0.65, 0.6), xycoords=ax.transAxes, color='red', fontsize=70) sns.set(style='white', font_scale=1.6) iris = sns.load_dataset('iris') g = sns.PairGrid(iris, aspect=1.5, diag_sharey=False, despine=False) g.map_lower(sns.regplot, lowess=True, ci=False, line_kws={'color': 'red', 'lw': 1}, scatter_kws={'color': 'black', 's': 20}) g.map_diag(sns.distplot, color='black', kde_kws={'color': 'red', 'cut': 0.7, 'lw': 1}, hist_kws={'histtype': 'bar', 'lw': 2, 'edgecolor': 'k', 'facecolor':'grey'}) g.map_diag(sns.rugplot…
has comment: http://stackoverflow.com/comment/93212040
score: 47
has comment: http://stackoverflow.com/comment/111899476

automated-tests
tags question: http://stackoverflow.com/q/48037121
tag name: automated-tests
tags question: http://stackoverflow.com/q/48061607
tags question: http://stackoverflow.com/q/48137504
type: Tag

http://stackoverflow.com/q/48149922
has body: I am creating a Sudoku game, and i have generated a series of buttons creating a 9x9 grid. Every time a button is clicked, i would like it to cycle through a list of numbers 1-9 (so if i want the button to read 6, the button needs to be clicked 6 times). I have managed to achieve this, however when i bring it onto my main code which includes the grid, it doesnt work. #Create a 9x9 (rows x columns) grid of buttons inside the frame for row_index in range(9): for col_index in range(9): if (row_index in {0, 1, 2, 6, 7, 8} and col_index in {3, 4, 5}) or \ (row_index in {3, 4, 5} and col_index in {0, 1, 2, 6, 7, 8}): #Colours a group of 3x3 buttons together to differentiate the board better. colour = 'gray85' else: colour = 'snow' x = random.randint(1,9) btn = Button(frame, width = 12, height = 6, bg=colour) #create a button inside frame btn.grid(row=row_index, column=col_index, sticky=N+S+E+W) def LeftClick(event, btn): global position btn.config(text=list1[position]) position=position+1 if position == len(list1): position=0 btn.bind("&lt;Button-1&gt;", LeftClick) Any idea why this isn't working? Currently nothing happens when i click the button.
has comment: http://stackoverflow.com/comment/83287679
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48149989
has comment: http://stackoverflow.com/comment/83278801
type: Question
has comment: http://stackoverflow.com/comment/83278646
score: -1
has comment: http://stackoverflow.com/comment/83298274
has title: cycling through a list when an event occurs and displaying it on the screen
accepted answer: http://stackoverflow.com/a/48149989
answer count: 1
tagged with: button
has comment: http://stackoverflow.com/comment/83279049
has comment: http://stackoverflow.com/comment/83278520
favorite count: 0
has comment: http://stackoverflow.com/comment/83278765
tagged with: events
tagged with: python
tagged with: sudoku
has comment: http://stackoverflow.com/comment/83283073
type: AnsweredQuestion
tagged with: tkinter

http://stackoverflow.com/comment/83152537
comment on: http://stackoverflow.com/a/48088539
score: 0
type: AnswerComment
type: Comment
has text: What do you mean if groups have different frequencies? You mean you want not only the most frequent ones? You mean you it for each name?

http://stackoverflow.com/comment/83142190
type: Comment
score: 1
has text: Thanks brothers, I used pycharm, it gives the field but don't give the parenthesis with it that is why I got stuck.
comment on: http://stackoverflow.com/q/48083587
type: QuestionComment

http://stackoverflow.com/a/48104261
type: Answer
has body: So, in file2.py there are two variables defined, right? sam and dan. You can see that taking advantage than in Python, everything is an object: import file2 print("This is what I found in file2:\n%s" % vars(file2)) You'll see a looot of stuff, but among other things, you will see your sam and dan variables. There is no myvar name, right? In your question file1.py's myvar will contain the name of the variable that you want to access... And here's where getattr comes in: Given an instance, how can you get one of its fields if you know its name (if you have the name stored in a string). Like this: getattr(file2, myvar) So your loopbov function, where you pass the name of the list to iterate in the myvar argument would become: def loopbov(myvar): lst=[] for each in getattr(file2, myvar): # myvar will be the string `"sam"` te = fet(each): lst.append(te) return lst As @MadPhysicist mentioned in his comment, it's probably worth mentioning what getattr will do when it's trying to get an attribute by name that is not defined: You will get an AttributeError exception. Try it. Put somewhere in your file1.py this code: getattr(file2, "foobar") However! If you see the docs for getattr you will see that accepts an optional argument: default. That can be read like "ok, if I don't find the attribute, I won't give you an error, but that default argument". Probably it's also worth it reading a bit, if you're interested in the subject, about how import works and the namespaces it creates (see this and this)
answers question: http://stackoverflow.com/q/48104094
score: 2
has comment: http://stackoverflow.com/comment/83184173
has comment: http://stackoverflow.com/comment/83184161
has comment: http://stackoverflow.com/comment/83185033
has comment: http://stackoverflow.com/comment/83184185
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48104094
upvote count: 2

http://stackoverflow.com/q/48160554
has answer: http://stackoverflow.com/a/48160711
has title: Using Python Requests to simulate clicking a 'show more' button
tagged with: python
tagged with: python-requests
score: 1
tagged with: web-scraping
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/61678194
has comment: http://stackoverflow.com/comment/83303257
has answer: http://stackoverflow.com/a/48161413
answer count: 3
has body: I am not sure what code to use for clicking the show more button. I want to get a list of university who are doing certain topic. below is one of the websites http://www.sciencedirect.com/science/article/ your helps will be true appreciated Thanks
favorite count: 0
has comment: http://stackoverflow.com/comment/83300671
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/104025918
comment on: http://stackoverflow.com/q/48158628
score: 0
type: Comment
type: QuestionComment
has text: I experience the same error. Have you already found a solution to it?

twilio
tag name: twilio
type: Tag
tags question: http://stackoverflow.com/q/48054365

http://stackoverflow.com/q/48015707
score: 0
has title: Pybabel misses tagged messages in html files
answer count: 1
tagged with: flask
type: UnansweredQuestion
tagged with: python
tagged with: python-babel
has body: I am working through Miguel Grinberg's new Flask tutorial and have made it to i18n/l10n. Half this chapter had been a headache. First, pybabel extract -F babel.cfg -k _l -o messages.pot doesn't run. All I get is: pybabel: error: no input files or directories specified Whatever, quick Google search says: pybabel extract -F babel.cfg -k _l -o messages.pot --input-dir=. will work. It does. I see all the files it's supposed to be extracting from in the readout. ... extracting messages from app/routes.py extracting messages from app/templates/404.html (extensions="jinja2.ext.autoescape,jinja2.ext.with_") ... Alight, on to generating the language catalog. pybabel init -i messages.pot -d app/translations -l es runs without error and looks good when I open the file. I start copy/pasting translations when I notice my messages.po file is 100 lines shorter than Miguel's. I looked closer at my version of the file and found that while pybabel may have looked into all of my files, it didn't extract anything from some. I can only speculate that adding --input-dir=. may have changed things but I couldn't get pybabel to run without it and Googling pybabel extract babel.cfg messages.pot "no input files" returns 3 results all mentioning making that change. For anyone familiar with the Mega Tutorial, pybabel isn't extracting anything from my base.html, _post.html, or user.html files.
type: Question
has answer: http://stackoverflow.com/a/48156003

http://stackoverflow.com/q/48126766
upvote count: 1
has comment: http://stackoverflow.com/comment/83230657
type: Question
has answer: http://stackoverflow.com/a/48127139
has title: Pandas groupby selecting only one value based on 2 groups and converting rest to 0
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48127139
has answer: http://stackoverflow.com/a/48126824
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48131541
tagged with: python
has body: I have a pandas data frame which has a datetime index which looks like this: df = Fruit Quantity 01/02/10 Apple 4 01/02/10 Apple 6 01/02/10 Pear 7 01/02/10 Grape 8 01/02/10 Grape 5 02/02/10 Apple 2 02/02/10 Fruit 6 02/02/10 Pear 8 02/02/10 Pear 5 Now for each date and for each fruit I only want one value (preferably the top one) and the rest of the fruit for the date to remain zero. So desired output is as follows: Fruit Quantity 01/02/10 Apple 4 01/02/10 Apple 0 01/02/10 Pear 7 01/02/10 Grape 8 01/02/10 Grape 0 02/02/10 Apple 2 02/02/10 Fruit 6 02/02/10 Pear 8 02/02/10 Pear 0 This is only a small example, but my main data frame has over 3 million rows and the fruit are not necessarily in order per date. Thanks
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48126824

http://stackoverflow.com/a/48070586
upvote count: 1
answers question: http://stackoverflow.com/q/48055551
score: 1
has comment: http://stackoverflow.com/comment/83116725
downvote count: 0
has body: def crawl_web(seed) tocrawl = [seed] crawled = [] while tocrawl: page = tocrawl.pop() if page not in crawled: union(tocrawl, get_all_links(get_page(page))) crawled.append(page) return crawled
type: Answer

http://stackoverflow.com/q/48034487
tagged with: python
has title: Equivalent of numpy 'ufunc.at' method in Tensorflow
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: tensorflow
linked to: http://stackoverflow.com/q/40389822
type: Question
score: 1
linked to: http://stackoverflow.com/q/32283082
tagged with: numpy
downvote count: 0
has body: Note that this is essentially the same question as here but unfortunately the solution does not work in general even though it was accepted as the answer. Even more importantly, one of the main use cases for the ufunc.at methods, when there are multiple identical indices, is where it fails. For now we will take np.add as the ufunc to demonstrate in the rest of our code. Consider the objects row_idx: A 1D numpy array of integers with shape=(N,) col_idx: A 1D numpy array of integers with shape=(N,) values : A 1D numpy array of floats with shape=(N,) M : A 2D numpy array of floats with shape=(k,k) Importantly the row and column combinations are not unique i.e. the following does NOT hold (row_idx[i], col_idx[i]) == (row_idx[j], col_idx[j]) =&gt; i==j (1) That means, to achieve the update of the following function def update_loop(row_idx, col_idx, M): for i in range(row_idx.size): M[row_idx[i], col_idx[i]] += values[i] The following way will not work (maybe unexpectedly for some) when (1) doesn't hold. def update_index(row_idx, col_idx, M): M[row_idx, col_idx] += values But fortunately we can use def update_ufunc(row_idx, col_idx, M): np.add.at(M, (row_idx, col_idx), values) When dealing with the same issue in Tensorflow, the answer in the linked question suggested using sparse matrices as essentially the values (row_idx, col_idx, values) represent a sparse matrix. In particular if we have the following objects row_idx_tf: A 2D tensorflow tensor of integers with shape=(N,1) col_idx_tf: A 2D tensorflow tensor of integers with shape=(N,1) values_tf : A 2D tensorflow tensor of floats with shape=(N,1) M_tf : A 2D tensorflow tensor of floats with shape=(k,k) The suggested code is essentially in our case idx = tf.concat((row_idx, col_idx), 1) sparse_tensor = tf.SparseTensor(idx, values, [k,k]) tf.sparse_add(M_tf, sparse_tensor) However, if we want this to behave like the np.add.at method, this hinges on the fact that when creating the sparse tensor, if we come across an index…
has comment: http://stackoverflow.com/comment/83046395
linked to: http://stackoverflow.com/q/39964555
favorite count: 0

http://stackoverflow.com/comment/83297648
has text: How could `int1(b)[2]` work since you only `return` a single value? If you returned multiple results, then you're indexing a particular result. If you return a single string, well you're picking a character in that string, and so on...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48158746

memoization
type: Tag
tag name: memoization
tags question: http://stackoverflow.com/q/48066441

gps
tags question: http://stackoverflow.com/q/48153580
tag name: gps
tags question: http://stackoverflow.com/q/48100919
type: Tag

http://stackoverflow.com/comment/120241528
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50862053
has text: Although many of the scrapy users get problems with `USER_AGENT`, but the actual answer of OP is the answer by @Andy.

http://stackoverflow.com/a/48151467
has body: The Javascript spread operator treats an array of values and a array containing another array of values exactly the same: [].concat(...[1, 2]) Array [ 1, 2 ] [].concat(...[[1, 2]]) Array [ 1, 2 ] It essentially flattens multiple arrays: [].concat(...[[1, 2], [3, 4]]) Array [ 1, 2, 3, 4 ] but only by one layer: [].concat(...[[[1, 2]]]) [[ 1, 2 ]] Python is much more exact. There is no implicit flattening, you have to do it explicitly: def arrSum(*args): if len(args) == 1 and isinstance(args[0], list): args = args[0] return sum(args) If you wanted to replicate the support for multiple lists (so arrSum([1, 2], [3, 4]), I'd just reuse the Flatten (an irregular) list of lists top answer: import collections def flatten(l): for el in l: if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)): yield from flatten(el) else: yield el def arrSum(*args): return sum(flatten(args))
has comment: http://stackoverflow.com/comment/83281429
downvote count: 0
has comment: http://stackoverflow.com/comment/83281396
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48151185

http://stackoverflow.com/q/48053981
has title: What is the most efficient way to dedupe a Pandas dataframe that has typos?
tagged with: python
tagged with: nlp
upvote count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48054091
has answer: http://stackoverflow.com/a/62012027
tagged with: python-dedupe
type: Question
has body: I have a dataframe of names and addresses that I need to dedupe. The catch is that some of these fields might have typos, even though they are still duplicates. For example, suppose I had this dataframe: index name zipcode ------- ---------- --------- 0 john doe 12345 1 jane smith 54321 2 john dooe 12345 3 jane smtih 54321 The typos could occur in either name or zipcode, but let's just worry about the name one for this question. Obviously 0 and 2 are duplicates as are 1 and 3. But what is the computationally most efficient way to figure this out? I have been using the Levenshtein distance to calculate the distance between two strings from the fuzzywuzzy package, which works great when the dataframe is small and I can iterate through it via: from fuzzywuzzy import fuzz for index, row in df.iterrows(): for index2, row2 in df.iterrows(): ratio = fuzz.partial_ratio(row['name'], row2['name']) if ratio &gt; 90: # A good threshold for single character typos on names # Do something to declare a match and throw out the duplicate Obviously this is not a approach that will scale well and unfortunately I need to dedupe a dataframe that is about 7M rows long. And obviously this gets worse if I also need to dedupe potential typos in the zipcode too. Yes, I could do this with .itertuples(), which would give me a factor of ~100 speed improvement, but am I missing something more obvious than this clunky O(n^2) solution? Are there more efficient ways I could go about deduping this noisy data? I have looked into the dedupe package, but that requires labeled data for supervised learning and I don't have any nor am I under the impression that this package will handle unsupervised learning. I could roll my own unsupervised text clustering algorithm, but I would rather not have to go that far if there is an existing, better approach.
score: 3
has answer: http://stackoverflow.com/a/62863515
has comment: http://stackoverflow.com/comment/83114355
answer count: 3
downvote count: 0
favorite count: 0
tagged with: pandas

http://stackoverflow.com/comment/107321280
comment on: http://stackoverflow.com/a/48032535
has text: How I would use it? What I have: ``` from apscheduler.schedulers.blocking import BlockingScheduler def some_job(): print("Decorated job") scheduler = BlockingScheduler() scheduler.add_job(some_job, 'interval', minutes=1) scheduler.start() ``` So, after scheduler has started, I want to know if its up. (My actual guess is that I will need to start scheduler in a separate thread to no-blocking my script and add after this something like: `scheduler.STATE_STOPPED`)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83297599
score: 0
comment on: http://stackoverflow.com/q/48157639
has text: if you have a problem with he excel installation with `xlwings`, it might be possible to use another library to access your files. I was just testing https://openpyxl.readthedocs.io/en/latest/index.html# to read very large files and worked fine for my purposes, but ended using ´readxl` in R thanks to this QA https://stackoverflow.com/questions/6099243/read-an-excel-file-directly-from-a-r-script
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83000747
comment on: http://stackoverflow.com/q/48015668
score: 0
type: Comment
type: QuestionComment
has text: That's the result of unsuccessfully installation of MySQL-python. Once you can install it, the later error message will disappear.

http://stackoverflow.com/q/48084555
linked to: http://stackoverflow.com/q/16639125
favorite count: 0
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/83144408
has answer: http://stackoverflow.com/a/48084582
tagged with: tkinter
has title: How do i change the background color of a frame in tkinter?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83144617
tagged with: python
type: Question
upvote count: 2
answer count: 1
has body: I am trying to change the background of the window of my gui. Can someone explain why this don't work. I am using python version 3.6.3 from tkinter import * class Window(Frame): #Initialize the Window def __init__(self, master=None, bg = "#a6a6a6"): # Parameters that you want to send through the window Frame.__init__(self, master) self.master = master self.bg = bg root = Tk() root.geometry("400x300") app = Window(root) root.mainloop()

http://stackoverflow.com/q/48068573
tagged with: sqlalchemy
score: 0
has body: Note: This is a simplified example of what I'm actually trying to do here. I have the following Parent-Child relationship both driven off a declarative_base. class Parent(declartive_base): __tablename__ = 'parents' id = Column(Integer, primary_key=True) _children = relationship("Child", lazy='dynamic') def total_for_date(self, date): return sum([child.num for child in self._children.filter(Child.date == date)]) @classmethod def total_for_date_query(cls, date): #TODO Return a query that represents this... pass class Child(declarative_base): __tablename__ = 'children' id = Column(Integer, primary_key=True) num = Column(Integer) date = Column(Date) parent_id = Column(Integer, ForeignKey('parents.id')) _parent = relationship("Parent") I'd like to calculate a total of a certain number associated with a child given a parent query. This can be performed via python as such q = session.query(Parent).filter(Parent.id_([4,5,10,...])) total = sum([parent.total_for_date(datetime.date(2018, 1, 2)) for parent in q.all()]) However, the computation here is done in python and given a large amount of data, won't perform as well compared to SQL. I'm trying to figure out a way using hybrid expressions, selects, sqlalchemy queries etc. to have an equivalent method on the parent that returns a query/selectable/expression that will allow me to perform the computation on the SQL side, but maintain a similar interface compared to the other method. In this example, I'd would like to do the following instead. q = session.query(Parent).filter(Parent.id.in_([4,5,10])) total = q.select_entity_from(Parent.total_for_date_query(datetime.date(2018, 1, 2))).scalar() #Note idk if "select_entity_from" is what I want here But I don't know how to fill out the SQL-side method equivalent total_for_date_query. I just can't seem to wrap my head around when to use a Query vs. Selectable, hybrid property expressions vs. hybrid method expressions etc.
tagged with: python
has title: SQLAlchemy Replicate Client Side Method on SQL-Side
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/83120956
has comment: http://stackoverflow.com/comment/83134542

http://stackoverflow.com/comment/98701191
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48105955
has text: Now I have geopandas==0.4.0 and geopandas-osm==0.0.1 and pandas==0.24.1, and it works! Thanks!
score: 0

http://stackoverflow.com/comment/94816388
type: Comment
type: QuestionComment
has text: technically, no, but practically, yes. The org had dedicated AD accounts for RO access that did not require DUO 2FA via API calls.
comment on: http://stackoverflow.com/q/48119389
score: 0

http://stackoverflow.com/comment/83220875
comment on: http://stackoverflow.com/a/48121981
score: 0
type: AnswerComment
has text: thanks for the explanation! I understand what I did wrong
type: Comment

http://stackoverflow.com/q/48101474
has comment: http://stackoverflow.com/comment/83190347
has body: I am detecting the trees and drawing a polygon on the buildings detected using opencv Python. When I try to run the code I am getting the following error. AttributeError: 'module' object has no attribute 'cv' Here is my code, import cv2 as cv import numpy as np import utils # thresh = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 2) # WINDOW_NAME = "win" def detect(segmented, original, xdim, ydim): # morphological opening and closing kernel = np.ones((3,3), np.uint8) img = cv.morphologyEx(segmented, cv.MORPH_OPEN, kernel) img = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel) utils.show_image(img, 'open-close') imgcopy = img.copy() gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY) num_buildings = 0 for i in xrange(255): # threshold the grayscale image at that value binary = np.zeros((xdim, ydim), np.uint8) ret, binary = cv.threshold(gray, dst=binary, thresh=i, maxval=255, type=cv.THRESH_OTSU) #binary[gray == i] = 255 # utils.show_image(binary, 'binary') # find contours, fit to polygon, and determine if rectangular _, contours, hierarchy = cv.findContours(binary, mode=cv.RETR_LIST, method=cv.CHAIN_APPROX_SIMPLE) for c in contours: poly = cv.approxPolyDP(np.array(c), 0.07*cv.ar cLength(c,True), True) carea = cv.contourArea(c) polyarea = cv.contourArea(poly) hull = cv.convexHull(c) hullarea = cv.contourArea(hull) # bounding box rect = cv.minAreaRect(c) box = cv.cv.BoxPoints(rect) box = np.int0(box) if polyarea &gt; 30 and carea &gt; 30: cv.drawContours(img, [c], 0, (0,0,255), 1) if len(poly) &lt; 6 and carea &gt; 100: #and carea &gt; 5: #\ #and abs(polyarea/carea - 1) &lt; 0.25: num_buildings += 1 cv.drawContours(imgcopy, [poly], 0, (0,0,255), 1) cv.drawContours(original, [poly], 0, (0,0,255), 1) # show images utils.show_image(img, 'all bounding boxes') utils.show_image(imgcopy, 'with some filtering') utils.show_image(original, 'onto original') print num_buildings return original I am trying to draw the polygons detected on the image, When i…
upvote count: 0
has comment: http://stackoverflow.com/comment/83179784
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/46462198
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83190699
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/48148652
downvote count: 3
type: Question
tagged with: opencv
tagged with: image
has title: AttributeError: 'module' object has no attribute 'cv' Error in opencv python

http://stackoverflow.com/comment/83234179
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48128670
has text: You say you've been stuck on this for hours. So *edit* the question to show us what you tried and explain why its results are unsatisfactory

http://stackoverflow.com/a/48166803
has comment: http://stackoverflow.com/comment/124470774
has body: from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By import traceback driver = webdriver.Firefox() driver.get('https://www.google.com') def error_catching(): traceback.print_stack() print '--------------' traceback.print_exc() return False #try to grab &lt;div id="gbw"&gt; def presence_of_element(driver, timeout=5): try: w = WebDriverWait(driver, timeout) w.until(EC.presence_of_element_located((By.ID,'gbw'))) return True except: error_catching()
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48165357
type: Answer
accepted answer of: http://stackoverflow.com/q/48165357

http://stackoverflow.com/a/48031009
has body: This is due to the generator being passed to sorted() in the for loop for the second case. The sorted() function makes a copy of the sequence first and this copy will be slower for generator to list than for list to list because a list needs to be made from the generator first. See this question. So if you replace by the generator by a list it becomes much faster. In [11]: %%timeit students = [['Zack',38],['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] s = sorted(set([x[1] for x in students])) for name in sorted([x[0] for x in students if x[1] == s[1]]): name ....: The slowest run took 5.71 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 4.72 µs per loop In [6]: %%timeit students = [['Zack',38],['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] second_highest = sorted(list(set([x[1] for x in students])))[1] ([a for a,b in sorted(students) if b == second_highest]) ...: The slowest run took 11.50 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 5.31 µs per loop
answers question: http://stackoverflow.com/q/48030603
score: 0
type: Answer

http://stackoverflow.com/q/48080581
has answer: http://stackoverflow.com/a/48081975
answer count: 1
has title: How to include external python file i SQL request
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: mysql
type: Question
has body: I'm not experienced in Python. I have the following Python code: How can i import various values from files outside the file, and use them in a SQL request? #!/usr/bin/env python import MySQLdb import Stamdata from Stamdata import Varmekurve K = Varmekurve print K #this vorks, and the value 1.5 from Varmekurve is printed. #Open database connection db = MySQLdb.connect("localhost","root","Codename","MyDvoDb") #prepare a cursor object using cursor method cursor = db.cursor() #Get SetTemp FROM SQL sql = ("SELECT SetTemp FROM varmekurver WHERE kurvenummer = '1.5' AND TempSensor ='15'") #Here i would like to import the value from Varmekurve instead of '1.5', and the data from a DS18b20 temp. sensor instead of '15'. #The DS18B20 sensor are located in '/sys/bus/w1/devices/28-0316007914ff/w1_slave' cursor.execute(sql) results = cursor.fetchall() for row in results: print row[0] db.close() Only the Stamdata file are in the same library. The Script shall control a motorvalve by calling the SetTemp and open/close a mix-valve if the temp. is to high or low (within 2-3 degrees) But i haven't come that far yet :0)
score: -1

http://stackoverflow.com/comment/83081991
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48054604
has text: Thank you, I'll try that. so just clarifying, my problem is within the code itself not the application

http://stackoverflow.com/comment/83101062
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48062047
type: Comment
has text: Try with the updated answer and let me know the status.

http://stackoverflow.com/q/48024578
tagged with: python
has title: face recognition using tracking.js
tagged with: opencv
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48024730
upvote count: 1
type: Question
tagged with: javascript
answer count: 1
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48024730
favorite count: 0
has body: On the client side(HTML) using webcam i need to detect the face and process the face image in the middleware(python) once the processing is done the relavant name of the face has to be tagged to the face detected in the webcam. Using tracking.js i am able to detect the face but unable to do the face recognition in the server side(python) How each detected frame can be sent to the server from tracking.js? How can the response (person name) from the middleware be tagged to the face detected in webcam? i tried using webhooks but am unable to send the detected frame to the server. using javascript, i tried with the below code script. window.onload = function() { var video = document.getElementById('video'); var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var c=document.getElementById("image_canvas"); var ctx=c.getContext("2d"); var tracker = new tracking.ObjectTracker('face'); tracker.setInitialScale(4); tracker.setStepSize(2); tracker.setEdgesDensity(0.1); tracking.track('#video', tracker, { camera: true }); tracker.on('track', function(event) { context.clearRect(0, 0, canvas.width, canvas.height); event.data.forEach(function(rect) { context.strokeStyle = '#FFFAF0'; console.log(rect); context.strokeRect(rect.x, rect.y, rect.width, rect.height); context.font = '11px Helvetica'; context.fillStyle = "#fff"; context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11); context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22); ctx.clearRect(0, 0, 180, 180); ctx.drawImage(video, rect.x+50, rect.y-20, rect.width+160, rect.height+180, 0, 0, 180, 180); var http = new XMLHttpRequest(); var url = "/createreg"; var params = 'imageData:'+ctx; http.open("POST", url, true); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.onreadystatechange = function() {//Call a function when the state changes. if(http.readyState == 4 &amp;&amp; http.status == 200) { alert(http.responseText);…

http://stackoverflow.com/comment/83288289
comment on: http://stackoverflow.com/a/48082152
has text: @user7692855 I think it would be more inefficient in memory usage to iterate over all the old dict, especially if not all the keys will be accessed. But that might not matter if the dictionaries are not huge, and a simple clear process may be preferable for readability. Just to clarify - are you mapping from 20 different old dicts to one new dict, or vice versa?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83058310
type: AnswerComment
comment on: http://stackoverflow.com/a/48043157
type: Comment
has text: @y33t made an iterative version at the bottom.
score: 0

http://stackoverflow.com/a/48163178
downvote count: 0
answers question: http://stackoverflow.com/q/48163135
type: Answer
score: 6
upvote count: 6
has body: When you override the save method, you still have to make sure that the it actually saves the instance. You can do that by simply calling the parent class' save via super: class Message(models.Model): # ... def save(self, *args, **kwargs): # this will take care of the saving super(Message, self).save(*args, **kwargs) # do email stuff # better handle ecxeptions well or the saving might be rolled back You can also connect the mail sending to the post_save (or pre_save, depending on your logic) signal. Whether you want to separate one orm the other in that way depends on how closely the two actions are linked and a bit on your taste. Overriding save gives you the option to intervene in the saving process, e.g. you can change the value of fields based on whether the mail sending was successful or not save the instance at all.
accepted answer of: http://stackoverflow.com/q/48163135
type: AcceptedAnswer

http://stackoverflow.com/q/48053086
type: AnsweredQuestion
has body: I'm attempting to write a program that lets the user input a list of numbers and tell them maximum and minimum numbers. The program should let the user choose the allowable minimum and maximum values, and should not let the user input something to the list that is outside of these bounds. I've managed to get the first bit done but I have no idea how to filter data outside of a range. Help would be greatly appreciated. print ("Input done when finished") print ("Input thresholds") maximumnum = int(input("Input maximum number: ")) minimumnum = int(input("Input minimum number: ")) minimum = None maximum = None while True: inp =input("Enter a number: ") if inp == "done": break try: num = float(inp) except: print ("Invalid input") continue if minimum is None or num &lt; minimum: minimum = num if maximum is None or num &gt; maximum: maximum = num print ("Maximum:", maximum) print ("Minimum:", minimum)
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/48053109
score: 0
tagged with: python
tagged with: user-input
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83078383
has comment: http://stackoverflow.com/comment/83078397
accepted answer: http://stackoverflow.com/a/48053109
has title: Filtering Data outside of a range using python shell

http://stackoverflow.com/a/48089631
accepted answer of: http://stackoverflow.com/q/48089571
has comment: http://stackoverflow.com/comment/83154007
score: 0
has comment: http://stackoverflow.com/comment/83153947
upvote count: 1
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/83153883
has comment: http://stackoverflow.com/comment/83153851
has comment: http://stackoverflow.com/comment/83153699
type: Answer
has comment: http://stackoverflow.com/comment/83154042
has comment: http://stackoverflow.com/comment/83153804
has comment: http://stackoverflow.com/comment/83153758
has comment: http://stackoverflow.com/comment/83153986
answers question: http://stackoverflow.com/q/48089571
has body: class RegisterView(SignupView): form_class = RegisterForm template_name = 'oauth/auth_form.html' def form_valid(self, form): return redirect('profiles:Index', slug=form.cleaned_data['username'])
has comment: http://stackoverflow.com/comment/83153928

http://stackoverflow.com/a/48081452
downvote count: 0
has comment: http://stackoverflow.com/comment/83137435
type: Answer
answers question: http://stackoverflow.com/q/48081124
has comment: http://stackoverflow.com/comment/83137475
accepted answer of: http://stackoverflow.com/q/48081124
upvote count: 1
has comment: http://stackoverflow.com/comment/83137487
score: 1
has body: I think you mistested somehow. Here's my results: import timeit timeit.timeit('eval(s)', number=1000, setup="import random;" " s = '[' + ','.join(str(random.random())" " for _ in range(4096)) + ']'") results in 4.92162881999684 This means that using a simple eval of the string takes ~5ms. With JSON it gets a little faster: timeit.timeit('json.loads(s)', number=1000, setup="import random, json;" " s = '[' + ','.join(str(random.random())" " for _ in range(4096)) + ']'") results in 1.1105524039994634 i. e. ~1.1ms
has comment: http://stackoverflow.com/comment/83137708
type: AcceptedAnswer

http://stackoverflow.com/q/48065753
tagged with: pandas
has comment: http://stackoverflow.com/comment/83115950
has body: I have two columns, one is a string field customer containing customer names and the other is a numeric field sales representing sales. What I want to do is to group data by customer and then sort sales within group. In SQL or Pandas, this is normally achieved by something like order by customer, sales on the table. But I am just curious about this implementation. Instead first sorting on customer and then sorting on sales, why not first group customer and sort sales. I don't really care about the order of the different customers since I only care about records of same customers being grouped together. Grouping is essentially mapping and should run faster than sorting. Why isn't there such implementation in SQL? Am I missing something? Example data name,sales john,1 Amy,1 john,2 Amy,3 Amy,4 and I want it to group by name and then sort by sales: name,sales john,1 john,2 Amy,1 Amy,3 Amy,4 In SQL you probably would do select * from table order by name,sales This would definitely do the job. But my confusion is since I don't care about the order of name, I should be able to do some kind of grouping (which should be cheaper than sorting) first and do sorting only on the numeric field. Am I able to do this? Why do a lot of examples from google simply uses sorting on the two fields? Thanks!
tagged with: sql
answer count: 1
has comment: http://stackoverflow.com/comment/83140507
has comment: http://stackoverflow.com/comment/83106048
has title: Sort by two columns, why not do grouping first?
has comment: http://stackoverflow.com/comment/83105541
linked to: http://stackoverflow.com/q/27983
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83133157
has comment: http://stackoverflow.com/comment/83108195
has comment: http://stackoverflow.com/comment/83112917
tagged with: python
has comment: http://stackoverflow.com/comment/83140214
has comment: http://stackoverflow.com/comment/83105429
has comment: http://stackoverflow.com/comment/83140678
has comment: http://stackoverflow.com/comment/83115724
has comment: http://stackoverflow.com/comment/83112869
type: Question
has comment: http://stackoverflow.com/comment/83105595
has comment: http://stackoverflow.com/comment/83105654
tagged with: group-by
tagged with: sorting
has comment: http://stackoverflow.com/comment/83141228
has answer: http://stackoverflow.com/a/48071714
score: 0

http://stackoverflow.com/q/48050906
has comment: http://stackoverflow.com/comment/83073526
tagged with: pandas
type: AnsweredQuestion
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/83074156
score: 0
has body: I have a df as follow: SN Asset Dept Location FREQ SUN 1 A11 Mech ACTB M NaN 2 A12 Mech CTBA M NaN 3 A13 Mech CABA Y NaN 4 A14 Elec ACTB Y NaN 5 A15 Elec CTBA M NaN 6 A16 Elec CABA Y NaN 7 A17 Mech CABA Y NaN 8 A18 Mech CTBA M NaN 9 A19 Mech ACTB Y NaN 10 A20 Elec CTBA M NaN I need to apply a filter, having two conditions. 1) IF Dept=='Mech' 2) IF Location contain string 'CTB' Then copy cells from FREQ to SUN. The output should look like: SN Asset Dept Location FREQ SUN 1 A11 Mech ACTB M M 2 A12 Mech CTBA M M 3 A13 Mech CABA Y NaN 4 A14 Elec ACTB Y NaN 5 A15 Elec CTBA M NaN 6 A16 Elec CABA Y NaN 7 A17 Mech CABA Y NaN 8 A18 Mech CTBA M M 9 A19 Mech ACTB Y Y 10 A20 Elec CTBA M NaN
answer count: 1
has title: Multiple filter operations on the same dataframe [Pandas]
has answer: http://stackoverflow.com/a/48051034
accepted answer: http://stackoverflow.com/a/48051034

http://stackoverflow.com/comment/83025691
comment on: http://stackoverflow.com/q/48027855
type: Comment
has text: This is actually stupidly simple. Do you mind showing me what you've done?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83049783
type: QuestionComment
has text: It would be better to get an empty list than `None`, that way the result is always a list.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48039657

http://stackoverflow.com/comment/83052787
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48041008
has text: One last thing to know sir: should I always use this way `driver.execute_script("arguments[0].style.display='none';", header)` whenever it is necessary to set a `header` as landmark, i meant this `"arguments[0].style.display='none';"` portion?
type: AnswerComment

http://stackoverflow.com/a/48087738
accepted answer of: http://stackoverflow.com/q/48087691
answers question: http://stackoverflow.com/q/48087691
type: Answer
has comment: http://stackoverflow.com/comment/83244343
has body: If you deployed the app gcloud app update If it's testing in Cloud Shell I missed where you stated the app was deployed and wrote the answer below. I'll leave it for future readers or in case it might help. To stop the local server from the command line, you press the following: Mac OS X or Linux: Control-C Windows: Control-Break Then restart again with dev_appserver.py app.yaml This assumes you're completing the App Engine hello world tutorial. Still not working? Maybe you have multiple processes running or something else is wrong. Let's try killing all of the web server processes and restarting. ps aux | grep dev_appserver.py Look at the process number. kill PROCESS_NUM_HERE If you see multiple processes after running ps aux... then you should kill all of them. Then restart dev_appserver.py app.yaml
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/83212985
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48117575
has text: I dont understand 'use button {} to correctly format code '. Do I need to enable the use of a button?

http://stackoverflow.com/comment/83180221
type: QuestionComment
has text: Any reason to not use: `np.where(mymatrix <= 0.5, -1, 1)` ?
score: 3
comment on: http://stackoverflow.com/q/48102450
type: Comment

http://stackoverflow.com/q/48147182
score: 0
accepted answer: http://stackoverflow.com/a/48199515
answer count: 1
tagged with: python
has title: Python Multi-process share an imported Class
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83272833
tagged with: process
tagged with: multiprocessing
type: Question
has body: I got an issue on Python multiprocessing sharing imported Class. The troubled part is like this: file A: class Meta: db_a = None db_b = None ... # class will be initialized at the very beginning of the program and might # be imported by all other models globally for a global variable/instance # access, for example, a global DB access instance is in Meta file B: from file_A import Meta def runner(): initialize_meta_db() # Meta's attributes now have values ... pool = multiprocessing.Pool(4) pool.map(worker, arg_list) pool.close() pool.join() ... def worker(*args): ... print(Meta.db_a) # process will print None ... # a runner function which spawns 4 processes, each process will use class Meta # to do some work. But the program runs with errors that for each process, the Meta class is not initialized and every attribute is None. I know the reason why, that the Meta class is only initialized in the memory of the main process, and each child process will have its own raw class Meta independently. But is there any way that I can share this class with both parent process and child processes? Thanks!
tagged with: python-multiprocessing
has answer: http://stackoverflow.com/a/48199515

http://stackoverflow.com/comment/83127058
score: 0
comment on: http://stackoverflow.com/q/48076329
type: Comment
type: QuestionComment
has text: better show your code which you use to get items.

http://stackoverflow.com/a/48121615
upvote count: 3
has body: Use the is_month_end component of the .dt date accessor: # Ensure the date column is a Timestamp df['Date'] = pd.to_datetime(df['Date']) # Filter to end of the month only df = df[df['Date'].dt.is_month_end] Applying this to the data you provided: Date CumReturn 0 2017-03-31 1.000 5 2017-05-31 1.022 6 2017-06-30 1.033 EDIT To get business month end, compare using BMonthEnd(0): from pandas.tseries.offsets import BMonthEnd # Ensure the date column is a Timestamp df['Date'] = pd.to_datetime(df['Date']) # Filter to end of the month only df = df[df['Date'] == df['Date'] + BMonthEnd(0)] Applying this to the data you provided: Date CumReturn 0 2017-03-31 1.000 3 2017-04-28 1.012 5 2017-05-31 1.022 6 2017-06-30 1.033
has comment: http://stackoverflow.com/comment/83220002
has comment: http://stackoverflow.com/comment/83222857
has comment: http://stackoverflow.com/comment/83219969
has comment: http://stackoverflow.com/comment/83220097
answers question: http://stackoverflow.com/q/48121396
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83220161
score: 3

http://stackoverflow.com/comment/83053709
type: AnswerComment
comment on: http://stackoverflow.com/a/48019175
type: Comment
has text: doesn't it create intermediate list structure?
score: 0

http://stackoverflow.com/comment/88558650
has text: Sorry @Leila, my usage was fairly simple. Never tried something like that!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48029807

http://stackoverflow.com/a/48164312
score: 0
answers question: http://stackoverflow.com/q/48040791
has body: Not sure what fig.canvas.update() would do. If you replace that line by fig.canvas.draw_idle() it should work as expected. In that case you would not need to draw the artists individually.
type: Answer

http://stackoverflow.com/comment/83154376
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48084896
has text: Thanks! Quick follow-up, when I do it this way is there still a way for me to check the status of each checkbox? The ultimate goal here is to not only have these created, but when one is checked to have a total amount increased by 1.
score: 0

http://stackoverflow.com/q/48079216
tagged with: for-loop
has body: I want to print only 10 elements from list in Django template here is my code Positive Tweets : {% for tweet in positiveTweet %} {{ tweet.0 }} {% endfor %} How can I print first 10 elements if positiveTweet list having length of 100 something.
downvote count: 0
possible better answer: http://stackoverflow.com/a/61305573
favorite count: 0
tagged with: python-3.x
has title: add limit for list in for loop django template
tagged with: django
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: django-templates
has answer: http://stackoverflow.com/a/62109420
upvote count: 14
has answer: http://stackoverflow.com/a/48080646
has answer: http://stackoverflow.com/a/61305573
type: Question
score: 14
has answer: http://stackoverflow.com/a/48079259
accepted answer: http://stackoverflow.com/a/48079259

http://stackoverflow.com/q/48090801
accepted answer: http://stackoverflow.com/a/48100195
answer count: 2
tagged with: user-interface
favorite count: 0
has body: I am trying to make a GUI program where at the press of a button, the program picks a random word out of 3 files and displays the selected word in a Label. What is the simplest way that I could go about doing this? Thanks!
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has answer: http://stackoverflow.com/a/48100195
downvote count: 3
has title: Python: Program that picks a random word from multiple text files
upvote count: 1
has comment: http://stackoverflow.com/comment/83173114
has comment: http://stackoverflow.com/comment/83173081
has comment: http://stackoverflow.com/comment/83156200
type: Question
has comment: http://stackoverflow.com/comment/83156465
score: -2
possible better answer: http://stackoverflow.com/a/48094152
has answer: http://stackoverflow.com/a/48094152

http://stackoverflow.com/q/48124183
downvote count: 0
tagged with: string
has title: Slicing a string based on common delimeter in Python
tagged with: python
has body: I'd like to take the following string and slice it based on the pipe delimeter: address = '1234 Broadway Ave | Los Angeles | CA | 94530' I figured out the first piece: street = address[:address.index('|')] print(street) 1234 Broadway Ave But I am unclear on how to get city/state/zip: city = state = zip = Also, is there a better way to do this? Using RegEx or something similar? Haven't used that before.. Thanks!
favorite count: 0
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48124194
has comment: http://stackoverflow.com/comment/83225311
upvote count: 3
tagged with: slice
type: Question
accepted answer: http://stackoverflow.com/a/48124194
answer count: 1

http://stackoverflow.com/q/48043661
downvote count: 0
type: Question
answer count: 2
tagged with: scikit-learn
upvote count: 2
has answer: http://stackoverflow.com/a/48044037
accepted answer: http://stackoverflow.com/a/48060206
favorite count: 0
has answer: http://stackoverflow.com/a/48060206
tagged with: classification
has body: I'm using sklearn's Random Forest classifier for a model I've built. When using it for predictions, I was wondering if there's a way to get the certainty level of the predictions (i.e. the number of trees that predicted that class)?
tagged with: python
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/48044037
has title: sklearn: get score of prediction from random forest?

http://stackoverflow.com/q/48047146
tagged with: special-characters
type: Question
tagged with: ascii
tagged with: python-3.5
answer count: 1
downvote count: 0
has body: I have strings of ASCII characters represented like this: '\\xaa\\xaa\\x02\\xba\\x04A\\xaa\\xaa\\x02\\xbc\\x05&gt;\\xaa\\xaa\\x04\\x80\\x02\\xf8\\x00\\x85\\xaa\\xaa\\x04\\x80\\x02\\xf8' I would like to convert these strings to lists where each element of the list is an ASCII character, and the order and values of the characters are conserved from the original string: ['\xaa', '\xaa', '\x02', '\xba', '\x04', 'A', '\xaa', '\xaa', '\x02', '\xbc', '\x05', '&gt;', '\xaa', '\xaa', '\x04', '\x80', '\x02', '\xf8', '\x00', '\x85', '\xaa', '\xaa', '\x04', '\x80', '\x02', '\xf8'] This wouldn't be too difficult if every character was in the form \xa0 (representing a hex byte), but sometimes ASCII escape characters such as \n newline and \\ backslash are included. This throws off the converter method I wrote. Is there a simple built-in function that can do what I desire? Or is there some package I can download? Or does someone have a simple code solution?
has title: How do I convert a '\x'-escaped string into a list of the corresponding individual characters?
has answer: http://stackoverflow.com/a/48050912
tagged with: python
favorite count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/48050912
type: AnsweredQuestion
tagged with: escaping
score: 1

http://stackoverflow.com/a/48025420
score: 1
has body: You can filter the list from zeroes and add a list with the number of zeroes found to the end of the filtered list: s = [1,2,3,'a', False,0,5,0,3] new_s = [i for i in s if isinstance(i, int) and i or isinstance(i, bool)]+[0]*s.count(0) Output: [1, 2, 3, False, 5, 3, 0, 0, 0]
downvote count: 0
answers question: http://stackoverflow.com/q/48025345
type: Answer
has comment: http://stackoverflow.com/comment/83020303
upvote count: 1

http://stackoverflow.com/comment/83388755
type: AnswerComment
has text: Thanks @Andy ! Do you know if this code would work for the PowerTrack API? Is there any other way to query a larger volume of Tweets (does not need to be streraming) with the free access?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48078277

http://stackoverflow.com/a/48074853
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48074705
upvote count: 2
has body: You have defined img=[] inside except block (locally). That's why it doesn't have access outside the block. Define it outside the block. def get_class(img_path): return int(img_path.split('/')[-2]) imgs=[] labels=[] #Your code
type: Answer

http://stackoverflow.com/comment/83325445
type: AnswerComment
comment on: http://stackoverflow.com/a/48172564
score: 0
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Thanks for the comments!! Editted.

http://stackoverflow.com/a/48031288
type: Answer
score: 2
upvote count: 2
has body: Why don't you try to break it up? Based on the current distance, set your speed. And then based on the current speed, increment or decrement your distance. speed = 1 dis = 0 while True: if dis &gt;= 10: # Set speed if dis &lt;= 0: # Set speed # Based on speed, increment or decrement distance
answers question: http://stackoverflow.com/q/48031245
downvote count: 0
has comment: http://stackoverflow.com/comment/83032797

http://stackoverflow.com/q/48123809
has body: With Python 3.6 and the Turtle module, I would like to know how to print the coordinates of the turtle on screen. My questions are: How do I print text on the screen, and how do I make that text the player's coordinates? Here is my code. from turtle import Turtle, Screen play = Screen() play.bgcolor("black") play.screensize(250, 250) play.title("Turtle Keys") def position(): coord = follow.coor() coord.color("white") coord.setposition(130, 100) run = Turtle("triangle") run.speed("fastest") run.color("white") run.penup() run.setposition(250, 250) print(position) Thank you. Edit I tried write, but it throws a name not defined error.
has comment: http://stackoverflow.com/comment/83239082
has comment: http://stackoverflow.com/comment/83225283
favorite count: 0
tagged with: python-3.x
tagged with: turtle-graphics
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48123963
tagged with: python
has answer: http://stackoverflow.com/a/48124912
has answer: http://stackoverflow.com/a/48124004
has comment: http://stackoverflow.com/comment/83225765
score: -1
downvote count: 1
has title: How to display turtle coordinates on the canvas
type: Question
upvote count: 0
answer count: 3
tagged with: python-turtle

http://stackoverflow.com/comment/83243729
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48133141
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162670/discussion-between-pastudilloe-and-cs).

http://stackoverflow.com/comment/83022837
type: QuestionComment
comment on: http://stackoverflow.com/q/48026490
has text: Fixed it, thanks for the help. 1 question though, the activate function I had was below the one that it was meant to be using, why did it default to that one instead of the one higher up in the code?
score: 0
type: Comment

http://stackoverflow.com/comment/83123766
comment on: http://stackoverflow.com/q/48075002
score: 0
type: Comment
type: QuestionComment
has text: @philantrovert I mostly tried splitting the values, and creating new columns each with Hour and minute, then I had to change the type of these columsn to Integer and finaly I was trying to figure out an udf to multiply and sum the columns. The thing is I have multiple hours columns so this would probably attack any performance (using withColumns for every new column and all).

http://stackoverflow.com/comment/83320889
has text: What is the symptom of the misparsing?
type: Comment
comment on: http://stackoverflow.com/q/48167216
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83250132
type: Comment
type: QuestionComment
has text: No. My case is different from the one you gave. I did test the solutions given in the website.
score: 0
comment on: http://stackoverflow.com/q/48134649

http://stackoverflow.com/a/53466175
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48099928
has body: Do you have "pillow" package installed ? If not may be This because you didn't add a "pillow" package to you system , you can easily add it by write this command in cmd pip install pillow And if use Anaconda Package Manger search for pillow and install it this will solve it

http://stackoverflow.com/a/59934664
answers question: http://stackoverflow.com/q/48152908
downvote count: 0
has body: Short: You can try my solution in django-admin-autocomlete-all or make something similar. Long answer: One pain is: limit_choices_to-.. of source foreign key is not implemented too :( I was able to implement filter into get_search_results() of the target ModelAdmin. But here we have another serious pain. We can check request.is_ajax and '/autocomplete/' in request.path. In addition we only have request.headers['Referer']. With help of this we can limit affected foreign keys to 1 model. But if we have 2+ foreign keys into same target (lets say: two user roles inside the same model instance), we don't know which one of them calls the ajax. My idea was modify the url's. With Request url I was not successfull (after long attempts to find in DOM and in js the select2 elements and extend the url). But I have some success with modifying of the Referer url (ie. source admin page url) using window.history.replaceState(). I can temporary modify the url like /?key=author - which run always if you will use django-admin-autocomplete-all and I am able to add almost everything into Referer url with additional custom javascript. Especially adding of current values of other form fields could be useful to implement dynamic filtering (dependencies of fields). So, it is a hack, sure. But you can give try to django-admin-autocomplete-all. - More in docs of it.
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/a/48127355
type: Answer
has comment: http://stackoverflow.com/comment/83295304
answers question: http://stackoverflow.com/q/48114083
accepted answer of: http://stackoverflow.com/q/48114083
has comment: http://stackoverflow.com/comment/83396658
has body: I think your code is correct, problem on motor's side. While investigating I found two problems: If at the moment you close loop connection is not established, you'll get exception calling callback for &lt;Future error since loop closed before async callbacks done. It seems not to be related to async generators or streams, but to any motor usage. AgnosticChangeStream async iteration mechanism (_next function) is written without thinking of case when it cancelled. Try of setting exception to cancelled future leads to InvalidStateError. This code demonstrates two problems and possible workarounds: import types import asyncio from contextlib import suppress from motor.motor_asyncio import AsyncIOMotorClient async def test(): while True: await asyncio.sleep(0.1) async def cleanup(task): task.cancel() with suppress(asyncio.CancelledError): await task def _next(self, future): try: if not self.delegate: self.delegate = self._collection.delegate.watch(**self._kwargs) change = self.delegate.next() self._framework.call_soon(self.get_io_loop(), future.set_result, change) except StopIteration: future.set_exception(StopAsyncIteration()) except Exception as exc: # CASE 2: # Cancellation of async iteration (and future with it) happens immediately # and trying to set exception to cancelled future leads to InvalidStateError, # we should prevent it: if future.cancelled(): return future.set_exception(exc) async def watch(collection): async with collection.watch([]) as stream: # Patch stream to achieve CASE 2: stream._next = types.MethodType(_next, stream) async for change in stream: print(change) if __name__ == '__main__': loop = asyncio.get_event_loop() tmp = asyncio.ensure_future(test()) # Way to receive KeyboardInterrupt immediately. client = AsyncIOMotorClient() collection = client.test_database.test_collection task = asyncio.ensure_future(watch(collection)) try: loop.run_forever() except KeyboardInterrupt: print('KeyboardInterrupt') finally: loop.run_until_complete(cleanup(tmp)) …
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/comment/83026497
type: AnswerComment
score: 0
type: Comment
has text: For this problem, I went with @ayhan's answer just because I needed the last one. But your earlier answer addressed my next question which was going to be passing this index into another dataframe. You both rock.
comment on: http://stackoverflow.com/a/48028128

http://stackoverflow.com/q/48167807
has answer: http://stackoverflow.com/a/48168535
score: -3
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83315164
downvote count: 3
has comment: http://stackoverflow.com/comment/83315682
has comment: http://stackoverflow.com/comment/83317355
type: Question
has comment: http://stackoverflow.com/comment/83315445
accepted answer: http://stackoverflow.com/a/48168535
has comment: http://stackoverflow.com/comment/83315980
upvote count: 0
has body: The date document is wrote like below 1060301 1030727 1041201 1060606 1060531 1060629 1060623 1060720 ...and some of them like.... 831008 751125 1060110 890731 700815 731022 1010724 980116 Which represent the date data of: Year(2~3 character)/Month(2 characters)/Day(2 characters) And some r blanks for leaking data is there a way to read those data into arranged date type?
has comment: http://stackoverflow.com/comment/83315553
has title: Read date in different lengths and conjoined numbers in python
answer count: 1
favorite count: 0

http://stackoverflow.com/q/48131194
score: 0
duplicate of: http://stackoverflow.com/q/4020539
tagged with: python
has comment: http://stackoverflow.com/comment/83239970
accepted answer: http://stackoverflow.com/a/48131331
type: AnsweredQuestion
has title: Python - If a user enters \n in an input, and the varible is printed, the \n makes a new line
type: Question
has comment: http://stackoverflow.com/comment/83239957
has comment: http://stackoverflow.com/comment/83239717
has comment: http://stackoverflow.com/comment/83239396
has answer: http://stackoverflow.com/a/48131331
linked to: http://stackoverflow.com/q/1885181
answer count: 1
linked to: http://stackoverflow.com/q/4020539
has body: For example, if I did this: test=input("Text: ") print(test) And then set test ashello\nhow are you?, and then call test(), I want it to appear as this: hello how are you? and not hello\nhow are you? Is this possible? -darth
has comment: http://stackoverflow.com/comment/83239343
has comment: http://stackoverflow.com/comment/83239745
has comment: http://stackoverflow.com/comment/83239361

http://stackoverflow.com/comment/83230504
type: QuestionComment
type: Comment
has text: Have you tried anything? It looks like you could use a look-up table, from an integer index to an image string. I don't use Python, but would an array be a good place to start?
comment on: http://stackoverflow.com/q/48126818
score: 0

http://stackoverflow.com/q/48069045
tagged with: node.js
has comment: http://stackoverflow.com/comment/83112318
has comment: http://stackoverflow.com/comment/83112283
has comment: http://stackoverflow.com/comment/83113798
has comment: http://stackoverflow.com/comment/83112237
tagged with: stdout
has answer: http://stackoverflow.com/a/63190173
type: Question
has comment: http://stackoverflow.com/comment/83114410
has body: I have a server.js file that uses child_process to call a python file: const express = require('express') const app = express() path = require('path'); fs = require('fs') app.get('/call_script', function(req, res) { function_choice = req.query.function_choice args_choice = req.query.args_choice // call python scripts var spawn = require("child_process").spawn; var process = spawn("python",["test.py", function_args]); process.stdout.on("data", function (data){ from_python = data.toString("utf8"); from_python = from_python.replace(/\n/g, " ").replace(/\\n/g, " "); res.json({ "answer" : from_python }) }); The python file: function_args = sys.argv[1] # ..... retrieve function and arguments from function_args result = locals()[function_choice](*arr_n) print(result) sys.stdout.flush() If I run node server.js in the terminal it runs the file and works perfectly. I can call the express endpoint using a URL with Ajax. The python file gets called and returns the output correctly. No problems. If I now place server.js into a Docker container the output from python is not returned. There are no errors or crashes, just nothing. The Ajax call just hangs and returns nothing. The Dockerfile and package.json contain all necessary commands and dependencies. I can run the container with everything working EXCEPT the python output. I know there are issues with Docker/node and stdout but I have not been able to get the python output to come outside the container. If I put console.log inside process.stdout.on the terminal and Docker logs show nothing. Is it something to do with buffering or flushing? EDIT It seems it has something to do with modules not being made available. For example, matplotlib is not found, yet it installs during docker build. Here is my Dockerfile: FROM node:9 # Create app directory WORKDIR /usr/src/app # Install app dependencies # A wildcard is used to ensure both package.json AND package-lock.json are copied COPY package*.json ./ RUN npm install RUN apt-get updat…
tagged with: docker
score: 0
has comment: http://stackoverflow.com/comment/83113955
answer count: 1
has title: Cannot capture python stdout inside Docker container using child_process in node
has comment: http://stackoverflow.com/comment/83114155
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83240065
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48131324
type: Comment
has text: Hmmmm. Not 100% sure how I can achieve any of this tho. I'll review the documentation some more! :)

http://stackoverflow.com/comment/83167407
score: 1
has text: You're supposed to be sending a *header*, not a query parameter. Also you now need to revoke that token and get a new one.
comment on: http://stackoverflow.com/q/48096390
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83221964
type: QuestionComment
has text: @taoufikA Could you elaborate more on that.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48122550

http://stackoverflow.com/q/48158167
has title: How do I groupby a dynamic list of column names?
has comment: http://stackoverflow.com/comment/83295794
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48159110
type: Question
has body: I am trying to modify some code to become more flexible. Here is the woking code: df_out = pdf.set_index('TTF_WEEKS').groupby(['PRODUCT','COMMODITY_CODE','FISCAL_WEEK_ENDDATE'], group_keys=False).apply(lambda x: x.reindex(np.arange(pdf.TTF_WEEKS.min(),pdf.TTF_WEEKS.max()+1))) I would like to make it so that the column names are not hard coded. I got the set_index piece solved since it's just a single string, but not sure how to handle the group by. Here is my partial solution: col_cnt = len(list(pdf.columns.values)) df_out = pdf.set_index(pdf.columns[col_cnt-1]).groupby(['PRODUCT','COMMODITY_CODE','FISCAL_WEEK_ENDDATE'], group_keys=False).apply(lambda x: x.reindex(np.arange(pdf.TTF_WEEKS.min(),pdf.TTF_WEEKS.max()+1))) I'm thinking that I would want some sort of join (pseudo code) for i in range(col_cnt-2): join( pdf.columns[i],',') How would I go about this? Edit: OK, so I got closer, but now getting an error: col_grp = "'" + "','".join(map(str, list(pdf.columns.values)[:col_cnt-2])) + "'" df_out = pdf.set_index(pdf.columns[col_cnt-2]).groupby([col_grp], group_keys=False).apply(lambda x: x.reindex(np.arange(pdf.TTF_WEEKS.min(),pdf.TTF_WEEKS.max()+1))) Gives an error: KeyError: "'PRODUCT','COMMODITY_CODE','FISCAL_WEEK_ENDDATE'"
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/a/48017259
downvote count: 0
has body: Likely, your cvs file has empty line(s) or a line that is too short. Skip empty lines: for x in readCSV: if x: update_teams(x[0], x[2]) You can also assert that len(x) &gt;= 3: for x in readCSV: if len(x) &lt; 3: print('Skipping', x) else: update_teams(x[0], x[2])
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/48017105
has comment: http://stackoverflow.com/comment/83003737
accepted answer of: http://stackoverflow.com/q/48017105
score: 2
type: AcceptedAnswer

http://stackoverflow.com/q/48057387
tagged with: python
has comment: http://stackoverflow.com/comment/83086984
score: 3
has title: How to bulk update a single field in elasticsearch using python
downvote count: 0
has answer: http://stackoverflow.com/a/48061783
type: Question
answer count: 2
has body: How to perform a single field bulk update in elastic search. Currently, I am trying with helper function as follows, from elasticsearch import Elasticsearch, helpers for doc in collection_1: try: uid = int(doc["uid"]) k.append({ "_index": "col1", "_type" : "col1", "_id" : uid, "_source": doc }) except Exception as err: print(err) helpers.bulk(es, k) E.S version: 2.4
upvote count: 3
has comment: http://stackoverflow.com/comment/83087407
tagged with: elasticsearch
linked to: http://stackoverflow.com/q/29469218
favorite count: 0
has answer: http://stackoverflow.com/a/65211145
has comment: http://stackoverflow.com/comment/83087037
type: UnansweredQuestion

http://stackoverflow.com/q/48054531
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/54305147
has answer: http://stackoverflow.com/a/54305147
has comment: http://stackoverflow.com/comment/83085441
tagged with: tensorflow
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83121634
upvote count: 15
has answer: http://stackoverflow.com/a/48123076
score: 15
accepted answer: http://stackoverflow.com/a/48123076
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/83121659
has comment: http://stackoverflow.com/comment/83113788
has comment: http://stackoverflow.com/comment/83121706
downvote count: 0
favorite count: 0
has body: I'm trying to learn Machine Learning, but I cannot resolve below error. [My environment] Mac High Sierra 10.13.2 Python3.4.5 Numpy1.13.3 [Command] $ python3 -c "import jupyter, matplotlib, numpy, pandas, scipy, sklearn" [Error] RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb Traceback (most recent call last): File "/Users/uekyo/ml/env/lib/python3.4/site-packages/pandas/__init__.py", line 26, in &lt;module&gt; from pandas._libs import (hashtable as _hashtable, File "/Users/uekyo/ml/env/lib/python3.4/site-packages/pandas/_libs/__init__.py", line 4, in &lt;module&gt; from .tslib import iNaT, NaT, Timestamp, Timedelta, OutOfBoundsDatetime File "pandas/_libs/tslib.pyx", line 1, in init pandas._libs.tslib ImportError: numpy.core.multiarray failed to import During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/Users/uekyo/ml/env/lib/python3.4/site-packages/pandas/__init__.py", line 35, in &lt;module&gt; "the C extensions first.".format(module)) ImportError: C extension: numpy.core.multiarray failed to import not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace --force' to build the C extensions first. [Things I tried] I understood numpy is wrong. So I tried below things, but the error still appears. ~1~ sudo mv /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy_old ~2~ pip3 uninstall numpy pip3 install numpy -I Thanks.
has title: RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb
has answer: http://stackoverflow.com/a/50382190
has comment: http://stackoverflow.com/comment/83115294
has answer: http://stackoverflow.com/a/60824351
tagged with: python
has comment: http://stackoverflow.com/comment/83082274
has comment: http://stackoverflow.com/comment/83120763

http://stackoverflow.com/comment/83065198
has text: It probably has to due with the character widths, Java uses 16 bit characters while python uses 8 bit characters. Encode the string as a unicode or UTF-8 string and it *should* work.
comment on: http://stackoverflow.com/q/48046843
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/48054365
has comment: http://stackoverflow.com/comment/83081312
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48055014
has title: ImportError: no module named urllib3, urllib3 is already installed
tagged with: urllib3
answer count: 1
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/48055014
favorite count: 0
tagged with: twilio
tagged with: python
has comment: http://stackoverflow.com/comment/83081110
type: AnsweredQuestion
has body: Here is my code: from twilio.rest import Client # Your Account SID from twilio.com/console account_sid = "sid" # Your Auth Token from twilio.com/console auth_token = "token" client = Client(account_sid, auth_token) message = client.messages.create( to="number", from_="number", body="new phone who dis") print(message.sid) Here is the error message: Traceback (most recent call last): File "/Users/mahika/Documents/sendtexttest.py", line 1, in &lt;module&gt; from twilio.rest import Client File "build/bdist.macosx-10.6-intel/egg/twilio/rest/__init__.py", line 14, in &lt;module&gt; File "build/bdist.macosx-10.6-intel/egg/twilio/http/http_client.py", line 1, in &lt;module&gt; File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests-2.18.4-py2.7.egg/requests/__init__.py", line 43, in &lt;module&gt; import urllib3 ImportError: No module named urllib3 The problem is that urllib3 is already installed. What should I do?
has comment: http://stackoverflow.com/comment/83081220
has comment: http://stackoverflow.com/comment/83081251

http://stackoverflow.com/a/48104730
has comment: http://stackoverflow.com/comment/83201070
has comment: http://stackoverflow.com/comment/83207946
upvote count: 1
has comment: http://stackoverflow.com/comment/83186557
has comment: http://stackoverflow.com/comment/83185978
has comment: http://stackoverflow.com/comment/83186437
has comment: http://stackoverflow.com/comment/83185946
has comment: http://stackoverflow.com/comment/83185836
has comment: http://stackoverflow.com/comment/83185558
type: AcceptedAnswer
downvote count: 0
has body: I made this an answer show I could show an example. Use the pyuic tool to convert the .ui file to a .py file. The .py file this creates will have a class in it that is the name of the widget built in Qt Designer. Import and subclass this class into the GUI class that you are creating. from designer_file import Ui_Gui # Designer file is the converted .ui file and Ui_Gui is the ui class it created class GUIWindow(QtWidgets.QWidget, Ui_Gui): def __init__(self): QtWidgets.QWidget.__init__(self) self.setupUi(self) # This is necessary to setup the ui when using this method # Code here...
has comment: http://stackoverflow.com/comment/83188793
has comment: http://stackoverflow.com/comment/83186775
has comment: http://stackoverflow.com/comment/83186295
answers question: http://stackoverflow.com/q/48104077
type: Answer
has comment: http://stackoverflow.com/comment/83186179
accepted answer of: http://stackoverflow.com/q/48104077
score: 1

http://stackoverflow.com/q/48123074
tagged with: c++
has title: Fatal error in extension: PyThreadState_Get: no current thread
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48242260
score: 17
has comment: http://stackoverflow.com/comment/83378759
upvote count: 17
has answer: http://stackoverflow.com/a/48474705
type: Question
has comment: http://stackoverflow.com/comment/83424721
linked to: http://stackoverflow.com/q/48289858
tagged with: anaconda
has answer: http://stackoverflow.com/a/48257819
linked to: http://stackoverflow.com/q/15678153
has comment: http://stackoverflow.com/comment/83459053
answer count: 3
has comment: http://stackoverflow.com/comment/83420137
downvote count: 0
accepted answer: http://stackoverflow.com/a/48474705
has comment: http://stackoverflow.com/comment/83294782
tagged with: macos
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/16246352
has body: I've seen several posts that have stated the same error, but looking and trying out the answers in those posts have not helped. I was wondering if someone could look at this and see if something pops out? I'm building a Python extension for a CPP application, and there are no errors during the compilation and build step. However, when I import the module I get the error mentioned in the title. Other stackoverflow answers have claimed that this is because of being linked with one library while compilation and using a different interpreter. As far as I can tell, I'm using the same Python interpreter. I'm going to describe now why I think I'm using the same Python in the linking process and for the interpreter. This is the comand I'm using to build the Python extension $ gcc -shared helicsPYTHON_wrap.c $(python-config3 --includes) -I/path/to/helics-0.9/includes -L/path/to/helics-0.9/lib -lhelicsSharedLib -L$(python3-config --prefix)/lib -lpython3.6m -o _helics.so $ which python3-config /Users/$USER/miniconda3/bin/python3-config $ python3-config --prefix /Users/$USER/miniconda3 If I try to import the python file that imports the shared library, it throws the fatal error. If I use otool -L on the shared library, I get the following. This is what I expect to get. $ otool -L _helics.so _helics.so: @rpath/libhelicsSharedLib.dylib (compatibility version 0.0.0, current version 0.0.0) @rpath/libpython3.6m.dylib (compatibility version 3.6.0, current version 3.6.0) /usr/local/opt/zeromq/lib/libzmq.5.dylib (compatibility version 7.0.0, current version 7.3.0) libboost_program_options.dylib (compatibility version 0.0.0, current version 0.0.0) libboost_filesystem.dylib (compatibility version 0.0.0, current version 0.0.0) libboost_system.dylib (compatibility version 0.0.0, current version 0.0.0) libboost_date_time.dylib (compatibility version 0.0.0, current version 0.0.0) /usr/local/opt/gcc/lib/gcc/7/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.24.0) /usr/lib/lib…
has comment: http://stackoverflow.com/comment/83269274
has comment: http://stackoverflow.com/comment/83295193
tagged with: python
possible better answer: http://stackoverflow.com/a/48242260
has comment: http://stackoverflow.com/comment/83269194

http://stackoverflow.com/a/65957580
score: 1
upvote count: 1
has body: You can get the details of only failing tests and save the logs into a file with command below. Logs also contain the trace of each test. py.test -rf tests/ | tee logs.txt
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48054392

http://stackoverflow.com/comment/83295722
comment on: http://stackoverflow.com/q/48158110
type: Comment
type: QuestionComment
has text: "my laptop" *checks profile pic* hmmmm -_-
score: 1

http://stackoverflow.com/a/48087555
accepted answer of: http://stackoverflow.com/q/48087336
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48087336
has body: To establish the values in the query we can use prepare(), where we establish placeholders for the data, these placeholders we fill in through bindValue(): def getWordsAndInsert(word, searchShortDefn, mnemonics, defArr, defDict): word = str(word) searchShortDefn = str(searchShortDefn) mnemonics = str(mnemonics) defArr = str(defArr) defDict = str(defDict) query = QSqlQuery() query.prepare("""INSERT INTO dictin (word, searchShortDefn, mnemonics, defArr, defDict) VALUES (:word, :searchShortDefn, :mnemonics, :defArr, :defDict)""") query.bindValue(":word", word) query.bindValue(":searchShortDefn", searchShortDefn) query.bindValue(":mnemonics", mnemonics) query.bindValue(":defArr", defArr) query.bindValue(":defDict", defDict) if query.exec_(): print("Successful") else: print("Error: ", query.lastError().text())
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83327882
type: AnswerComment
type: Comment
score: 0
has text: Can you provide the response.text, response.headers, and response.cookies returns from the login? It's possible that the server is returning a value that you need to include in the header of subsequent requests, perhaps a session ID
comment on: http://stackoverflow.com/a/48171911

http://stackoverflow.com/q/48094733
has answer: http://stackoverflow.com/a/48099990
score: -1
has comment: http://stackoverflow.com/comment/83164405
has comment: http://stackoverflow.com/comment/83165749
has title: Django2, the forms in template do not work
has comment: http://stackoverflow.com/comment/83164699
has comment: http://stackoverflow.com/comment/83165550
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83164558
accepted answer: http://stackoverflow.com/a/48099990
has comment: http://stackoverflow.com/comment/83164860
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: (only in Django 2 &amp; 2.0.1) if I use {{form}} it works but if I use {{form.field}} it disappears all &lt;form method="POST" class="post-form" method="post"&gt; {% csrf_token %} {{ form }} &lt;input type="submit" id="salva" class="btn btn-primary" /&gt; &lt;/form&gt; forms.py class PreventivoForm(forms.ModelForm): class Meta: model = Preventivo fields = ['cliente','prestazione1', 'ripetizione1', 'prestazione2', 'ripetizione2', 'prestazione3', 'ripetizione3', 'prestazione4', 'ripetizione4', 'prestazione5', 'ripetizione5']
tagged with: django-templates
has comment: http://stackoverflow.com/comment/83164832
downvote count: 2
upvote count: 1
type: Question

http://stackoverflow.com/comment/83263168
type: QuestionComment
has text: Use dict.get(key, default_value)
comment on: http://stackoverflow.com/q/48142516
score: 1
type: Comment

http://stackoverflow.com/comment/83051256
score: 0
has text: @dkato Ok the shape of X and y are (18,) and (18, 1), respectively. Also, I updated it in the bottom of my original post.
comment on: http://stackoverflow.com/q/48040346
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48084459
upvote count: 1
answers question: http://stackoverflow.com/q/48084139
has body: Brief You don't even need regex for this. Python has isupper() and islower() functions available. Code See code in use here passwords = [ "all lowercase letters", "ALL UPPERCASE LETTERS", "Mixed lowercase and UPPERCASE letters" ] def lower_score(string, weight): if any(s.islower() for s in string): print "Contains: LOWERCASE" return weight else: print "Message: The password needs lowercase letters for a higher score" return 0 def upper_score(string, weight): if any(s.isupper() for s in string): print "Contains: UPPERCASE" return weight else: print "Message: The password needs capital letters for a higher score" return 0 for password in passwords: print "Password: " + password score = 0 score += lower_score(password, 5) score += upper_score(password, 5) print "Score: " + str(score) + "\n"
downvote count: 0
type: Answer
score: 1

apache-spark
tags question: http://stackoverflow.com/q/48172675
tags question: http://stackoverflow.com/q/48058008
tags question: http://stackoverflow.com/q/48121354
tags question: http://stackoverflow.com/q/48164206
tags question: http://stackoverflow.com/q/48131718
tags question: http://stackoverflow.com/q/48169520
tags question: http://stackoverflow.com/q/48148840
tags question: http://stackoverflow.com/q/48104138
tags question: http://stackoverflow.com/q/48158760
tags question: http://stackoverflow.com/q/48062671
tags question: http://stackoverflow.com/q/48124389
tags question: http://stackoverflow.com/q/48162739
tags question: http://stackoverflow.com/q/48106284
tag name: apache-spark
tags question: http://stackoverflow.com/q/48139940
tags question: http://stackoverflow.com/q/48075002
tags question: http://stackoverflow.com/q/48112315
tags question: http://stackoverflow.com/q/48142859
tags question: http://stackoverflow.com/q/48148256
tags question: http://stackoverflow.com/q/48165234
tags question: http://stackoverflow.com/q/48083401
tags question: http://stackoverflow.com/q/48024983
tags question: http://stackoverflow.com/q/48148881
type: Tag
tags question: http://stackoverflow.com/q/48140510
tags question: http://stackoverflow.com/q/48075018
tags question: http://stackoverflow.com/q/48094534
tags question: http://stackoverflow.com/q/48093364

http://stackoverflow.com/q/48134966
accepted answer: http://stackoverflow.com/a/48135519
type: Question
has body: Nothing is happened when I put comment button.I wanna make a page which is shown comment&recomment.I wrote codes in views.py class DetailView(generic.DetailView): model = POST template_name = 'detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comment_form'] = CommentCreateForm() context['recomment_form'] = ReCommentCreateForm() return context class CommentCreateView(generic.View): def post(self, request, *args, **kwargs): form = CommentCreateForm(request.POST) post = POST.objects.get(pk=kwargs['post_pk']) if form.is_valid(): obj = form.save(commit=False) obj.target = post obj.save() return redirect('detail', pk=post.pk) class ReCommentCreateView(generic.View): def post(self, request, *args, **kwargs): form = ReCommentCreateForm(request.POST) comment = Comment.objects.get(pk=kwargs['comment_pk']) if form.is_valid(): obj = form.save(commit=False) obj.target = comment obj.save() return redirect('detail', pk=comment.target.pk) in urls.py from django.urls import path from django.conf import settings from . import views urlpatterns = [ path('detail/<int:pk>/', views.DetailView.as_view(), name='detail'), path('comment/<int:post_pk>/',views.CommentCreateView.as_view(), name='comment'), path('recomment/<int:comment_pk>/', views.ReCommentCreateView.as_view(), name='recomment'), ] in detail.html {% load static %} DETAIL {% for comment in post.comment.all %} {% by_the_time comment.created_at %} {{ comment.name }} {{ comment.created_at }} Recomment {% for recomment in comment.recomment.all %} {{ recomment.name }} {{ recomment.created_at }} {% endfor %} {{recomment_form}} {% csrf_token %} {% endfor %} {{comment_form}} {% csrf_token %} in models.py class Comment(models.Model): name = models.CharField(max_length=100, blank=True) text = models.TextField() target = models.ForeignKey(POST, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=…
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/48135519
tagged with: django
tagged with: python
has title: Nothing is happened when I put comment button
type: AnsweredQuestion

http://stackoverflow.com/a/48053998
has comment: http://stackoverflow.com/comment/83080469
score: 3
answers question: http://stackoverflow.com/q/48053960
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48053960
has comment: http://stackoverflow.com/comment/83080433
has comment: http://stackoverflow.com/comment/83080451
has comment: http://stackoverflow.com/comment/83080369
has body: final = range(31) ar = [] for i in range(0, len(final), 3): ar.append(tuple(final[i:i+3])) print(ar) Output: [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 14), (15, 16, 17), (18, 19, 20), (21, 22, 23), (24, 25, 26), (27, 28, 29),(30,)] Your list length is divisible by 3 - you last element would be the last triplet , not a tuple with only one element... Mine is not divisible by 3 without rest, so I have an incomplete tuple at the end. Using the list comprehension tuple(final[i:i+3]) will ensure you do not overstep the boundaries of final and the remaining 1 or 2 numbers are in the last tuple.
upvote count: 3
type: Answer

http://stackoverflow.com/comment/83026731
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48028356
score: 0
has text: You just show the code where you compile the expression. Where is the code where you actually *use* it?

http://stackoverflow.com/q/48126253
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48126265
accepted answer: http://stackoverflow.com/a/48126265
has title: How to check if a python varaible is of type pandas.core.series.Series
possible better answer: http://stackoverflow.com/a/48126264
has body: In Python 3.x, how can I check if my variable is of type pandas.core.series.Series?
favorite count: 0
score: 16
tagged with: python
upvote count: 17
duplicate of: http://stackoverflow.com/q/152580
has answer: http://stackoverflow.com/a/48126264
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83229143
linked to: http://stackoverflow.com/q/35490420
downvote count: 1

http://stackoverflow.com/comment/83134361
score: 0
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162431/discussion-between-dale-and-ar-kang).
type: AnswerComment
comment on: http://stackoverflow.com/a/48078183
type: Comment

http://stackoverflow.com/q/48046647
type: Question
tagged with: indexing
has body: I am using the google finance api to pull data into a pandas dataframe. The index is a number and I would like to change it to be a date inclusive of hours and minutes. Any ideas? Thanks! import pandas as pd api_call = 'http://finance.google.com/finance/getprices?q=SPY&amp;i=300&amp;p=1d&amp;f=d,o,h,l,c,' df = pd.read_csv(api_call, skiprows=8, header=None) df.columns = ['Record', 'Open', 'High', 'Low', 'Close'] df['Record'] = df.index Record Open High Low Close 0 0 268.19 268.48 268.18 268.46 1 1 268.14 268.23 267.98 268.19 2 2 268.11 268.19 268.06 268.13 3 3 268.05 268.16 267.96 268.11 4 4 267.93 268.1 267.9 268.06 5 5 267.98 268.01 267.89 267.92 6 6 267.95 267.99 267.86 267.97 7 7 267.88 267.95 267.85 267.94 8 8 267.78 267.9 267.78 267.88 9 9 267.94 267.96 267.68 267.78 10 10 267.91 267.95 267.87 267.94
tagged with: google-finance-api
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83064781
has answer: http://stackoverflow.com/a/48046744
has title: Adding a time index to a pandas dataframe from google finance
tagged with: datetime
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48046744

http://stackoverflow.com/a/52627264
has comment: http://stackoverflow.com/comment/135517251
has comment: http://stackoverflow.com/comment/115185291
downvote count: 0
score: 66
has comment: http://stackoverflow.com/comment/106515665
type: Answer
upvote count: 66
has body: My solution for adding basic formatting for JSONField in Django Admin (Django>=3.1): import json import logging from django.db.models import JSONField from django.contrib import admin from django.forms import widgets logger = logging.getLogger(__name__) class PrettyJSONWidget(widgets.Textarea): def format_value(self, value): try: value = json.dumps(json.loads(value), indent=2, sort_keys=True) # these lines will try to adjust size of TextArea to fit to content row_lengths = [len(r) for r in value.split('\n')] self.attrs['rows'] = min(max(len(row_lengths) + 2, 10), 30) self.attrs['cols'] = min(max(max(row_lengths) + 2, 40), 120) return value except Exception as e: logger.warning("Error while formatting JSON: {}".format(e)) return super(PrettyJSONWidget, self).format_value(value) class JsonAdmin(admin.ModelAdmin): formfield_overrides = { JSONField: {'widget': PrettyJSONWidget} } Usage: admin.site.register(models.MyModel, JsonAdmin) For Django < 3.1 you have to import JSONField in this way: from django.contrib.postgres.fields import JSONField Hope it will help you!
answers question: http://stackoverflow.com/q/48145992

odoo-9
tags question: http://stackoverflow.com/q/48090111
tag name: odoo-9
type: Tag
tags question: http://stackoverflow.com/q/48090513
tags question: http://stackoverflow.com/q/48062624

http://stackoverflow.com/comment/83564630
type: Comment
has text: @JamesKent I do not see any reason. Could you elaborate?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48143566

http://stackoverflow.com/comment/83206969
comment on: http://stackoverflow.com/a/48115426
has text: @schmoozed what is the part you're not sure about ? "moving the code to a custom management command" or "that you execute as part of your deployment process" ?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48028111
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48027853
downvote count: 0
has body: If you have a pandas dataframe you could set the display options. import pandas as pd import numpy as np pd.options.display.float_format = '{:.2f}'.format pd.DataFrame(dict(randomvalues=np.random.random_sample((5,)))) Returns: randomvalues 0 0.02 1 0.66 2 0.24 3 0.87 4 0.63
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48027853

http://stackoverflow.com/comment/83236974
has text: you must provide templates for each of the objects. In one of the original sift papers there is a description on how to use keypoint matching for object detection. But if there isnt enough texture (transparent bottle without label?) keypoint matching will probably not work.
score: 0
comment on: http://stackoverflow.com/q/48129595
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83207216
has text: OK, now understand. Give me some time.
type: Comment
comment on: http://stackoverflow.com/a/48115355
score: 1
type: AnswerComment

http://stackoverflow.com/a/48048358
has body: If your requirements are only to remove first space and then making first letter capital You can try something like this: your_data=' on the insert tab, the galleries include items that are designed to coordinate with the overall look of your document. you can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks. when you create pictures, charts, or diagrams, they also coordinate with your current document look. ' conversion=list(your_data) if conversion[0]==' ': del conversion[0] capitalize="".join(conversion).split() for j,i in enumerate(capitalize): try: if j==0: capitalize[j]=capitalize[j].capitalize() if '.' in i: capitalize[j + 1] = capitalize[j + 1].capitalize() except IndexError: pass print(" ".join(capitalize)) output: On the insert tab, the galleries include items that are designed to coordinate with the overall look of your document. You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks. When you create pictures, charts, or diagrams, they also coordinate with your current document look.
accepted answer of: http://stackoverflow.com/q/48039486
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48039486
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/83019650
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48025092
has text: https://stackoverflow.com/questions/19907442/python-explain-dict-attribute

http://stackoverflow.com/q/48095037
tagged with: python
has comment: http://stackoverflow.com/comment/83166622
has comment: http://stackoverflow.com/comment/83186391
tagged with: pygame
accepted answer: http://stackoverflow.com/a/48096231
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83166677
has title: Why wont Pygame detect where I'm clicking
score: 0
has answer: http://stackoverflow.com/a/48096231
answer count: 1
has body: This is a game I'm making but I'm having some trouble with it (this is just one function which is part of a larger part of my program, I know I haven't called it in the code below). def qfq(): pygame.event.get() pygame.mixer.music.pause() gameDisplay.fill(white) gameDisplay.blit(plainbg_img, [0, 0]) if year == 7: ans = randint(8, 15) y = randint(0, 8) x1 = ans - y x2 = randint(0, 8) x3 = randint(0, 8) x4 = randint(0, 8) eqt = ("x + "+ str(y)+ " = "+ str(ans)) x1 = ("x = " + str(x1)) x2 = ("x = " + str(x2)) x3 = ("x = " + str(x3)) x4 = ("x = " + str(x4)) mouse_pos = pygame.mouse.get_pos() mathquestion(eqt,black,(screen_width169/2 -250),(screen_height169/2 -400)) py1 = screen_height169/2 py2 = screen_height169/2 +100 py3 = screen_height169/2 +200 py4 = screen_height169/2 +300 yArray = [py1,py2,py3,py4] yValue1 = random.choice(yArray) mathanswer((x1),black,(screen_width169/2 -100),(yValue1)) yCheck1 = yValue1 yArray.remove(yValue1) yValue2 = random.choice(yArray) mathanswer((x2),black,(screen_width169/2 -100),(yValue2)) yCheck2= yValue2 yArray.remove(yValue2) yValue3 = random.choice(yArray) mathanswer((x3),black,(screen_width169/2 -100),(yValue3)) yCheck3 = yValue3 yArray.remove(yValue3) yValue4 = random.choice(yArray) mathanswer((x4),black,(screen_width169/2 -100),(yValue4)) yCheck4 = yValue4 yArray.remove(yValue4) answer = None qfqLoop = True while qfqLoop == True: pygame.event.get() #Checking if answers are correct if mouse_pos[0] &gt;= 855 and mouse_pos[0] &lt;= 1065: #correct answer if mouse_pos[1] &gt;=yCheck1 and mouse_pos[1] &lt;=yCheck1+65: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: answer = True if mouse_pos[0] &gt;= 855 and mouse_pos[0] &lt;= 1065: #wrong answer if mouse_pos[1] &gt;=yCheck2 and mouse_pos[1] &lt;=yCheck2+65: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: answer = False if mouse_pos[0] &gt;= 855 and mouse_pos[0] &lt;= 1065: #wrong answer if mouse_pos[1] &gt;=yCheck3 and mouse_pos[1] &lt…
favorite count: 0

http://stackoverflow.com/q/48171256
has comment: http://stackoverflow.com/comment/83323122
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83322137
tagged with: dataframe
has title: Pandas: replace Nan with values from one of two columns
has comment: http://stackoverflow.com/comment/83321957
type: Question
has comment: http://stackoverflow.com/comment/83322520
has comment: http://stackoverflow.com/comment/83322876
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/83322921
has comment: http://stackoverflow.com/comment/83322322
has comment: http://stackoverflow.com/comment/83322059
has comment: http://stackoverflow.com/comment/83322997
answer count: 1
has comment: http://stackoverflow.com/comment/83323025
tagged with: nan
favorite count: 0
has comment: http://stackoverflow.com/comment/83322389
has body: Given the following dataframe df, where df['B']=df['M1']+df['M2']: A M1 M2 B 1 1 2 3 1 2 NaN NaN 1 3 6 9 1 4 8 12 1 NaN 10 NaN 1 6 12 18 I want the NaN in column B to equal the corresponding value in M1 or M2 provided that the latter is not NaN: A M1 M2 B 1 1 2 3 1 2 NaN 2 1 3 6 9 1 4 8 12 1 NaN 10 10 1 6 12 18 This answer suggested to use: df.loc[df['B'].isnull(),'B'] = df['M1'], but the structure of this line allows to consider either M1 or M2, and not both at the same time. Ideas on how I should change it to consider both columns? EDIT Not a duplicate question! For ease of understanding, I claimed that df['B']=df['M1']+df['M2'], but in my real case, df['B'] is not a sum and comes from a rather complicated computation. So I cannot apply a simple formula to df['B']: all I can do is change the NaN values to match the corresponding value in either M1 or M2.
has answer: http://stackoverflow.com/a/48171849
accepted answer: http://stackoverflow.com/a/48171849
tagged with: python
linked to: http://stackoverflow.com/q/11106823
has comment: http://stackoverflow.com/comment/83322200
has comment: http://stackoverflow.com/comment/83321999
downvote count: 0
has comment: http://stackoverflow.com/comment/83322839
score: 1
has comment: http://stackoverflow.com/comment/83322122
linked to: http://stackoverflow.com/q/29177498

http://stackoverflow.com/q/48054120
has answer: http://stackoverflow.com/a/48054221
has comment: http://stackoverflow.com/comment/83080564
has body: This is the push and pop functions written by Codility (source: https://codility.com/media/train/5-Stacks.pdf) stack = [0] * N size = 0 def push(x): global size stack[size] = x size = size + 1 def pop(): global size size = size - 1 return stack[size] I see that the only thing that the function pop() does is to decrement the value of size by 1, and return stack[size]. How does it actually remove the last element from the stack? I don't really see it...
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48054221
has title: Push and pop in stack
tagged with: python
has comment: http://stackoverflow.com/comment/83080553
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48054168
has answer: http://stackoverflow.com/a/48054168

http://stackoverflow.com/q/48074396
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/43362986
score: 0
has answer: http://stackoverflow.com/a/48074524
answer count: 1
duplicate of: http://stackoverflow.com/q/43362986
has title: Run the example of help(np.frombuffer) and got the error like this: AttributeError: 'str' object has no attribute '__buffer__'`,why?
has body: Here is an example of help(np.frombuffer): s = 'hello world' np.frombuffer(s, dtype='S1', count=5, offset=6) help(np.frombuffer)'s output like this: array(['w', 'o', 'r', 'l', 'd'],dtype='|S1') However, I got the error like this: s = 'hello world' np.frombuffer(s, dtype='S1', count=5, offset=6) Traceback (most recent call last): File "&lt;ipython-input-151-624044df0072&gt;", line 1, in &lt;module&gt; np.frombuffer(s, dtype='S1', count=5, offset=6) AttributeError: 'str' object has no attribute '__buffer__'` Could you tell me why the example of help(np.frombuffer) not run ok? Run on Spyder(Python3.6)'s IPython console.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83123121

http://stackoverflow.com/q/48135256
tagged with: bash
answer count: 3
has answer: http://stackoverflow.com/a/48137917
linked to: http://stackoverflow.com/q/10002021
possible better answer: http://stackoverflow.com/a/48136646
linked to: http://stackoverflow.com/q/21867847
has comment: http://stackoverflow.com/comment/83247878
favorite count: 0
tagged with: command
has comment: http://stackoverflow.com/comment/83250063
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/48136527
type: AnsweredQuestion
tagged with: command-line
score: 2
has comment: http://stackoverflow.com/comment/83248170
upvote count: 3
has title: Split csv file vertically using command line
has body: Is it possible to split a csv file, vertically, into multiple files? I know we can split single large files into smaller files with no of rows mentioned using the command line. I have csv files in which columns are repeating after certain column no and I want to split that file column-wise.Is that possible with the command line, If not then how can we do it with python? For Eg. consider above sample in which site and address present multiple times vertically, I want to create 3 different csv files containing single site and single address Any help would be highly appreciated, Thanks
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83266011
accepted answer: http://stackoverflow.com/a/48136527
has answer: http://stackoverflow.com/a/48136646
has comment: http://stackoverflow.com/comment/83248451
has comment: http://stackoverflow.com/comment/83271419

django-generic-views
type: Tag
tag name: django-generic-views
tags question: http://stackoverflow.com/q/48100366

http://stackoverflow.com/comment/83234598
score: 0
type: Comment
type: QuestionComment
has text: have you imported the `subprocess` module?
comment on: http://stackoverflow.com/q/48128203

http://stackoverflow.com/a/68691143
type: Answer
has body: First check your data cuz you may get an error if you have ',' instead of '.' if so, you need to transform every ',' into '.' with a function : def replacee(s): i=str(s).find(',') if(i&gt;0): return s[:i] + '.' + s[i+1:] else : return s then you need to apply this function on every row in your column : dfOPA['Montant']=dfOPA['Montant'].apply(replacee) then the convert function will work fine : dfOPA['Montant'] = pd.to_numeric(dfOPA['Montant'],errors = 'coerce')
answers question: http://stackoverflow.com/q/48094854
score: 0

http://stackoverflow.com/q/48151686
has title: Python: Imported matplotlib but cannot use imshow
has comment: http://stackoverflow.com/comment/134266423
linked to: http://stackoverflow.com/q/4783810
upvote count: 3
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48151947
linked to: http://stackoverflow.com/q/76105218
downvote count: 1
accepted answer: http://stackoverflow.com/a/48151947
duplicate of: http://stackoverflow.com/q/56656777
duplicate of: http://stackoverflow.com/q/76105218
has body: I'm working in Ubuntu as Virtual-Box guest on top of Windows machine (as host), and I am attempting to run my python script from the terminal. I had difficulty installing matplotlib using pip install. I managed to install it using sudo apt-get install python-matplotlib However, I am unable to bring up an image I have created in my code: import numpy as np import matplotlib.pyplot as plt import random as random from random import randrange image = plt.imshow(mymatrix) plt.show() If I import matplotlib as: import matplotlib as plt I am recieving the following error on attempting to run the script: AttributeError: 'module' object has no attribute 'imshow' If I import matplotlib as: import matplotlib.pyplot as plt I recieve the following error: raise ImportError, str(msg) + ', please install the python-tk package' ImportError: No module named _tkinter, please install the python-tk package On attempting to install python-tk using 'pip install python-tk' this is what I'm getting: ~/ising $ pip install python-tk Collecting python-tk Could not find a version that satisfies the requirement python-tk (from versions: ) No matching distribution found for python-tk I'm unsure if I have in fact incorrectly installed matplotlib from the beginning. I am aware pyplot is not automatically imported with matplotlib, could the same be true for installing it from the console? Seems like I have tried everything at this stage.
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/83281866
tagged with: python-2.7
score: 2
type: AnsweredQuestion
favorite count: 0
possible better answer: http://stackoverflow.com/a/48152384
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48152384
has comment: http://stackoverflow.com/comment/83281789
tagged with: python

http://stackoverflow.com/a/48117558
score: 0
has comment: http://stackoverflow.com/comment/83211767
has comment: http://stackoverflow.com/comment/83211557
has comment: http://stackoverflow.com/comment/83211629
type: Answer
has comment: http://stackoverflow.com/comment/83211587
answers question: http://stackoverflow.com/q/48117224
has comment: http://stackoverflow.com/comment/83211507
has comment: http://stackoverflow.com/comment/83211713
has comment: http://stackoverflow.com/comment/83211736
has body: look at grid_rowconfigure and grid_columnconfigure here. I seem to recall having a similar problem a while ago. You need to give each column/row a weight.
has comment: http://stackoverflow.com/comment/83211836

http://stackoverflow.com/a/48035642
upvote count: 18
type: Answer
has body: Let's break down your problem. You want to Filter rows based on some boolean condition You want to select a subset of columns from the result. For the first point, the condition you'd need is - df["col_z"] < m For the second requirement, you'd want to specify the list of columns that you need - ["col_x", "col_y"] How would you combine these two to produce an expected output with pandas? The most straightforward way is using loc - df.loc[df["col_z"] < m, ["col_x", "col_y"]] The first argument selects rows, and the second argument selects columns. More About loc Think of this in terms of the relational algebra operations - selection and projection. If you're from the SQL world, this would be a relatable equivalent. The above operation, in SQL syntax, would look like this - SELECT col_x, col_y # projection on columns FROM df WHERE col_z < m # selection on rows pandas loc allows you to specify index labels for selecting rows. For example, if you have a dataframe - col_x col_y a 1 4 b 2 5 c 3 6 To select index a, and c, and col_x you'd use - df.loc[['a', 'c'], ['col_x']] col_x a 1 c 3 Alternatively, for selecting by a boolean condition (using a series/array of bool values, as your original question asks), where all values in col_x are odd - df.loc[(df.col_x % 2).ne(0), ['col_y']] col_y a 4 c 6 For details, df.col_x % 2 computes the modulus of each value with respect to 2. The ne(0) will then compare the value to 0, and return True if it isn't (all odd numbers are selected like this). Here's what that expression results in - (df.col_x % 2).ne(0) a True b False c True Name: col_x, dtype: bool Further Reading 10 Minutes to Pandas - Selection by Label Indexing and selecting data Boolean indexing Selection with .loc in python pandas loc vs. iloc vs. ix vs. at vs. iat?
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48035493
score: 18
answers question: http://stackoverflow.com/q/48035493
type: AcceptedAnswer

http://stackoverflow.com/comment/83242687
has text: 'from tkinter import * import tkinter root = Tk() name = 'Jeff' dob = '01/01/2000' gender = 'male' text = str(name)+'\t'+str(dob)+'\t'+str(gender) Lb = Listbox(root) Lb.insert(0, text) Lb.insert("end", "1\t2\t3\t4\t5") Lb.pack() Lb.selection_set(0) root.mainloop()'
type: Comment
comment on: http://stackoverflow.com/a/48132007
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83211942
comment on: http://stackoverflow.com/q/48116337
type: QuestionComment
score: 1
has text: But you _do_ have two dictionaries. You run your code once, and your file has one dictionary. You run your code a second time, and your file now has two dictionaries.
type: Comment

http://stackoverflow.com/a/48063855
answers question: http://stackoverflow.com/q/48063800
score: 6
type: Answer
downvote count: 0
has body: You should split your strings on the arrow characters, reverse, then join them back. This works: [' -&gt; '.join(reversed(a.split(' -&gt; '))) for a in arr]
has comment: http://stackoverflow.com/comment/83107085
upvote count: 6

http://stackoverflow.com/comment/83143335
score: 0
has text: yes, they are sorted by first element
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48084224

http://stackoverflow.com/comment/83057300
type: AnswerComment
has text: RuntimeError: maximum recursion depth exceeded Any ideas ?
type: Comment
comment on: http://stackoverflow.com/a/48043157
score: 0

http://stackoverflow.com/comment/83105595
score: 1
comment on: http://stackoverflow.com/q/48065753
has text: Probably a great example here as to why you should provide your code/query and not just an (open ended) question. You would have an answer already if you did. Since we only are able to guess at what you are thinking, the answer we can give is "yes you can order and group in the same query".
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48087534
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48087725
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83150038
duplicate of: http://stackoverflow.com/q/23199796
has answer: http://stackoverflow.com/a/48087725
has body: Plot of sensor I have an experiment on a sensor that contains 8 electrodes. The image above is a plot of the electrode output vs time. As you can see on the plot, one of the 8 electrodes is clearly an outlier (probably due to some electrical failure). The plot is generated from a Pandas DataFrame, which essentially has 10 columns (1 for time, 8 for the electrodes, and 1 averaging the 8 electrodes). What is the best way to statistically detect that one of the columns is an outlier? I imagine the outlier column can then just be dropped from the dataframe. Thanks!
type: Question
linked to: http://stackoverflow.com/q/23199796
score: 4
has title: Checking a Pandas Dataframe for Outliers
upvote count: 4

http://stackoverflow.com/comment/83210777
type: Comment
comment on: http://stackoverflow.com/a/48115476
has text: is it giving an error or your objective is not achieved ?
score: 0
type: AnswerComment

http://stackoverflow.com/q/48028747
score: 0
tagged with: sqlite
answer count: 1
has title: How to only pull one column, but need both columns information
type: UnansweredQuestion
tagged with: python
has body: I have a sql query, that works the way i want it, as i need it to pull the information, but i don't want my department column Example qry = """ select distinct Department , (select count(*) from MyTable t2 where t2.Department = t1.Department and t2.CompletedTraining='Incomplete') as Total from MyTable t1 ORDER BY Department ASC df = pd.read_sql_query(qry, con) print("Incomplete Training") print(df) Current Output: Incomplete Training Department Total 0 AQPSD 6 1 ASD 8 2 CO 2 3 ECARS 3 4 ED 6 5 EO 4 6 ISD 4 7 MLD 0 8 MSCD 5 9 OIS 0 10 RD 2 11 TTD 4 I would like my query to only put put Total column, but still have the same data, so output would be Incomplete Training 0 6 1 8 2 2 3 3 4 6 5 4 6 4 7 0 8 5 9 0 10 2 11 4
has answer: http://stackoverflow.com/a/48029069
type: Question

http://stackoverflow.com/comment/83062621
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48044646
has text: Your second code block runs each of the middle functions (that is, all but the first and last) twice. You should probably just call them all inside a single `try` statement (or even without the `try`/`except`, and just let the exception stop the program).

http://stackoverflow.com/comment/83303269
type: Comment
type: QuestionComment
has text: @keipa, Mean :)
comment on: http://stackoverflow.com/q/48161758
score: 0

http://stackoverflow.com/a/48114614
has comment: http://stackoverflow.com/comment/83205888
has body: That's a good question. tf.estimator.DNNClassifier is using tf.losses.sparse_softmax_cross_entropy loss, in other words it expects ordinal encoding, instead of one-hot (can't find it in the doc, only the source code): labels must be a dense Tensor with shape matching logits, namely [D0, D1, ... DN, 1]. If label_vocabulary given, labels must be a string Tensor with values from the vocabulary. If label_vocabulary is not given, labels must be an integer Tensor with values specifying the class index. You should read the data with one_hot=False and also cast the labels to int32 to make it work: y=ydata.astype(np.int32)
has comment: http://stackoverflow.com/comment/83206034
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48114258
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48114258
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/83125929
comment on: http://stackoverflow.com/q/48062763
score: 0
type: QuestionComment
type: Comment
has text: "Mysql without Python and Django is of no use for me" => you can't expect to properly use Django models (the ORM part) if you don't understand how it translates at the database level (schema, queries etc) nor have any notion of proper relational database schemas design. But if you really insist on wasting your time then please go ahead...

http://stackoverflow.com/q/48042951
answer count: 2
tagged with: forecasting
tagged with: keras
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/83057874
has body: I am very new to the doing time-series forecasting in Keras. For the problem I am working on, I want to know how well my model is performing. I would like to know of some best practices for accomplishing this task. Please advise, and thanks in advance.
has title: How do I "measure" the performance of a time-series forecasting code in Keras?
score: 1
has answer: http://stackoverflow.com/a/48043807
favorite count: 0
upvote count: 2
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/48431630
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48043807
possible better answer: http://stackoverflow.com/a/48431630
type: Question
tagged with: time-series

http://stackoverflow.com/a/48088830
answers question: http://stackoverflow.com/q/48087095
upvote count: 2
has body: The only data you are passing to the template is locals(), which would be your local variables. I suggest passing specific variables to your template instead like this: return render(request, 'news/article.html', { 'news_articles': news_articles, 'article': article}) Now that it is easier to read you can see how your variables are passed to your article.html template from new() and why it works on this template. news_articles isn't working on your product.html template because you do not have your local variables set in product(). When you pass locals() to this template you are sending: return render(request, 'products/product.html', { 'product_images': product_images, 'product': product, 'links': links}) Add your news_articles variable to product() and add it to render to access them on your template.
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/83228595
comment on: http://stackoverflow.com/q/48125788
score: 0
type: QuestionComment
type: Comment
has text: it's returning the data is encoded form `{'cells': [<LTTextLineHorizontal>]}`

http://stackoverflow.com/q/48048310
type: Question
has comment: http://stackoverflow.com/comment/83070712
has comment: http://stackoverflow.com/comment/83073394
has comment: http://stackoverflow.com/comment/83073179
has comment: http://stackoverflow.com/comment/83073591
has answer: http://stackoverflow.com/a/48051087
answer count: 1
has title: extending a url to another in django
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83073383
tagged with: python
has comment: http://stackoverflow.com/comment/83068722
has body: I have a django application where by I can create a category and from the category I can select a subcategory before selecting a post. I have also created slugs for both the category , subcategory and the post and this works fine. what I now want to do but could not achieve is to make the subcategory slug continous on d category that is if the slug is http://127.0.0.1:8000/house/ before clicking on a subcategory, I want the url to look like this after clicking on a post under house http://127.0.0.1:8000/house/duplex with dublex being a subcategory of the category house. below is my model for my sub category Models.py class SubCategory(models.Model): category = models.ForeignKey(Category, related_name='property', on_delete=models.CASCADE) name = models.CharField(max_length=400,db_index=True) slug = models.SlugField(max_length=400,db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'subcategory' verbose_name_plural = 'subcategories' def __str__(self): return self.name def get_absolute_url(self): return reverse('subcategory:property_list_by_subcategory', args=[self.slug]) View def index(request, subcategory_slug=None): subcategory = None subcategories = SubCategory.objects.all() properties = Property.objects.filter(available=True) if subcategory_slug: subcategory = get_object_or_404(SubCategory, slug=subcategory_slug) properties = properties.filter(subcategory=subcategory) context = { 'subcategory': subcategory, 'subcategories': subcategories, 'properties': properties } template = 'subcategory/index.html' return render(request, template, context) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P&lt;subcategory_slug&gt;[-\w]+)/$',views.index, name='property_list_by_subcategory'), ] additional codes would be supplied on request.
has comment: http://stackoverflow.com/comment/83073212
score: 0
has comment: http://stackoverflow.com/comment/83070687
tagged with: django

http://stackoverflow.com/q/48033369
has body: I have been writing a few programs for the raspberry pi camera, namely one that just shows the camera output, one that takes a picture and then applies face recognition and so on. I got most of these working but I am having trouble incorporating all these into 1 program. What I'm thinking is just simple buttons than when pressed will execute the associated python script, for simplicity sake lets say I just want to execute the simplest one, just the output of the camera. I have the code written like this. import cv2 import time from picamera.array import PiRGBArray from picamera import PiCamera camera =PiCamera() camera.resolution=(320, 240) camera.framerate=30 rawCapture=PiRGBArray(camera, size=(320, 240)) time.sleep(1) for frame in camera.capture_continuous(rawCapture, format="bgr" , use_video_port=True): image=frame.array cv2.imshow("Faces" , image) key = cv2.waitKey(1) rawCapture.truncate(0) Now I have another code, done mostly in tkinter thats just the buttons that call the code to execute the camera script. I want it to look something like this. from Tkinter import * def executeCameraScript(): #Code for the camera script to trigger def option2(): #x def option3(): #y root = Tk() frame= Frame(root) frame.pack() button=Button(frame, text="Turn on the Camera", command=executeCameraScript) button.pack(side=LEFT) button=Button(frame, text="Option3", command=option2) button.pack(side=LEFT) button=Button(frame, text="Option3", command=option3) button.pack(side=LEFT) root.mainloop() My question is what should I use so that when I press the Turn on the Camera button , it executes the camera script (preferably without closing the button frame so I can close the script from there as well) , is there any simple way to do this ?
tagged with: opencv
has comment: http://stackoverflow.com/comment/83037054
tagged with: camera
has title: Using tkinter buttons to execute another script
has comment: http://stackoverflow.com/comment/83037647
has comment: http://stackoverflow.com/comment/83038829
has comment: http://stackoverflow.com/comment/83037685
type: Question
has comment: http://stackoverflow.com/comment/83038591
score: 0
tagged with: raspberry-pi
answer count: 1
has comment: http://stackoverflow.com/comment/83040470
has comment: http://stackoverflow.com/comment/83041392
has comment: http://stackoverflow.com/comment/83037033
has comment: http://stackoverflow.com/comment/83037041
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83045239
has answer: http://stackoverflow.com/a/70933122
tagged with: python

http://stackoverflow.com/comment/83317209
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48164698
score: 0
has text: I fixed my question hopfully it makes sense now

http://stackoverflow.com/q/48061206
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I am trying to make a simple shop application with asciimatics module.It is supposed to be a app where you can browse products, like in a shop and then you can add or delete the item from your cart. I was using their contact list sample app as my guide, but when I wrote my code I got stuck at this error kumecky@osmijanko:~/notebooks$ python3 form.py Traceback (most recent call last): File "form.py", line 103, in &lt;module&gt; Screen.wrapper(demo, catch_interrupt=True, arguments=[last_scene]) File "/usr/local/lib/python3.5/dist-packages/asciimatics/screen.py", line 1167, in wrapper func(screen, *arguments) File "form.py", line 97, in demo screen.play(scenes, stop_on_resize=True) File "/usr/local/lib/python3.5/dist-packages/asciimatics/screen.py", line 1343, in play scenes, unhandled_input=unhandled_input, start_scene=start_scene) File "/usr/local/lib/python3.5/dist-packages/asciimatics/screen.py", line 1406, in set_scenes old_scene=start_scene, screen=self) File "/usr/local/lib/python3.5/dist-packages/asciimatics/scene.py", line 44, in reset effect.reset() File "/usr/local/lib/python3.5/dist-packages/asciimatics/widgets.py", line 552, in reset self.data = deepcopy(self._initial_data) File "/usr/local/lib/python3.5/dist-packages/asciimatics/widgets.py", line 475, in data layout.update_widgets() File "/usr/local/lib/python3.5/dist-packages/asciimatics/widgets.py", line 1162, in update_widgets widget.value = widget.value File "/usr/local/lib/python3.5/dist-packages/asciimatics/widgets.py", line 2224, in value for i, [_, value] in enumerate(self._options): ValueError: too many values to unpack (expected 2) Here is my code - ShopDB class is just holding database object and Shop class is working with asciimatics module itself. from asciimatics.widgets import Frame, ListBox, Layout, Divider, Text, \ Button, TextBox, Widget from asciimatics.scene import Scene from asciimatics.screen import Screen from asciimatics.exceptions import ResizeScreenError, NextScene, StopApplicati…
type: Question
has answer: http://stackoverflow.com/a/48062001
has title: asciimatics too many values to unpack (expected 2) error
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48062001
tagged with: python-module

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

http://stackoverflow.com/a/48118218
score: 0
type: Answer
has body: You can achieve this using sets and itertools.combinations: word = "Demo Deer Deep Deck Cere Reep Creep Creeps" split_word = word.split() from itertools import combinations letters = {s for it in split_word for s in it.lower()} out = dict() for n in range(len(letters)): out[n] = {''.join(letters_subset): [word for word in split_word if set(word.lower()).issubset(letters_subset)] for letters_subset in combinations(letters, n)} out[n] = {k: v for k, v in out[n].items() if len(v) &gt; 0} # Print output for n, d in out.items(): for k, v in d.items(): print('{}:\t{}\t{}'.format(n, k, v))
answers question: http://stackoverflow.com/q/48116843

http://stackoverflow.com/q/48045217
has answer: http://stackoverflow.com/a/48068472
has body: TL;DR: I have combined 1,000 mp3 files into one large mp3 file, but am unable to pass this file through the Torch framework. I have been able to use Torch to successfully generate unique output from Shakespeare samples. Now, I want to take this a step further and input an audio file instead of a text file. bash$ audio.load(/path/to/fullyMerged.mp3) -bash: syntax error near unexpected token `/path/to/fullyMerged.mp3' I tried using audio.load(path) as suggested on torch documentation here, but I get an unexpected token error. Edit: Here are some things I have tried, but failed Tried inputting mp3 directly using, however, mp3 is an invalid input: python scripts/preprocess.py --input_mp3 data/fullyMerged.mp3 --output_h5 data/fullyMerged.h5 --output_json data/fullyMerged.json Tried renaming the .mp3 extension to .txt and feeding it into Torch, however, that returns a UnicodeDecodeError, since audio cannot be represented as text Tried converting my .mp3 file into .raw format, .wav format, and many others, however, no audio format was processable by Torch. Also tried renaming the extensions of these converted .raw and .wav files into .txt, but that still gave me a UnicodeDecodeError I've spent countless hours trying to get Torch to process audio, but am unable to do so! Any feedback at all would be greatly appreciated.
downvote count: 4
has comment: http://stackoverflow.com/comment/83078147
favorite count: 0
has comment: http://stackoverflow.com/comment/83110559
has title: How can I input audio?
has comment: http://stackoverflow.com/comment/83107430
type: Question
answer count: 2
tagged with: python
tagged with: artificial-intelligence
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/83078204
has answer: http://stackoverflow.com/a/48068299
tagged with: algorithm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83078220
score: -3
tagged with: torch

http://stackoverflow.com/q/48163135
tagged with: python
has answer: http://stackoverflow.com/a/48163178
accepted answer: http://stackoverflow.com/a/48163178
has answer: http://stackoverflow.com/a/48163264
tagged with: django
has answer: http://stackoverflow.com/a/48163183
type: AnsweredQuestion
has title: How to rewrite the Django model save method?
type: Question
score: 0
has body: How to rewrite the Django model save method? class Message(models.Model): """ message """ message_num = models.CharField(default=getMessageNum, max_length=16) title = models.CharField(max_length=64) content = models.CharField(max_length=1024) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): # I want send email there pass I mean, in the Django model, if I create instance success, I want to call a function, such as send a email in the function. I find in the Django model have a save method. I am not sure whether should write other code, because there are so many params. I mean whether I only should care about my send email logic?
possible better answer: http://stackoverflow.com/a/48163183
answer count: 3

clr
type: Tag
tags question: http://stackoverflow.com/q/48156741
tag name: clr

http://stackoverflow.com/q/48170638
has comment: http://stackoverflow.com/comment/83320785
has comment: http://stackoverflow.com/comment/83321320
has comment: http://stackoverflow.com/comment/83320875
answer count: 1
has comment: http://stackoverflow.com/comment/83320714
has comment: http://stackoverflow.com/comment/83321038
has comment: http://stackoverflow.com/comment/83322819
score: 0
has title: Using "any" as a value in Python
has comment: http://stackoverflow.com/comment/83320633
tagged with: python
has answer: http://stackoverflow.com/a/48170947
has comment: http://stackoverflow.com/comment/83320748
has body: I'm writing a function like this (in the context of AWS/SNS): def validate(message, topic=None): if topic == any or topic == message.topic: accept() else: reject() ... The value any in the condition is actually the built-in function any. But here I'm not using it for its designed purpose, but as a constant, to indicate that any topic would be accepted without colliding with any possible existing topic value (which are strings). I have the feeling this is not a good idea, but I can't find a good reason why it isn't. Also, I've tried googling this, but "any" is too common a word and I haven't had luck finding a discussion about this. Is this right, wrong, pythonic?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83320770
type: Question
has comment: http://stackoverflow.com/comment/83320767

large-data
tags question: http://stackoverflow.com/q/48086961
type: Tag
tag name: large-data

http://stackoverflow.com/comment/83227861
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48125438
has text: OK, then check my answer.

http://stackoverflow.com/a/58896016
score: 0
has body: Here's a simpler way to go about it, using either iterative or recursive methods: function FibSmartRecursive(n, a = 0, b = 1) { return n &gt; 1 ? FibSmartRecursive(n-1, b, a+b) : a; } function FibIterative(n) { if (n &lt; 2) return n; var a = 0, b = 1, c = 1; while (--n &gt; 1) { a = b; b = c; c = a + b; } return c; } function FibMemoization(n, seenIt = {}) {//could use [] as well here if (n &lt; 2) return n; if (seenIt[n]) return seenIt[n]; return seenIt[n] = FibMemoization(n-1, seenIt) + FibMemoization(n-2, seenIt); } console.log(FibMemoization(25)); //75025 console.log(FibIterative(25)); //75025 console.log(FibSmartRecursive(25)); //75025
type: Answer
answers question: http://stackoverflow.com/q/48150328

http://stackoverflow.com/comment/83187287
type: Comment
has text: If the values of a variable are strings, then they are automatically treated as categorical in the formulas. C(Area) and Area should produce the same designmatrix and parameter names.
comment on: http://stackoverflow.com/a/48104568
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83178689
comment on: http://stackoverflow.com/a/48086616
has text: Scrapy will have no problem parsing a local file, just give it a file:// URI
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48090641
tagged with: request
tagged with: urllib
type: Question
has answer: http://stackoverflow.com/a/48091064
score: 0
tagged with: urllib2
answer count: 2
tagged with: urllib3
linked to: http://stackoverflow.com/q/22676
has body: I would like to download data from this website. I inspected the source code and found that it uses the following link format for downloading data. url = 'http://current.hydro.gov.hk/en/download_csv.php?start_dt={}%20{}:00&amp;end_dt={}%20{}:00&amp;mode=Surface' url_filled = url.format("2018-01-02", "00:00", "2018-01-02", "23:45") Then I tried to use request to download the CSV data. import requests r = requests.get(url_filled) But then I received error. TimeoutError Traceback (most recent call last) ~\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connection.py in _new_conn(self) 140 conn = connection.create_connection( --&gt; 141 (self.host, self.port), self.timeout, **extra_kw) 142 ~\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py in create_connection(address, timeout, source_address, socket_options) 82 if err is not None: ---&gt; 83 raise err 84 ~\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\util\connection.py in create_connection(address, timeout, source_address, socket_options) 72 sock.bind(source_address) ---&gt; 73 sock.connect(sa) 74 return sock TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond During handling of the above exception, another exception occurred: NewConnectionError Traceback (most recent call last) ~\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw) 599 body=body, headers=headers, --&gt; 600 chunked=chunked) 601 ~\AppData\Local\Continuum\Anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httpli…
accepted answer: http://stackoverflow.com/a/48091064
possible better answer: http://stackoverflow.com/a/48090975
has title: Download from links using python
has comment: http://stackoverflow.com/comment/83156022
has answer: http://stackoverflow.com/a/48090975
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48063382
linked to: http://stackoverflow.com/q/25292239
has comment: http://stackoverflow.com/comment/83099689
tagged with: refactoring
has answer: http://stackoverflow.com/a/48063622
type: Question
has comment: http://stackoverflow.com/comment/83099873
answer count: 2
score: 5
has answer: http://stackoverflow.com/a/48064072
upvote count: 5
has comment: http://stackoverflow.com/comment/83099744
has title: Is it good to use inner function in a python function to make the logic clear?
has comment: http://stackoverflow.com/comment/83100244
has comment: http://stackoverflow.com/comment/83099813
has comment: http://stackoverflow.com/comment/83100236
has comment: http://stackoverflow.com/comment/83350686
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: Below is the basic logic for function foo: def foo(item_lst): val_in_foo_scope = 1 for item in item_lst: # some logic to deal with item # val_in_foo_scope used pass return 0 The logic in the loop can be very complex, in order to make the code more clear, I want to split the logic with a separate function. With inner function: def foo(item_lst): val_in_foo_scope = 1 def some_logic(item): # val_in_foo_scope used pass for item in item_lst: some_logic(item) return 0 With outer function: def some_logic(item, val): # val used pass def foo(item_lst): val_in_foo_scope = 1 for item in item_lst: some_logic(item, val_in_foo_scope) return 0 The inner function version val_in_foo_scope can be used directly -- good we can easily know that the some_logic is relevant with foo, actually only be used in function foo -- good each time function foo is called, a new inner function will be created -- not so good The outer function version val_in_foo_scope can not be used directly -- not so good we can not see the relevance between some_logic and foo directly -- not so good some_logic will be created one time -- good there will be so many functions in the global namespace -- not so good So, which solution is better or is there any other solutions? Factors below or any other factors you come up with can be considered： val_in_foo_scope is used or not whether the time cost to create inner function each time can be ignored
has comment: http://stackoverflow.com/comment/83099690
has comment: http://stackoverflow.com/comment/83099619

http://stackoverflow.com/q/48172961
has answer: http://stackoverflow.com/a/48173660
has title: Make a category on a server with a BOT inside the discord.py API
tagged with: python
score: 2
has body: I am new to Python (and, of course to discord.py), and I didn't really find any documentation on websites or on the official Discord for this question. I was wondering if there is any function inside discord.py that would create a category on a server (client.get_server('295959610043531264')) Thanks a lot ;)
downvote count: 0
type: Question
tagged with: discord.py
upvote count: 2
answer count: 2
tagged with: discord
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/58147608
type: UnansweredQuestion

http://stackoverflow.com/a/48097270
accepted answer of: http://stackoverflow.com/q/48092212
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83203486
score: 1
answers question: http://stackoverflow.com/q/48092212
has body: Are you using python 3? Because it seams mysql_to_gcs of the latest version (1.90) is not python compatible it seams. It seams that this operator was changed here to make mysql_to_gcs py3 compatible. But the latest version(1.90) doesn't include this change
downvote count: 0
has comment: http://stackoverflow.com/comment/83170530
has comment: http://stackoverflow.com/comment/83170856
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83193029

http://stackoverflow.com/a/48101748
has body: Try this: newfile = r'output.txt' oldfile = r'input.txt' with open(newfile, 'w') as outfile, open(oldfile, 'r') as infile: for line in infile: if if line[:5].lower() == 'small': outfile.write(line) #output small:door Small:chair Of course, this assumes you want to eliminate rows where small or Small is to the left of the colon. Additionally, you will have a new file output, as I don't think you really want to update your input file.
has comment: http://stackoverflow.com/comment/83178707
type: Answer
has comment: http://stackoverflow.com/comment/83179955
has comment: http://stackoverflow.com/comment/83179924
score: 0
answers question: http://stackoverflow.com/q/48101298

http://stackoverflow.com/q/48167475
tagged with: boto3
has answer: http://stackoverflow.com/a/48171558
answer count: 1
downvote count: 0
score: 1
tagged with: aws-lambda
favorite count: 0
type: UnansweredQuestion
has body: I want to insert data from AWS Lambda to AWS DynamoDB and upload a file from Lambda to AWS S3. Currently, I'm using Access Key and Secret Key to do this from boto3. But, due to security issues, I had to change this approach to role-based approach. (i.e) To insert data in DDB or uploading a file to S3 I should use the provided role_ARN. I had spent enough time in searching for a clue of doing this. If anybody knows please help me. Thanks in advance
tagged with: python
tagged with: amazon-dynamodb
upvote count: 1
has title: boto3 support for role_arn
type: Question
has comment: http://stackoverflow.com/comment/83314443

http://stackoverflow.com/comment/83202960
score: 0
comment on: http://stackoverflow.com/a/48099068
type: AnswerComment
has text: Thank You! Worked perfectly
type: Comment

http://stackoverflow.com/comment/83306312
score: 0
type: Comment
has text: is there an index on product.goods_id ? I assumed there is, but if this is not the case, that can be source of lost time.
type: AnswerComment
comment on: http://stackoverflow.com/a/48162994

http://stackoverflow.com/comment/83302152
score: 0
comment on: http://stackoverflow.com/a/48161349
type: AnswerComment
type: Comment
has text: Ok. That is great. Thanks!

http://stackoverflow.com/q/48046843
tagged with: python
has comment: http://stackoverflow.com/comment/83065225
has comment: http://stackoverflow.com/comment/83453421
has answer: http://stackoverflow.com/a/48047051
has title: Converting Java to Python
downvote count: 9
tagged with: java
has comment: http://stackoverflow.com/comment/83065198
type: Question
score: -9
has comment: http://stackoverflow.com/comment/83071317
upvote count: 0
answer count: 1
tagged with: hashlib
favorite count: 0
has comment: http://stackoverflow.com/comment/83065202
has body: I was wondering if you guys could help me convert some java code to python. Basically I'm trying to get the same hash output that the java code executes. Currently all I have gotten to (in python) is using the hashlib module converting some string to sha256. I have tried googling and I have found nothing, friends couldn't help so this is my last resort. Here is the hash outputs I get from python &amp; java. Obviously python being the incorrect hash, and java code being the correct hash. Java Code Output Hash(correct): 947e238ef26e56d3de2fe2480268c23297d91efe6355b3e5fac0dcf63 Python Code Output Hash(incorrect): 88c5f638b023a5740676960747833fc4eacc20697c92e1b46b0384ebf The java code hashes a string which gets split into variables, im stuck on the for loop which I'm not able to convert to python. PLEASE take note I am a noob and not that very experienced, thanks :P. Java CODE: String pass = "6b508/^!zVl?947e238ef26e56d3de2fe2480268c23297d91efe6355b3e5fac0dcf63"; String secretKey = "Wr79mk1PXFac!#%"; String loginKey = pass.substring(0, 5); String randomKey = pass.substring(5, 13); String originalHash = pass.substring(13); try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update((loginKey + randomKey + secretKey).getBytes(StandardCharsets.UTF_8)); //obtain hash byte[] hash = md.digest(); StringBuilder hexString = new StringBuilder(); for (byte aHash : hash) { String hex = Integer.toHexString(0xff &amp; aHash); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } String newHash = hexString.toString().substring(0, 56); if (newHash.equals(originalHash)) { //hash is right return true; } Python CODE(My attempt to convert): key = "6b508" salt = "Wr79mk1PXFac!#%" rand = "/^!zVl?" hash = hashlib.sha256(key+rand+salt).hexdigest() raw_input(hash[0:57]) Any help would be appreciated, thanks.
tagged with: hash
type: UnansweredQuestion

http://stackoverflow.com/q/48070373
answer count: 1
has title: Cannot call function that expects list of double
has body: I'm testing out a python library that is a SWIG wrapper. One of the functions in this library is: def point_inside(self, *args) -&gt; "bool": return _vulcanpy.TRI_triangulation_t_point_inside(self, *args) As far as I can tell, this function should take either a list of double, or three doubles. When I call it with three numbers, it works: &gt;&gt;&gt; tri.point_inside(100,100,100) True When I call it with a list of numbers, it fails: &gt;&gt;&gt; tri.point_inside([100,100,100]) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Program Files\Maptek\Vulcan 10.1\bin\exe\lib\site-packages\vulcan.py", line 1551, in point_inside return _vulcanpy.TRI_triangulation_t_point_inside(self, *args) NotImplementedError: Wrong number or type of arguments for overloaded function 'TRI_triangulation_t_point_inside'. Possible C/C++ prototypes are: TRI_triangulation_t::point_inside(double_list) TRI_triangulation_t::point_inside(double,double,double) Is there some syntax I'm missing to invoke the second overload correctly? Not sure whether this is useful, but when I call a different function that returns list of double I get the obvious result. def get_elevations(self, x: 'double', y: 'double') -&gt; "double_list": return _vulcanpy.TRI_triangulation_t_get_elevations(self, x, y) &gt;&gt;&gt; tri.get_elevations(100,100) [88.0, 88.0, 112.0, 112.0]
tagged with: python
has answer: http://stackoverflow.com/a/48070598
has comment: http://stackoverflow.com/comment/83114647
type: AnsweredQuestion
tagged with: swig
has comment: http://stackoverflow.com/comment/83114671
accepted answer: http://stackoverflow.com/a/48070598
type: Question
score: 0

http://stackoverflow.com/q/48054298
type: AnsweredQuestion
has title: Finding nearest timeindex for many categories
type: Question
accepted answer: http://stackoverflow.com/a/48054452
tagged with: time-series
possible better answer: http://stackoverflow.com/a/48054467
has answer: http://stackoverflow.com/a/48054467
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48054452
tagged with: python
has body: I am trying to obtain the data points nearest to the query timestamp for multiple independent categories like this (example in more detail in the gist): dt = pd.to_datetime(dt) df_output = list() for category in df.category.unique(): df_temp = df[df.category == category] i = df_temp.index.get_loc(dt, method='nearest') latest = df_temp.iloc[i] df_output.append(latest) pd.DataFrame(df_output) The issue with this approach is that it is very slow (and obviously feels very blunt). Profiling suggests the bottleneck is iloc, which seems odd. What is a faster/more correct way to go about it? Is there a way to obtain the result for all of the categories at once? (I'm thinking of some groupby magic) Is pandas capable of doing it or should I switch to some other timeseries storage method?

http://stackoverflow.com/q/48046391
tagged with: scrapy
type: Question
has title: Removing blank lines in csv output on Windows 10 without an error
upvote count: 1
has comment: http://stackoverflow.com/comment/83197505
tagged with: http://stackoverflow.com/tag/csv
favorite count: 0
has body: I'm using Scrapy 1.4.0 and Python 3.6.3. When I run "scrapy crawl -o items.csv", every other line of the csv file is blank. While I did find a solution here, it generates the following error: 2017-12-31 18:39:48 [scrapy.utils.signal] ERROR: Error caught on signal handler: &lt;bound method FeedExporter.item_scraped of &lt;scrapy.extensions.feedexport.FeedExporter object at 0x000001FEA491D128&gt;&gt; Traceback (most recent call last): File "c:\programdata\anaconda3\lib\site-packages\twisted\internet\defer.py", line 150, in maybeDeferred result = f(*args, **kw) File "c:\programdata\anaconda3\lib\site-packages\pydispatch\robustapply.py", line 55, in robustApply return receiver(*arguments, **named) File "c:\programdata\anaconda3\lib\site-packages\scrapy\extensions\feedexport.py", line 224, in item_scraped slot.exporter.export_item(item) File "c:\programdata\anaconda3\lib\site-packages\scrapy\exporters.py", line 243, in export_item self.csv_writer.writerow(values) File "c:\programdata\anaconda3\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 77-78: character maps to &lt;undefined&gt; Thank you in advance. Here's the code: import scrapy from scrapy import Request class JobsSpider(scrapy.Spider): name = 'jobs' allowed_domains = ['craigslist.org'] start_urls = ['https://newyork.craigslist.org/search/egr?s=120'] def parse(self, response): jobs = response.xpath('//p[@class="result-info"]') for job in jobs: title = job.xpath('a[@class="result-title hdrlnk"]/text()').extract_first() address = job.xpath('span[@class="result-meta"]/span[@class="result-hood"]/text()').extract_first("")[2:-1] relative_url = job.xpath('a/@href').extract_first() yield Request(relative_url, callback=self.parse_page, meta={'URL': relative_url, 'Title': title, 'Address':address}) def parse_page(self, response): url = response.meta.get('URL') title = response.meta.get('Tit…
linked to: http://stackoverflow.com/q/45908465
has comment: http://stackoverflow.com/comment/83064421
type: UnansweredQuestion
tagged with: web-scraping
tagged with: python
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83064378

http://stackoverflow.com/q/48081743
tagged with: filepath
tagged with: audio
tagged with: tensorflow
type: Question
score: 0
answer count: 1
tagged with: librosa
has answer: http://stackoverflow.com/a/48081825
has body: sound_file_paths =[ "/Users/ferhatkaygun/Desktop/UrbanSound8K/audio/fold1/57320-0-0-7.wav", "/Users/ferhatkaygun/Desktop/UrbanSound8K/audio/fold1/24074-1-0-3.wav", "/Users/ferhatkaygun/Desktop/UrbanSound8K/audio/fold1/15564-2-0-1.wav", "/Users/ferhatkaygun/Desktop/UrbanSound8K/audio/fold1/31323-3-0-1.wav", "/Users/ferhatkaygun/Desktop/UrbanSound8K/audio/fold1/46669-4-0-35.wav", ] sound_names = [ "air conditioner", "car horn", "children playing", "dog bark", "drilling", "engine idling", "gun shot", "jackhammer", "siren", "street music" ] raw_sounds = load_sound_files(sound_file_paths) Hey there, I am using librosa and I did not deal often with importing files into python programs. How can I import the files without receiving that sound file paths is not defined? The Programm was first coded in python 2.7 but I use the current version on Mac Os. could that be a problem
type: UnansweredQuestion
tagged with: python
has title: Python utilizing file paths

http://stackoverflow.com/comment/83109380
comment on: http://stackoverflow.com/a/48067811
score: 0
type: AnswerComment
has text: I added example with queue
type: Comment

http://stackoverflow.com/a/48109501
downvote count: 0
has body: You can use sklearn.preprocessing for a lot of types of pre-processing tasks including normalization.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48109228
upvote count: 2

http://stackoverflow.com/q/48117925
has comment: http://stackoverflow.com/comment/83212297
type: Question
has body: I want to take a screenshot with python/selenium with fixed size. In a strange way, the image is always -76 pixels in height. As a workaround I just add 76 pixels to the window_size. Can this be done in another way? It's important that the images is exactly 1080 x 1920 and I'm afraid that this solution is only temporary. My code #!/usr/bin/env python3 from pyvirtualdisplay import Display import sys import os from selenium import webdriver # Portrait mode 1080 width, 1920 height display = Display(visible=0, size=(1080, 1920)) display.start() browser = webdriver.Firefox() # Needs to be 76 pixels more than desired??? browser.set_window_size(1080,1996) browser.set_window_position(0, 0) browser.get('https://google.com') # Actually prints out 1080 x 1966 print(browser.get_window_size()) # Saves the file in 1080 x 1920 browser.save_screenshot('screenshot.png'); Solution Thanks to Andersson. The problem is the viewport size. Solution found here: How to set browser viewport size
tagged with: selenium-firefoxdriver
has comment: http://stackoverflow.com/comment/83212628
score: 0
linked to: http://stackoverflow.com/q/37181403
tagged with: python
has title: Python Selenium - Firefox driver cuts height
answer count: 0
tagged with: screenshot
type: UnansweredQuestion
tagged with: selenium

http://stackoverflow.com/comment/83261897
comment on: http://stackoverflow.com/a/48141900
has text: D'oh...You got me :)
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48062779
tagged with: python
has title: How to fix Visual Tracker Benchmark error
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/48065242
tagged with: matlab
type: Question
answer count: 1
downvote count: 0
score: 1
has body: I will be glad for any help to fix this I have found a Benchmark dataset with ground truth data, in order to test Tracker algorithms, I had downloaded their source code, I followed the instructions in readme file : I setup MATLAB engine for Python code I had installed matplotlib python -m pip install matplotlib I had installed numpy python -m pip install numpy python -m pip install numpy I had installed Python Imaging Library (PIL) in the readme file they said command : python run_trackers.py -t "tracker" -s "sequence" -e "evaltype" so I choosed Fish dataset, then when I run python run_trackers.py -t IVT -s Fish -e OPE,SRE,TRE, an erro messege shows up for missing .mat files for the tracker alogithms tracker_benchmark-master\trackers\IVT, I got them here at this point, I did everything no missing file, Matlab, PIL libs and python have the same version 64bit. I only have to execute the command python run_trackers.py -t IVT -s Fish -e OPE but unfortunately I got this errors
favorite count: 0

http://stackoverflow.com/a/48053312
downvote count: 0
has comment: http://stackoverflow.com/comment/83079495
has comment: http://stackoverflow.com/comment/83079019
has comment: http://stackoverflow.com/comment/83079422
has body: You aren't starting the server server.py: import os import asyncio import websockets class Server: def get_port(self): return os.getenv('WS_PORT', '8765') def get_host(self): return os.getenv('WS_HOST', 'localhost') def start(self): return websockets.serve(self.handler, self.get_host(), self.get_port()) async def handler(self, websocket, path): async for message in websocket: print('server received :', message) await websocket.send(message) if __name__ == '__main__': ws = Server() asyncio.get_event_loop().run_until_complete(ws.start()) asyncio.get_event_loop().run_forever() client.py #!/usr/bin/env python3.6 import asyncio import websockets async def msg(): async with websockets.connect('ws://localhost:8765') as websocket: await websocket.send('test message') msg = await websocket.recv() print(msg) if __name__ == '__main__': asyncio.get_event_loop().run_until_complete(msg()) asyncio.get_event_loop().run_forever()
type: AcceptedAnswer
upvote count: 6
has comment: http://stackoverflow.com/comment/83078936
has comment: http://stackoverflow.com/comment/83079625
has comment: http://stackoverflow.com/comment/83079081
answers question: http://stackoverflow.com/q/48052806
score: 6
has comment: http://stackoverflow.com/comment/83079581
type: Answer
accepted answer of: http://stackoverflow.com/q/48052806

http://stackoverflow.com/comment/83150038
comment on: http://stackoverflow.com/q/48087534
score: 2
has text: https://stackoverflow.com/questions/23199796/detect-and-exclude-outliers-in-pandas-dataframe
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48039976
score: 0
has comment: http://stackoverflow.com/comment/83050587
answers question: http://stackoverflow.com/q/48036586
has comment: http://stackoverflow.com/comment/83050496
type: Answer
has body: Assume for now that there are three images for a particular comparison run: Image 1 represents the original screenshot. Image 2 represents the changed/altered screenshot. Image 3 represents the (literal) difference between Image 1 and Image 2 when Image 1 is subtracted from Image 2 after both (Image 1 and Image 2) have been converted to greyscale. Now, here's how I would break the problem down. STEPS: For one instance, derive Image 3 and not store it. Image 3 should consist of all zeros (or black color) except areas that had changes. You might want to consider converting negative pixel values to positive ones. Run an if-statement check to see if the total of all the pixel values in Image 3 is greater than 0 to check if changes happened. If the total is greater than 0, break Image 3 down into very small blocks/cells (and not pixels). By "break Image 3 down", I mean apply a grid and break into individual square blocks/cells. See code here for help. You can use this code to derive coordinates of those blocks. Once you have the coordinates, run a loop through each one of the blocks to pinpoint exactly where the change(s) happened. Once you know where the change(s) happened and the corresponding coordinates, use the CV2 function here to draw rectangle(s) on either Image 1 or Image 2 to show where the change(s) happened. Display the image with the rectangle(s) showing possible change(s). Put steps 1 - 6 in a loop with a time delay before going to the next instance run.
has comment: http://stackoverflow.com/comment/83050532
has comment: http://stackoverflow.com/comment/83050599
has comment: http://stackoverflow.com/comment/83050797
has comment: http://stackoverflow.com/comment/83050660
has comment: http://stackoverflow.com/comment/83050867

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

http://stackoverflow.com/a/48042170
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48038422
answers question: http://stackoverflow.com/q/48038422
has comment: http://stackoverflow.com/comment/83055732
type: Answer
has body: I use mplot3d and bar to plot 3d-hist as follow: #!/usr/bin/python3 # 2017.12.31 18:46:42 CST # 2017.12.31 19:23:51 CST import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np ## the hist data data = np.array([ np.array([826, 145, 26, 2, 1, 0, 0, 0, 0, 0]), np.array([389, 446, 145, 16, 4, 0, 0, 0, 0, 0]), np.array([227, 320, 368, 73, 12, 0, 0, 0, 0, 0]), np.array([199, 128, 369, 261, 43, 0, 0, 0, 0, 0]), np.array([219, 92, 158, 393, 137, 1, 0, 0, 0, 0]), np.array([252, 90, 91, 237, 323, 6, 1, 0, 0, 0]), np.array([235, 89, 69, 96, 470, 36, 5, 0, 0, 0]), np.array([242, 78, 61, 51, 438, 114, 16, 0, 0, 0]), np.array([235, 82, 52, 52, 243, 279, 57, 0, 0, 0]) ]) ## other data fig = plt.figure() ax = fig.add_subplot(111, projection='3d') colors = ["r","g","b"]*10 ## Draw 3D hist ncnt, nbins = data.shape[:2] xs = np.arange(nbins) for i in range(ncnt): ys = data[i] cs = [colors[i]] * nbins ax.bar(xs, ys.ravel(), zs=i, zdir='x', color=cs, alpha=0.8) ax.set_xlabel('idx') ax.set_ylabel('bins') ax.set_zlabel('nums') plt.show()
has comment: http://stackoverflow.com/comment/83055242
upvote count: 2
has comment: http://stackoverflow.com/comment/83055949
has comment: http://stackoverflow.com/comment/104183168
score: 2

http://stackoverflow.com/q/48117224
upvote count: 0
has comment: http://stackoverflow.com/comment/83214722
favorite count: 0
has comment: http://stackoverflow.com/comment/83211924
type: UnansweredQuestion
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83212006
has answer: http://stackoverflow.com/a/48117691
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48117558
has title: Tkinter - Grid positioning completely unresponsive for some widjets
score: -1
has body: I have this code (some code cut out): root = tk.Tk() root.title("PyCipher") root.iconbitmap('D:\\PyCipher\\media\\icon.ico') root.geometry('510x325') root.resizable(width=False, height=False) root.columnconfigure(10, weight=1) root.rowconfigure(20, weight=1) rootframe = tk.Frame(root) rootframe.grid(row=10, column=5) headertxt = tk.Label(root, text='PyCipher', font=('Helvecta', 20, 'bold'), anchor='c') headertxt.grid(row=3, column=5) entrybox = tk.Entry(root, width=60) entrybox.grid(row=7, column=5) entrylabel = tk.Label(root, text='Enter Text to convert') entrylabel.grid(row=9, column=5) output = tkst.ScrolledText(master=rootframe,wrap=tk.WORD, width=50, height=10) output.grid(row=10, column=8) outputlabel = tk.Label(root, text='Output text') outputlabel.grid(row=15, column=5) encodebtn = tk.Button(root, text='Encode', fg='green', command=encode, width=5) encodebtn.grid(row=7, column=4) decodebtn = tk.Button(root, text='Decode', fg='orange', command=decode, width=5) decodebtn.grid(row=7, column=6) copybtn = tk.Button(root, text='Copy', fg='blue', command=copy, width=5) copybtn.grid(row=17, column=5) clrbtn = tk.Button(root, text='Clear', fg='red', command=clear, width=5) clrbtn.grid(row=18, column=5) root.mainloop() The issue is with the buttons. When I try to change the column value to 2-4 or 6-9, the elements are completely unresponsive to the position change. But when I set it to column 5, it completely breaks the ui by entering another widjet. Why cant I move any elements in those other columns yet column 5 completely moves the element to the area it should be? Padding ends up padding the entire UI, and even when the elements are far away from others, It still has the same issue.
answer count: 2

http://stackoverflow.com/q/48059490
has comment: http://stackoverflow.com/comment/83091342
score: 1
upvote count: 2
tagged with: split
answer count: 3
possible better answer: http://stackoverflow.com/a/48059553
downvote count: 1
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/48060566
has comment: http://stackoverflow.com/comment/83091323
has title: Check the list and split the sentence in python
tagged with: python
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/48059548
has answer: http://stackoverflow.com/a/48059553
has comment: http://stackoverflow.com/comment/83091281
has comment: http://stackoverflow.com/comment/83091311
type: Question
has answer: http://stackoverflow.com/a/48059548
has body: I have a list as follows. mylist = ['test copy', 'test project', 'test', 'project'] I want to see if my sentence includes the aforementioned mylistelements and split the sentence from the first match and obtain its first part. For example: mystring1 = 'it was a nice test project and I enjoyed it a lot' output should be: it was a nice mystring2 = 'the example test was difficult' output should be: the example My current code is as follows. for sentence in L: if mylist in sentence: splits = sentence.split(mylist) sentence= splits[0] However, I get an error saying TypeError: 'in &lt;string&gt;' requires string as left operand, not list. Is there a way to fix this?

http://stackoverflow.com/comment/83325905
type: QuestionComment
type: Comment
score: 0
has text: What exactly is the question here? How would you like the plot to look like?
comment on: http://stackoverflow.com/q/48172881

http://stackoverflow.com/a/48105165
answers question: http://stackoverflow.com/q/48091060
has comment: http://stackoverflow.com/comment/83218941
upvote count: 1
has comment: http://stackoverflow.com/comment/83214394
has comment: http://stackoverflow.com/comment/83187754
score: 0
downvote count: 1
type: Answer
has body: The code to connect to Mysql: from flaskext.mysql import MySQL cursorclass, and autocommit to make life easier mysql = MySQL(autocommit=True, cursorclass= DictCursor) app.config['SECRET_KEY'] = 'Thisissupposedtobesecret!' app.config['MYSQL_DATABASE_USER'] = 'root' app.config['MYSQL_DATABASE_PASSWORD'] = 'root' app.config['MYSQL_DATABASE_DB'] = 'db' app.config['MYSQL_DATABASE_HOST'] = 'localhost' app.config['MYSQL_DATABASE_PORT'] = 8889 app.config['MYSQL_CURSORCLASS'] = 'DictCursor' mysql.init_app(app) connect cursor cursor = conn.cursor() You can download xxamp or Mamp and host database online at phpmyadmin (localhost)

http://stackoverflow.com/q/48115990
accepted answer: http://stackoverflow.com/a/48116278
tagged with: pandas
answer count: 1
tagged with: python-3.x
has title: Data transformation in Python. Is there a better way?
tagged with: python
has answer: http://stackoverflow.com/a/48116278
type: Question
type: AnsweredQuestion
has body: Below is a code snippet of the task I have to perform. I want to have the best time complexity possible for this task. Is there a library or a better implementation? import pandas as pd import numpy as np df1 = pd.DataFrame({"v_id": [1,1,1,2,2,3,3,3,3,5,5], \ "date": ['01-01-2017', '02-01-2017', '03-01-2017',\ '02-01-2017', '03-01-2017', '01-01-2017', '02-01-2017', '03-01-2017', '04-01-2017',\ '05-01-2017','04-01-2017'],\ "value":[0.9,1.5,2.4,7.1,0.4,1.8,5.1, 6.4, 7.7, 3.9, 0.3]}) dim1, dim2 = df1.v_id.unique(), df1.date.unique() dim1_dict, dim2_dict = dict(zip(dim1, list(range(0, len(dim1))))), \ dict(zip(dim2, list(range(0, len(dim2))))) value_result, date_result = np.empty((len(dim1), len(dim2)), dtype=object),\ np.empty((len(dim1), len(dim2)), dtype=object) for i in range(0, len(df1)): date_result[dim1_dict.get(df1.loc[i].v_id), \ dim2_dict.get(df1.loc[i].date)] = df1.loc[i].date value_result[dim1_dict.get(df1.loc[i].v_id), \ dim2_dict.get(df1.loc[i].date)] = df1.loc[i].value The dataframe df1 looks like this: My goal is to get the date_result (v_id x date) array([['01-01-2017', '02-01-2017', '03-01-2017', None, None], [None, '02-01-2017', '03-01-2017', None, None], ['01-01-2017', '02-01-2017', '03-01-2017', '04-01-2017', None], [None, None, None, '04-01-2017', '05-01-2017']], dtype=object) &amp; value_result matrix (v_id x value). array([[0.90000000000000002, 1.5, 2.3999999999999999, None, None], [None, 7.0999999999999996, 0.40000000000000002, None, None], [1.8, 5.0999999999999996, 6.4000000000000004, 7.7000000000000002, None], [None, None, None, 0.29999999999999999, 3.8999999999999999]], dtype=object)
tagged with: numpy
score: 0

http://stackoverflow.com/a/48038337
has comment: http://stackoverflow.com/comment/83046977
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83047113
accepted answer of: http://stackoverflow.com/q/48038320
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48038320
has comment: http://stackoverflow.com/comment/83047002
has body: Because neither of those modules exist. The app is named "django.contrib.auth".
has comment: http://stackoverflow.com/comment/83047069
has comment: http://stackoverflow.com/comment/83046969

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/48055903
tags question: http://stackoverflow.com/q/48074856
tags question: http://stackoverflow.com/q/48158027
type: Tag
tags question: http://stackoverflow.com/q/48169538
tags question: http://stackoverflow.com/q/48141064
tags question: http://stackoverflow.com/q/48060454
tags question: http://stackoverflow.com/q/48131838
tags question: http://stackoverflow.com/q/48109515
tags question: http://stackoverflow.com/q/48140103
tags question: http://stackoverflow.com/q/48083001
tags question: http://stackoverflow.com/q/48114533
tags question: http://stackoverflow.com/q/48028758
tags question: http://stackoverflow.com/q/48123418
tag name: xml
tags question: http://stackoverflow.com/q/48161457
tags question: http://stackoverflow.com/q/48049478
tags question: http://stackoverflow.com/q/48035643
tags question: http://stackoverflow.com/q/48135562
tags question: http://stackoverflow.com/q/48114441
tags question: http://stackoverflow.com/q/48061093
tags question: http://stackoverflow.com/q/48103815
tags question: http://stackoverflow.com/q/48166430
tags question: http://stackoverflow.com/q/48127309

http://stackoverflow.com/comment/83000706
comment on: http://stackoverflow.com/a/48015408
has text: Where did your numbers come from? Do you know what sort of equation they should follow? Scipy's cubic spline-fitting https://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html is fine for interpolation but not so accurate (ie usually terrible) for extrapolation.
type: AnswerComment
type: Comment
score: 2

flask-ask
tags question: http://stackoverflow.com/q/48104535
tags question: http://stackoverflow.com/q/48131710
tags question: http://stackoverflow.com/q/48144214
tag name: flask-ask
type: Tag
tags question: http://stackoverflow.com/q/48078836

http://stackoverflow.com/q/48133838
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
tagged with: python-asyncio
answer count: 1
tagged with: asynchronous
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: How to make my program asynchronous with asyncio?
has answer: http://stackoverflow.com/a/48136794
has body: Here is my code: import urllib import webbrowser from bs4 import BeautifulSoup import requests import re address = 'https://google.com/search?q=' # Default Google search address start file = open( "OCR.txt", "rt" ) # Open text document that contains the question word = file.read() file.close() myList = [item for item in word.split('\n')] newString = ' '.join(myList) # The question is on multiple lines so this joins them together with proper spacing qstr = urllib.parse.quote_plus(newString) # Encode the string newWord = address + qstr # Combine the base and the encoded query response = requests.get(newWord) #with open('output.html', 'wb') as f: # f.write(response.content) #webbrowser.open('output.html') answers = open("ocr2.txt", "rt") ansTable = answers.read() answers.close() ans = ansTable.splitlines() ans1 = str(ans[0]) ans2 = str(ans[2]) ans3 = str(ans[4]) ans1Score = 0 ans2Score = 0 ans3Score = 0 links = [] soup = BeautifulSoup(response.text, 'lxml') for r in soup.find_all(class_='r'): linkRaw = str(r) link = re.search("(?P&lt;url&gt;https?://[^\s]+)", linkRaw).group("url") if '&amp;' in link: finalLink = link.split('&amp;') link = str(finalLink[0]) links.append(link) #print(links) #print(' ') for g in soup.find_all(class_='g'): webBlock = str(g) ans1Tally = webBlock.count(ans1) ans2Tally = webBlock.count(ans2) ans3Tally = webBlock.count(ans3) if ans1 in webBlock: ans1Score += ans1Tally else: ans1Found = False if ans2 in webBlock: ans2Score += ans2Tally else: ans2Found = False if ans3 in webBlock: ans3Score += ans3Tally else: ans3Found = False if ans1Found and ans2Found and ans3Found is False: searchLink = str(links[0]) if searchLink.endswith('pdf'): pass else: response2 = requests.get(searchLink) soup2 = BeautifulSoup(response2.text, 'lxml') for p in soup2.find_all('p'): extraBlock = str(p) extraAns1Tally = extraBlock.count(ans1) extraAns2tally = extraBlock.count(ans2) extraAns3Tally = extraBlock.count(ans3) if ans1 in extraBlock: ans1Score += extraAns1Tally if…
score: 1
has comment: http://stackoverflow.com/comment/94019501
type: Question
has comment: http://stackoverflow.com/comment/83245405

http://stackoverflow.com/comment/83325673
comment on: http://stackoverflow.com/q/48173022
has text: You cannot do it like this, but you can have it as an array and then check whether the starting char is in the array
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/83055127
comment on: http://stackoverflow.com/q/48042029
type: Comment
type: QuestionComment
score: 1
has text: Good point @BlownhitherMa Even 3 ** 5 fails.

http://stackoverflow.com/q/48164772
has answer: http://stackoverflow.com/a/48164872
type: Question
score: 5
answer count: 1
has title: Write a dict on aws dynamodb as avS with python
tagged with: boto3
tagged with: amazon-web-services
upvote count: 5
tagged with: python
favorite count: 0
downvote count: 0
accepted answer: http://stackoverflow.com/a/48164872
tagged with: amazon-dynamodb
has body: I would like to store a dictionary on dynamo DB so: {"amount":"2.9","date":[]} and I know how to do it with Haskell. formattedInfo = avS .~ info $ attributeValue from Network.AWS.DynamoDB but when I try it with python: formatted_data = {'amount': str(data['amount']), 'date': data['date']} if 'Item' in item_response: table.update_item( Key={ 's3ObjectKey': s3_key }, UpdateExpression='SET kiData = :val1', ExpressionAttributeValues={ ':val1': formatted_data } ) else: table.put_item( Item={ 's3ObjectKey': s3_key, 'kiData': formatted_data } ) I get this { "amount" : { "S" : "2.9" }, "date" : { "L" : [ ] }} And it's not that bad, but it isn't as confortable as {"amount":"2.9","data":[]} does anybody know, how I could do it that way?
type: AnsweredQuestion

http://stackoverflow.com/q/48082043
type: UnansweredQuestion
has title: Calling C# code within Python3.6
tagged with: python
upvote count: 7
has comment: http://stackoverflow.com/comment/139548418
has comment: http://stackoverflow.com/comment/83159450
type: Question
has comment: http://stackoverflow.com/comment/83141028
tagged with: c#
tagged with: pythonnet
downvote count: 0
tagged with: .net
favorite count: 0
tagged with: python.net
answer count: 1
has body: with absolutely no knowledge of coding in C#, I wish to call a C# function within my python code. I know there's quite a lot of Q&amp;As around the same problem, but for some strange reason, i'm unable to import a simple c# class library from a sample python module. Here's below as to what i've done - C# Class Library setup I'm using the VS 2017 CE. I create a new project TestClassLibrary under the type of ClassLibrary(.NET Standard) The classes inside the project are as follows - MyClass.cs using System; namespace TestClassLibrary { public class MyClass { public string function() { return "Hello World!"; } } } This was built successfully, generating the .dll file under the \bin\Debug\netstandard2.0 dir as TestClassLibrary.dll Now, I switch over to python3.6 (running on a virtualenv, backed with pythonnet 2.3.0) main.py import sys sys.path.append(r"&lt;Ablsloute Path to \bin&gt;\Debug\netstandard2.0") import clr clr.AddReference(r"TestClassLibrary") from TestClassLibrary import MyClass When i Run python main.py, the code fails with the error - Traceback (most recent call last): File "main.py", line 6, in &lt;module&gt; from TestClassLibrary import MyClass ModuleNotFoundError: No module named 'TestClassLibrary' Should the code be - import sys sys.path.append(r"C:\Users\DELL\source\repos\TestClassLibrary\TestClassLibrary\bin\Debug\netstandard2.0") import clr clr.AddReference("TestClassLibrary.dll") from TestClassLibrary import MyClass I get - clr.AddReference("TestClassLibrary.dll") System.IO.FileNotFoundException: Unable to find assembly 'TestClassLibrary.dll'. at Python.Runtime.CLRModule.AddReference(String name) But when i ran the code below, the code runs as expected - import clr clr.AddReference(r"System.Windows.Forms") from System.Windows.Forms import MessageBox MessageBox.Show("Hello World!") I've no idea of what i might be missing :(
score: 7
has answer: http://stackoverflow.com/a/65604133

http://stackoverflow.com/a/48197679
type: AcceptedAnswer
has body: The problem The reason plt.gcf().autofmt_xdate() fails for subsequent updates of the axes content is that at the point when it is called, there are axes inside the figure, which are no subplots. This is the axes created by fig.add_axes, being the radiobutton axes. autofmt_xdate will not know what to do with this axes, i.e. it would not know if this is the axes for which to rotate the labels or not, hence it will decide not to do anything. In the matplotlib source code this looks like allsubplots = all(hasattr(ax, 'is_last_row') for ax in self.axes) if len(self.axes) == 1: # rotate labels else: if allsubplots: for ax in self.get_axes(): if ax.is_last_row(): #rotate labels else: #set labels invisible Because you have an axes, which is not a subplot, allsubplots == False and no rotation takes place. The solution The solution would be not to use autofmt_xdate(), but to do the work of rotating the ticklabels manually - which is really only 3 lines of code. Replace the line plt.gcf().autofmt_xdate() by for label in ax.get_xticklabels(): label.set_ha("right") label.set_rotation(30)
upvote count: 5
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48078540
score: 5
answers question: http://stackoverflow.com/q/48078540

http://stackoverflow.com/q/48119212
tagged with: deep-learning
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: one-hot-encoding
has comment: http://stackoverflow.com/comment/92348172
has title: How to one hot encode a variable with 3k categories without a MemoryError
tagged with: python
score: 2
has body: I am one-hot encoding a variable that has more than 3k categories and running into MemoryError. I have other variables that I'm one-hot encoding too, but they have fewer categories. The max categories I have for a variable that I can successfully one-hot encode is 935. I am using the following code: from sklearn import preprocessing from sklearn.preprocessing import OneHotEncoder def onehot(featurename): onehot_encoder = OneHotEncoder(sparse=False) onehot_encoded = onehot_encoder.fit_transform(df[featurename].reshape(-1, 1)) trn_onehot_encoded = onehot_encoded[msk] val_onehot_encoded = onehot_encoded[~msk] return trn_onehot_encoded, val_onehot_encoded trn_onehot_encoded_mt, val_onehot_encoded_mt = onehot('modality_type') trn_onehot_encoded_mr, val_onehot_encoded_mr = onehot('roleid') trn_onehot_encoded_sub, val_onehot_encoded_sub = onehot('subject') trn_onehot_encoded_quartile, val_onehot_encoded_quartile = onehot('quartile') trn_onehot_encoded_country, val_onehot_encoded_country = onehot('country_short') trn_onehot_encoded_region, val_onehot_encoded_region = onehot('region') trn_onehot_encoded_groupmemberornot, val_onehot_encoded_groupmemberornot = onehot('groupmemberornot') trn_onehot_encoded_highlight, val_onehot_encoded_highlight = onehot('highlight_bin_new') trn_onehot_encoded_note, val_onehot_encoded_note = onehot('note_bin_new') trn_onehot_encoded_eid, val_onehot_encoded_eid = onehot('new_eid') The final line of code where I encode the variable new_eid, is where I get the MemoryError or a dead kernel. In order to try and resolve this error, I set the field sparse to true in OneHotEncoder in the function onehot(). The code to fit with Sparse=True is as follows: &lt;All the code above with Sparse=True&gt; mt = Input(shape=(trn_onehot_encoded_mt.shape[1],)) mr = Input(shape=(trn_onehot_encoded_mr.shape[1],)) sub = Input(shape=(trn_onehot_encoded_sub.shape[1],)) gmon = Input(shape=(trn_onehot_encoded_groupmemberornot.shape[1],)) region = Input(shape=(trn_onehot_e…
answer count: 0
upvote count: 2
type: UnansweredQuestion
type: Question

http://stackoverflow.com/a/48039081
upvote count: 1
answers question: http://stackoverflow.com/q/48038883
type: Answer
downvote count: 0
score: 1
has body: "Can we always use a list type as a function parameter when a tuple is expected?" No. Aside from other reasons, the function may check the type. &gt;&gt;&gt; issubclass(ZeroDivisionError, (Exception,)) True &gt;&gt;&gt; issubclass(ZeroDivisionError, [Exception,]) Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; issubclass(ZeroDivisionError, [Exception,]) TypeError: issubclass() arg 2 must be a class or tuple of classes There are also a couple of places where Python syntax requires a tuple, as in except clauses. &gt;&gt;&gt; try: 1/0 except (Exception,) as e: print(e) division by zero &gt;&gt;&gt; try: 1/0 except [Exception] as e: print(e) Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 1, in &lt;module&gt; try: 1/0 ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 2, in &lt;module&gt; except [Exception] as e: print(e) TypeError: catching classes that do not inherit from BaseException is not allowed

http://stackoverflow.com/q/48069712
score: 1
has body: I would like to compile python regex inside another regex. for example find IP address like this below: This does not seem to work. &gt;&gt;&gt; import re &gt;&gt;&gt; p_ip = re.compile(r'[0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-5][0-5]') &gt;&gt;&gt; p_ip_full =re.compile( r'^(p_ip)\.{3}p_ip$') &gt;&gt;&gt; ip_str = "255.123.123.12" &gt;&gt;&gt; if (p_ip_full.match(ip_str)): ... print("match") ... &gt;&gt;&gt; p_ip_full re.compile('^(p_ip)\\.{3}p_ip$')
type: Question
has answer: http://stackoverflow.com/a/48069753
accepted answer: http://stackoverflow.com/a/48069753
has title: compiling pattern inside another pattern using python regex
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
tagged with: regex
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/48053742
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: If I understand your question correctly then you will achieve the fastest lookup time with a precomputed index. This index is the set of all items of list 1, where the following item is in list 2. # Build index, can be reused index = set(item1 for i, item1 in enumerate(list1[:-1]) if list1[i+1] in list2) def double_loop(words): return any(word in index for word in words.split()) Index lookups will be done in constant time, no matter how long list1 and list2 are. Index building will take longer when list1 and list2 get longer. Note that making list2 a set might speed up index building when list1 is large.
answers question: http://stackoverflow.com/q/48052487

http://stackoverflow.com/a/48169188
has comment: http://stackoverflow.com/comment/83321054
score: 1
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48168235
accepted answer of: http://stackoverflow.com/q/48168235
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/83517400
has comment: http://stackoverflow.com/comment/83322977
has body: I'm not familiarized with pyshp but this can be easily solved using ogr, which allows to work with vector data and makes part of the gdal library. from osgeo import ogr fn = r"file.shp" # The path of your shapefile ds = ogr.Open(fn, True) # True allows to edit the shapefile lyr = ds.GetLayer() print("Features before: {}".format(lyr.GetFeatureCount())) lyr.DeleteFeature(0) # Deletes the first feature in the Layer # Repack and recompute extent # This is not mandatory but it organizes the FID's (so they start at 0 again and not 1) # and recalculates the spatial extent. ds.ExecuteSQL('REPACK ' + lyr.GetName()) ds.ExecuteSQL('RECOMPUTE EXTENT ON ' + lyr.GetName()) print("Features after: {}".format(lyr.GetFeatureCount())) del ds

http://stackoverflow.com/q/48119142
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83214721
type: Question
score: 1
has body: I am trying to create a digital filter in Python to filter a wave file. It is telling me that i'm not passing an argument to the filter function, but I am as part of the loop at the bottom. TypeError: filter() missing 1 required positional argument: 'v' Can anyone assist please? import scipy.io.wavfile as wavfile import numpy as np #Load the data r, x = wavfile.read('M80_and_speech.wav') #create output array y = np.zeros(len(x)) #filter coefficients a1 = -1.96977856 a2 = 0.97022848 b0 = 0.98500176 b1 = -1.97000352 b2 = 0.98500176 #create filter class class IIR2Filter: def __init__(self, a1, a2, b0, b1, b2): self.input_acc = 0 self.outut_acc = 0 self.buffer1 = 0 self.buffer2 = 0 def filter(self, v): #accumulator for the IIR part self.input_acc = v self.input_acc = self.input_acc - (a1*self.buffer1) self.input_acc = self.input_acc - (a2*self.buffer2) #accumulator for the FIR part self.output_acc = self.input_acc * b0 self.output_acc = self.output_acc + (b1*self.buffer1) self.output_acc = self.output_acc + (b2*self.buffer2) self.buffer2 = self.buffer1 self.buffer1 = self.input_acc return self.output_acc for i in range (len(x)): y[i] = IIR2Filter.filter(x[i])
has answer: http://stackoverflow.com/a/48119235
has comment: http://stackoverflow.com/comment/83214792
accepted answer: http://stackoverflow.com/a/48119235
has title: TypeError: filter() missing 1 required positional argument: 'v'
tagged with: signal-processing
upvote count: 2
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83217148
has comment: http://stackoverflow.com/comment/83214726

http://stackoverflow.com/comment/83099386
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48063220
score: 0
has text: Have you tried printing the `result` variable to standard output, so you can verify that `PyPDF2` actually finds something when you call `extractText()`

http://stackoverflow.com/q/48163061
linked to: http://stackoverflow.com/q/36132350
has comment: http://stackoverflow.com/comment/83305364
has answer: http://stackoverflow.com/a/48163292
score: 1
type: Question
has title: How to install python wheel without using pip?
duplicate of: http://stackoverflow.com/q/36132350
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83305391
type: UnansweredQuestion
tagged with: package
tagged with: python-wheel
has body: I have downloaded .whl and trying to install it. Can you tell me the possible ways of installing wheel without using pip. For tar.gz files, I executed python setup.py install and it installed my package. How the same can be done for wheel when there is no setup.py file in it?
tagged with: python
has comment: http://stackoverflow.com/comment/83305335

http://stackoverflow.com/a/48018463
downvote count: 0
score: 1
has body: As per this document: You can add non-pip installable packages as: setup( ... dependency_links=['http://github.com/user/repo/tarball/master#egg=package-1.0'] ... )
answers question: http://stackoverflow.com/q/48017790
upvote count: 1
type: Answer

http://stackoverflow.com/q/48015191
has comment: http://stackoverflow.com/comment/82999706
tagged with: extrapolation
accepted answer: http://stackoverflow.com/a/48015408
possible better answer: http://stackoverflow.com/a/48015790
favorite count: 0
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/82999886
has body: Ok so I started with Python a few days ago. I mainly use it for DataScience because I am an undergraduate chemistry student. Well, now I got a small problem on my hands, as I have to extrapolate a function. I know how to make simple diagrams and graphs, so please try to explain it as easy to me as possible. I start off with: from matplotlib import pyplot as plt from matplotlib import style style.use('classic') x = [0.632455532, 0.178885438, 0.050596443, 0.014310835, 0.004047715] y = [114.75, 127.5, 139.0625, 147.9492188, 153.8085938] x2 = [0.707, 0.2, 0.057, 0.016, 0.00453] y2 = [2.086, 7.525, 26.59375,87.03125, 375.9765625] so with these values I have to work out a way to extrapolate in order to get a y(or y2) value when my x=0. I know how to do this mathematically, but I would like to know if python can do this and how do I execute it in Python. Is there a simple way? Can you give me maybe an example with my given values? Thank you
score: 2
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82999867
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48015408
answer count: 2
has comment: http://stackoverflow.com/comment/82999575
has comment: http://stackoverflow.com/comment/83000182
has title: How to extrapolate a function based on x,y values?
downvote count: 0
has answer: http://stackoverflow.com/a/48015790
has comment: http://stackoverflow.com/comment/82999550

http://stackoverflow.com/a/48145956
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48145182
has comment: http://stackoverflow.com/comment/83272236
has comment: http://stackoverflow.com/comment/83272452
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48145182
type: Answer
score: 1
has body: t1 is 2D list with many text elements and you can do the same with something like t1 = [] for j in range(myArray.shape[1]): sublist = [] for i in range(myArray.shape[2]): txt = self.ax.text(i+.2,n-.6-j,myArray[0][j][i]) sublist.append(txt) t1.append(sublist) So you can do something similar with set_text() to change text for j in range(myArray.shape[1]): for i in range(myArray.shape[2]): t1[i][j].set_text(myArray[0][j][i]) or using enumerate() for j, row in enumerate(t1): for i, cell in enumerate(row): cell.set_text(myArray[0][j][i]) or using zip() for row, arr_row in zi(t1, myArray[0]): for cell, arr_cell in zip(row, arr_row): cell.set_text(arr_cell) BTW: all examples are not tested so they may need some changes. Using t1 = self.ax.text(10,10, myArray[0][0][0]) you replaced list with single element so you loose access to all elements.

http://stackoverflow.com/q/48087638
has comment: http://stackoverflow.com/comment/83150201
type: AnsweredQuestion
has body: I am new to kivy and using some tutorials but i only get black screen while on the videos developpers get their widget on the screen. i've tried multiple solutions but i dont really understand what the problem is. I am trying to build a login screen here is the code i wrote : from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.boxlayout import BoxLayout from kivy.uix.textinput import TextInput class LoginScreen(BoxLayout): def __int__(self, **kwargs): super(LoginScreen,self).__int__(**kwargs) sm=ScreenManager Screen=Screen(name="screen") layout=BoxLayout(orientation='vertical') self.Username = TextInput(multiline=False) self.Password = TextInput(multiline=False, password=True) layout.add_widget(Label(text="username")) layout.add_widget(self.Username) layout.add_widget(Label(text="password")) layout.add_widget(self.Password) Screen.add_widget(layout) sm.add_widget(Screen) return sm class simplekivy(App): def build(self): return LoginScreen() if __name__ == "__main__": simplekivy().run() Thank you for your help !
has title: Blank screen with kivy
type: Question
answer count: 1
score: 0
tagged with: kivy
has answer: http://stackoverflow.com/a/48087765
accepted answer: http://stackoverflow.com/a/48087765
has comment: http://stackoverflow.com/comment/83150241
tagged with: python

http://stackoverflow.com/comment/83094452
comment on: http://stackoverflow.com/a/48060744
score: 0
type: Comment
has text: else change url to url(r'^albums/details/(?P<album_id>[0-9]+)/$',views.album,name='details') i think this is better
type: AnswerComment

http://stackoverflow.com/comment/83124778
has text: well which character is it if you want to type it, this error is odd.
comment on: http://stackoverflow.com/a/48075471
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48063788
tagged with: stream
has title: Streaming a binary file to Google Storage using Tornado
type: Question
has answer: http://stackoverflow.com/a/48070476
has comment: http://stackoverflow.com/comment/83101823
upvote count: 5
tagged with: google-cloud-storage
tagged with: tornado
has body: I'm trying to stream a binary file from a client request to Google Cloud Storage through my server. I'm using the Tornado framework to stream the data from the request to the server and Google Cloud Storage API for streaming the file to Google -upload_from_file method. I'm new to Tornado and I'm using the @stream_request_body decorator so I can get the data from the request in chunks and upload each chunk to Google. I've tried to open a file-like object to which I can write each chunk while uploading the 'file' itself to Google. The problem is that I can't upload the 'file' to Google before I start writing chunks to it. Any assistance would be much appreciated.
score: 5
answer count: 1
downvote count: 0
tagged with: file-upload
favorite count: 0
accepted answer: http://stackoverflow.com/a/48070476
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83393566
has text: what does `os.getcwd()` print?
comment on: http://stackoverflow.com/q/48097888
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83297117
score: 1
type: Comment
type: QuestionComment
has text: So you are looking for the *intersection* (only those integers that appear in *all* the sets)? Or are you looking for the *union* (all the unique integers from all the sets combined)?
comment on: http://stackoverflow.com/q/48158745

http://stackoverflow.com/a/48046629
answers question: http://stackoverflow.com/q/48046565
has comment: http://stackoverflow.com/comment/83064692
downvote count: 0
has comment: http://stackoverflow.com/comment/83064664
upvote count: 2
type: Answer
score: 2
has body: Code commented for explanation reasons, hth: cardsInHand = [23,24,25,23,27,4] # all your cards cardsInOrder = [] # empty list, to be filled with in order cards lastCard = None for card in cardsInHand: # loop all cards in hand if not lastCard or lastCard &lt; card: # if none taken yet or smaller cardsInOrder.append(card) # append to result lastCard = card # remember for comparison to next card else: # not in order break # stop collecting more cards into list print(cardsInOrder) # print all Output: [23, 24, 25] If you need the unordered part of your hand as well, you can get that by: unorderedCards = cardsInHand[len(cardsInOrder):] # list-comp based length of ordered cards

http://stackoverflow.com/comment/83259162
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48140587
score: 0
has text: Indexing and slicing explained here, on SO: https://stackoverflow.com/a/509295/8881141

http://stackoverflow.com/a/48118589
type: Answer
upvote count: 1
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48118464
has body: Get separately &lt;dt&gt; (as all_dt) and separately &lt;dd&gt; (as all_dd) and use zip(all_dt, all_dd) to create pairs. import requests from bs4 import BeautifulSoup res = requests.get("https://www.drugbank.ca/drugs/DB04789") soup = BeautifulSoup(res.text ,"lxml") all_dt = soup.select("dl &gt; dt") all_dd = soup.select("dl &gt; dd") for dt, dd in zip(all_dt, all_dd): print(dt.text, ":", dd.text) You can also use nextSibling to get element after dt all_dt = soup.select("dl &gt; dt") for dt in all_dt: dd = dt.nextSibling print(dt.text, ":", dd.text) My full code from answer to question Deep parse with beautifulsoup which was 2 hours ago. import requests from bs4 import BeautifulSoup def get_details(url): print('details:', url) # get subpage r = requests.get(url) soup = BeautifulSoup(r.text ,"lxml") # get data on subpabe dts = soup.findAll('dt') dds = soup.findAll('dd') # display details for dt, dd in zip(dts, dds): print(dt.text) print(dd.text) print('---') print('---------------------------') def drug_data(): url = 'https://www.drugbank.ca/drugs/' while url: print(url) r = requests.get(url) soup = BeautifulSoup(r.text ,"lxml") # get links to subpages links = soup.select('strong a') for link in links: # exeecute function to get subpage get_details('https://www.drugbank.ca' + link['href']) # next page url url = soup.findAll('a', {'class': 'page-link', 'rel': 'next'}) print(url) if url: url = 'https://www.drugbank.ca' + url[0].get('href') else: break drug_data()

http://stackoverflow.com/comment/83074296
type: Comment
comment on: http://stackoverflow.com/q/48049396
score: 0
type: QuestionComment
has text: What about using [SQL sequences](https://www.postgresql.org/docs/9.6/static/sql-createsequence.html)? Using application logic for something a database perfectly solves feels weired. If you really need to achieve one pk sequence per project you might create a sql sequence for each of your projects in the database. Read this question on how to use it: https://stackoverflow.com/questions/3379891/django-accessing-postgresql-sequence

http://stackoverflow.com/comment/83244031
has text: Thanks @Aiven. Do you know if there is a newer jar that I can use? The latest I can find is libtensorflow-1.5.0-rc0.jar. Or is there any other way I can load my model in Java? I would like to get it to work in Java :)
comment on: http://stackoverflow.com/q/48132420
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48147196
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48147000
answers question: http://stackoverflow.com/q/48147000
score: 1
has comment: http://stackoverflow.com/comment/83272695
type: AcceptedAnswer
downvote count: 0
has body: Since you know that there are pairs of A-B files, you could just iterate on A files and create B filenames: import glob A_files = glob.iglob('*-A.txt') for A_file in A_files: B_file = A_file.partition("-")[0]+"-B.txt" A_file.partition("-")[0] extracts the digit before the dash so you can generate the other file. You could even make sure that the B file isn't missing (well, you can't do that for A-files, obviously)
type: Answer

http://stackoverflow.com/q/48167742
upvote count: 1
score: 1
has body: I have the same beginning in two Python programs: #!/usr/bin/env python3 # -*- coding: utf-8 -*- from lxml import etree, html from lxml.builder import E import re import sys import locale #locale.setlocale(locale.LC_ALL, 'es_ES.UTF-8') locale.setlocale(locale.LC_ALL, '') In one case, everything works correctly, and in the other, I have uncomment the first and comment the second call to setlocale to avoid the following error: Traceback (most recent call last): File "./html2epub.py", line 11, in &lt;module&gt; locale.setlocale(locale.LC_ALL, '') File "/usr/lib/python3.5/locale.py", line 594, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting And, of course, nothing works when LC_ALL is not ''
type: Question
tagged with: locale
downvote count: 0
favorite count: 0
tagged with: lxml
tagged with: python
answer count: 0
type: UnansweredQuestion
has title: Strange behaviour of locale.setlocale in Python3

http://stackoverflow.com/a/48045628
has comment: http://stackoverflow.com/comment/83602582
has comment: http://stackoverflow.com/comment/83109576
has comment: http://stackoverflow.com/comment/83414613
has comment: http://stackoverflow.com/comment/83644726
has comment: http://stackoverflow.com/comment/83110094
score: 0
has comment: http://stackoverflow.com/comment/83110363
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83109541
answers question: http://stackoverflow.com/q/48044680
type: Answer
has comment: http://stackoverflow.com/comment/83415184
accepted answer of: http://stackoverflow.com/q/48044680
has comment: http://stackoverflow.com/comment/83078370
has comment: http://stackoverflow.com/comment/83078441
has body: The OP want to create a multidict as in http://www.gurobi.com/documentation/7.5/examples/netflow_py.html Goal is to generate a dictionary object that can be taken as the input of multidict, an api in the gurobi software. The needed input has a shape like { (0, 0): 0, (0, 1): 80, (0, 2): 11, (1, 0): 15, (1, 1): 0, (1, 2): 120 (2, 0): 103, (2, 1): 3, (2, 2): 0 } Method 1: for loop and dictionary from gurobi import multidict multidict_input = {} for i in range(N): for j in range(N): multidict_input[i,j] = random.randint(1,101) if i != j else 0 arcs, capacity = multidict(multidict_input) # feed it into multidict Method 2: (dictionary comprehension) multidict_input = dict() multidict_input = {(a,b): random.randint(1,101) if a != b else 0 for a in range(N) for b in range(N)} arcs, capacities = multidict(multidict_input)
has comment: http://stackoverflow.com/comment/83110454
has comment: http://stackoverflow.com/comment/83078461
has comment: http://stackoverflow.com/comment/83225001
has comment: http://stackoverflow.com/comment/83644619

http://stackoverflow.com/q/48137828
tagged with: anaconda
linked to: http://stackoverflow.com/q/35991403
has comment: http://stackoverflow.com/comment/83252974
score: 0
has body: I have been trying to install asyncmc module via conda and I keep on getting error below. I am not able to figure out the exact issue. pip install asyncmc Collecting asyncmc Using cached asyncmc-0.6.6.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-build-8yudAS/asyncmc/setup.py", line 18, in &lt;module&gt; long_description='\n\n'.join((read('README.md'), read('CHANGES.md'))), File "/tmp/pip-build-8yudAS/asyncmc/setup.py", line 8, in read return open(os.path.join(os.path.dirname(__file__), f)).read().strip() IOError: [Errno 2] No such file or directory: '/tmp/pip-build-8yudAS/asyncmc/CHANGES.md' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-8yudAS/asyncmc/
has title: Cannot install asyncmc [Version Issue]
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83253027
has comment: http://stackoverflow.com/comment/83253631
answer count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/83253008
type: Question

http://stackoverflow.com/comment/83247946
type: Comment
has text: Have u given chmod 777 to your project
comment on: http://stackoverflow.com/a/48135172
score: 0
type: AnswerComment

bash
tags question: http://stackoverflow.com/q/48148619
tags question: http://stackoverflow.com/q/48135256
tags question: http://stackoverflow.com/q/48069439
tags question: http://stackoverflow.com/q/48034370
tags question: http://stackoverflow.com/q/48151137
tags question: http://stackoverflow.com/q/48024209
tags question: http://stackoverflow.com/q/48124763
tags question: http://stackoverflow.com/q/48066114
tags question: http://stackoverflow.com/q/48055299
tags question: http://stackoverflow.com/q/48038293
tags question: http://stackoverflow.com/q/48108473
tags question: http://stackoverflow.com/q/48050639
type: Tag
tags question: http://stackoverflow.com/q/48089135
tags question: http://stackoverflow.com/q/48140941
tags question: http://stackoverflow.com/q/48119355
tags question: http://stackoverflow.com/q/48157247
tags question: http://stackoverflow.com/q/48085844
tag name: bash
tags question: http://stackoverflow.com/q/48064755

http://stackoverflow.com/comment/83134885
type: Comment
type: QuestionComment
score: 0
has text: Python without pandas for handling tables is a pain in the ass. You should know some libraries like collections and itertools and be familiar with comprehensions and string formatting to write readable code. Trust me, if you aim to use Python for manipulating table data. Learn pandas!
comment on: http://stackoverflow.com/q/48079783

http://stackoverflow.com/a/48494431
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48088516
has body: Sorry I'm late to answer this, but I think the accepted answer is not solving the complete problem, and furthermore solving it incorrectly. Note how in the local minimization, solving near nominal price doesn't give the best solution. Let's first build a hotel class: """ This file is 'hotel.py' """ import math class hotel(object): def __init__(self, rooms, price_ave, price_elastic): self.rooms = rooms self.price_ave = price_ave self.price_elastic = price_elastic def profit(self, P): # assert len(P) == len(self.rooms) return sum(j * self._reserved(P, i) for i,j in enumerate(P)) def remaining(self, P): # &gt;= 0 C = self.rooms # assert len(P) == C return [C[i] - self._reserved(P, i) for i,j in enumerate(P)] def _reserved(self, P, day): max_days = len(self.rooms) As = range(0, day) return sum(self._allocated(P, a, L) for a in As for L in range(day-a+1, max_days+1)) def _allocated(self, P, a, L): P_nom = self.price_ave e = self.price_elastic return math.ceil(self._demand(a, L)*(sum(P[a:a+L])/(P_nom*L))**e) def _demand(self, a,L): #XXX: fictional non-constant demand function return abs(1-a)/L + 2*(a**2)/L**2 Here's one way to solve it using mystic: """ This file is 'local.py' """ n_days = 7 n_rooms = 50 P_nom = 85 P_bounds = 0,None P_elastic = 2 import hotel h = hotel.hotel([n_rooms]*n_days, P_nom, P_elastic) def objective(price, hotel): return -hotel.profit(price) def constraint(price, hotel): # &lt;= 0 return -min(hotel.remaining(price)) bounds = [P_bounds]*n_days guess = [P_nom]*n_days import mystic as my @my.penalty.quadratic_inequality(constraint, kwds=dict(hotel=h)) def penalty(x): return 0.0 # using a local optimizer, starting from the nominal price solver = my.solvers.fmin mon = my.monitors.VerboseMonitor(100) kwds = dict(disp=True, full_output=True, itermon=mon, args=(h,), xtol=1e-8, ftol=1e-8, maxfun=10000, maxiter=2000) result = solver(objective, guess, bounds=bounds, penalty=penalty, **kwds) print([round(i,2) for i in result[0]]) Results: &gt;$ python local.p…
accepted answer of: http://stackoverflow.com/q/48088516

http://stackoverflow.com/a/48040615
accepted answer of: http://stackoverflow.com/q/48040412
has comment: http://stackoverflow.com/comment/83118357
type: Answer
answers question: http://stackoverflow.com/q/48040412
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83118602
has body: Just use the find_elements_by_css_selector() (note the "s") to locate multiple elements matching a locator - CSS selector in your case: results = driver.find_elements_by_css_selector('#results .page_block_sub_header_count') results would be a list of WebElement instances, you can iterate over it and get, say, a text: for item in results: print(item.text)
has comment: http://stackoverflow.com/comment/83064531
type: AcceptedAnswer
upvote count: 3

http://stackoverflow.com/q/48070278
type: AnsweredQuestion
upvote count: 0
favorite count: 0
score: -1
accepted answer: http://stackoverflow.com/a/48107885
type: Question
has body: Using ctypes, I create an array in Python to pass to a ctypes.WinDLL: arrA = (ctypes.c_float * len(varA))(*varA) Then I pass a pointer to the array into the DLL: retvar = SimpleTest(ctypes.byref(pvarr),ctypes.byref(pvarr2)) Where the first element of pvarr is a pointer to the array arrA. But when I try to write to values to the array arrA (using the pointer that was passed), I get "invalid access to memory location." So my question is: how can I now use the pointer to a ctypes.c_float array created in Python and passed to a DLL? Is that not possible? After working on this for awhile, I have refined the problem. The array shown above is immutable; to pass a mutable array, we do this: OutputArrayType = ctypes.c_float * 1000 arrNew = OutputArrayType() The ctypes array type is a class, so to use it we must create a class instance (arrayNew). But when I pass its pointer by reference: retvar = SimpleTest(ctypes.byref(PVarrNew),ctypes.byref(arrNew)) the pointer value is a different number from id(arrayNew). Even so, the DLL still cannot access any values in either pointer, as I get "invalid access to memory." So my question now is: why does the pointer passed by ctypes.byref(arrNew) differ from id(arrNew). Mark, thanks for your reply. Here is the concise summary: The first array is not mutable in place, it creates a new object with each assignment; I confirmed that by checking its id() before and after an assignment. However, the second array, instantiated as a class, is mutable in place so that's why I use it. So I create the array: OutputArrayType = ctypes.c_int64 * 1000 arrNew = OutputArrayType() and call the DLL: retvar = SimpleTest(ctypes.byref(PVarrNew),ctypes.byref(arrNew)) In 64-bit assembler, the second parameter (the pointer to arrNew) is passed in rdx. So in NASM, I can write to this array in two different ways, but both return "invalid access to memory location." mov rdi,rdx mov rax,1534 mov [rdi+8],rax push qword [rax] pop qword [rdx+32] If I reverse the order…
tagged with: python
has comment: http://stackoverflow.com/comment/83179989
has title: Python ctypes: how to use pointer passed to DLL?
has comment: http://stackoverflow.com/comment/83190818
has comment: http://stackoverflow.com/comment/83150264
answer count: 1
downvote count: 1
tagged with: ctypes
has answer: http://stackoverflow.com/a/48107885

http://stackoverflow.com/a/48129103
type: Answer
answers question: http://stackoverflow.com/q/48128790
has comment: http://stackoverflow.com/comment/83236140
has comment: http://stackoverflow.com/comment/83234961
has comment: http://stackoverflow.com/comment/83236885
score: 0
has body: I should be able to share all this together in one directory, so with a virtual environment Virtual environments are not portable (they must reside in the same directory on a computer where exist global Python), hence you cannot share a virtual environment. My question to you all is: how can I make the paths of a Python virtual env relative. No, and you certainly don't need to do it. A second question I have is: is it possible to just activate the virtual env without changing cmd prompts Yes, it's regulated in bin/activate script which you can edit to your taste. and things? What "things"? Activating virtual environment means changing PATH, PYTHONPATH and so on, you certainly cannot use virtual environment without changing these and other things. That batch file failed If you want us to help you should show us the essential parts of the batch and in what way it failed. May be you need a different solution like a Docker image. Docker can be installed on Windows though it must be installed on the target computers. There are also simpler solutions: py2exe, PyInstaller, cx_Freeze. They "compile" python scripts to .exe and accompany that .exe with Python interpreter (in a .dll) and library (in a .zip file). But if your program needs more DLLs you have to copy them to the target computer. You can also take a look at RVirtualEnv. It allows to create relocatable virtual environments. I don't know if such envs can be copied to a different host, though.
has comment: http://stackoverflow.com/comment/83235622

gmail
type: Tag
tags question: http://stackoverflow.com/q/48090313
tag name: gmail

http://stackoverflow.com/comment/83018554
comment on: http://stackoverflow.com/a/48024392
has text: Omg im such an idiot for using () as index instead of []. Thanks everyone above for helping me.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83298907
type: Comment
has text: `elif "bloody hand" in inventory or "soapy hand" in inventory or "hand" in inventory`
type: QuestionComment
comment on: http://stackoverflow.com/q/48159666
score: 0

http://stackoverflow.com/q/48064452
answer count: 1
downvote count: 1
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48064506
tagged with: python
duplicate of: http://stackoverflow.com/q/3906137
score: -1
type: Question
has body: i want to read in a 2 dimensional Gridworld and transform it into a 2D list of strings. I used the open("filename") function to read in the file. My Code works but as soon as I print out the gridfile with the .read() function it does not work anymore. The Output is the Gridworld and empty lists ([''] and [['']]). If I remove the print statement it works perfectly fine. Can anyone explain to me why this is the case? It seems like python has somehow "used" the file when calling the .read() function and is not able to call it twice... grid_file = open("3by4.grid") def transform_to_lists(grid_file): ***print(grid_file.read())*** onedim_list = grid_file.read().split('\n') twodim_list = [i.split(' ') for i in onedim_list] return twodim_list print (transform_to_lists(grid_file))
favorite count: 0
linked to: http://stackoverflow.com/q/3906137
has comment: http://stackoverflow.com/comment/83102031
has title: calling read() Function in Python twice

http://stackoverflow.com/comment/83099102
has text: Thats actually a really well written question. You dont get many like that haha
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48063176

http://stackoverflow.com/q/48075995
downvote count: 2
has comment: http://stackoverflow.com/comment/83128803
type: Question
has body: I would like to pull intraday data of any stocj in google finance just by asking for its ISIN number (not the google symbol). Is there is a way to do so using the python API googlefinance ? Thanks
tagged with: google-finance-api
favorite count: 0
tagged with: google-finance
type: UnansweredQuestion
tagged with: python
score: 11
upvote count: 13
answer count: 0
has title: Pulling google finance data with ISIN as an identifier

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/48159567
tags question: http://stackoverflow.com/q/48085215
tags question: http://stackoverflow.com/q/48030864
tags question: http://stackoverflow.com/q/48145992
tags question: http://stackoverflow.com/q/48116337
tags question: http://stackoverflow.com/q/48061146
tags question: http://stackoverflow.com/q/48078567
tags question: http://stackoverflow.com/q/48050769
tags question: http://stackoverflow.com/q/48160420
tags question: http://stackoverflow.com/q/48068001
tags question: http://stackoverflow.com/q/48078177
tags question: http://stackoverflow.com/q/48168885
tags question: http://stackoverflow.com/q/48130067
tags question: http://stackoverflow.com/q/48087665
tags question: http://stackoverflow.com/q/48143870
tags question: http://stackoverflow.com/q/48105246
tags question: http://stackoverflow.com/q/48048577
tags question: http://stackoverflow.com/q/48162727
tags question: http://stackoverflow.com/q/48128378
tags question: http://stackoverflow.com/q/48064834
tags question: http://stackoverflow.com/q/48157921
tags question: http://stackoverflow.com/q/48051319
tags question: http://stackoverflow.com/q/48155038
tags question: http://stackoverflow.com/q/48126969
tags question: http://stackoverflow.com/q/48127096
tags question: http://stackoverflow.com/q/48030773
tags question: http://stackoverflow.com/q/48015536
tags question: http://stackoverflow.com/q/48143929
tags question: http://stackoverflow.com/q/48023567
tags question: http://stackoverflow.com/q/48050595
tags question: http://stackoverflow.com/q/48042137
tags question: http://stackoverflow.com/q/48120216
tags question: http://stackoverflow.com/q/48122080
type: Tag
tags question: http://stackoverflow.com/q/48064451
tags question: http://stackoverflow.com/q/48172795
tags question: http://stackoverflow.com/q/48118602
tags question: http://stackoverflow.com/q/48020072
tags question: http://stackoverflow.com/q/48048330
tags question: http://stackoverflow.com/q/48061068
tags question: http://stackoverflow.com/q/48151540
tags question: http://stackoverflow.com/q/48140281
tags question: http://stackoverflow.com/q/48051149
tags question: http://stackoverflow.com/q/48143199
tags question: http://stackoverflow.com/q/48117272
tags question: http://stackoverflow.com/q/48171159
tags question: http://stackoverflow.com/q/48072001
tags question: http://stackoverflow.com/q/48036365
tags question: http://stackoverflow.com/q/48115308
tags question: http://stackoverflow.com/q/48160071
tags question: http://stackoverflow.com/q/48140858
tags question: http://stackoverflow.com/q/48075495
tags question: http://stackoverflow.com/q/48032708
tags question: http://stackoverflow.com/q/48017878
tags question: http://stackoverflow.com/q/48036929
tag name: json
tags question: http://stackoverflow.com/q/48155126
tags question: http://stackoverflow.com/q/48027076
tags question: http://stackoverflow.com/q/48117118
tags question: http://stackoverflow.com/q/48102595
tags question: http://stackoverflow.com/q/48094940
tags question: http://stackoverflow.com/q/48037575
tags question: http://stackoverflow.com/q/48071828
tags question: http://stackoverflow.com/q/48110167
tags question: http://stackoverflow.com/q/48131440
tags question: http://stackoverflow.com/q/48065751
tags question: http://stackoverflow.com/q/48131019
tags question: http://stackoverflow.com/q/48160623
tags question: http://stackoverflow.com/q/48132333
tags question: http://stackoverflow.com/q/48104763
tags question: http://stackoverflow.com/q/48023860
tags question: http://stackoverflow.com/q/48157699
tags question: http://stackoverflow.com/q/48039373
tags question: http://stackoverflow.com/q/48139398
tags question: http://stackoverflow.com/q/48023290
tags question: http://stackoverflow.com/q/48162077
tags question: http://stackoverflow.com/q/48122916
tags question: http://stackoverflow.com/q/48046500
tags question: http://stackoverflow.com/q/48015136
tags question: http://stackoverflow.com/q/48019524

http://stackoverflow.com/comment/83097542
has text: `isin` takes a list of scalars. You've passed it a nested list. Get rid of the `[..]`.
comment on: http://stackoverflow.com/q/48062375
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83249276
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48135999
has text: I'd add an outer loop from 0 to 3 and would use that loop. Also I would create lists of variables, not variables named as `a1` ... at this point this question is more for codereview.
score: 0

http://stackoverflow.com/a/52782331
answers question: http://stackoverflow.com/q/48082439
has body: Python is not like C or C++. Python inherently has high overhead. You can not store data in memory, but instead, get a fully-fledged object that is stored in memory. When you try things like 1) struct.pack('&gt;b', 10) 2) bytes(10), bytes([10]) 3) 0x10 4) bytearray(10) 5) b'10' These are not storing bytes directly to memory, they are creating python objects to store byte data in. Thats why sys.getsizeof(data) != 1. That being said there is a way around this to answer the underlying question. socket.send() requires a buffer or string and python has byte-strings. so socket.send('\x0a') would send exactly one byte. You could also return a byte string from a function. def return_byte_string(): return b'\x0a' Then this could be passed into socket.send(return_byte_string()) to send a single byte over a TCP connection.
upvote count: 3
type: AcceptedAnswer
type: Answer
score: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48082439

http://stackoverflow.com/a/48087121
has comment: http://stackoverflow.com/comment/83149218
upvote count: 4
answers question: http://stackoverflow.com/q/48087117
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/48087117
type: Answer
has body: You have probably overwritten str with a variable named str, presumably another string.

http://stackoverflow.com/q/48128586
answer count: 1
score: -1
tagged with: data-structures
has comment: http://stackoverflow.com/comment/83233867
has comment: http://stackoverflow.com/comment/83234074
has comment: http://stackoverflow.com/comment/83233898
has comment: http://stackoverflow.com/comment/83233844
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: How do variables retain their logic in IF statements throughout all operations in OOP?
downvote count: 1
has comment: http://stackoverflow.com/comment/83233841
tagged with: list
tagged with: oop
has answer: http://stackoverflow.com/a/48135268
type: Question
has comment: http://stackoverflow.com/comment/83233903
has body: I am working with the following script that involves two classes that create a list. It basically works like this. You push a Node instance onto the self.begin attribute (in the List class through the IF-statement condition and it sets self.end to self.begin). During the next push you only go through the ELSE statement and work the self.end attribute (so not touching upon self.begin). However, through the debugging prints I still see the self.begin attribute to get Nodes attached to it. So two things confuse me: 1) Does the IF statement logic keeps retained even in subsequent usages of the push method (wherein you only get to the ELSE statement -- e.g. the logic of self.end = self.begin)? 2) If the logic keeps retained, why does setting self.end to self.begin let you to arrive at a result where the self.begin attribute gets extended with newer nodes? Hope someone has an answer on this. Below is the script. class Node(object): def __init__(self, value, nxt): self.value = value self.next = nxt class List(object): def __init__(self): self.begin = None self.end = None def push(self, obj): node = Node(obj, None) if self.begin == None: self.begin = node self.end = self.begin else: self.end.next = node self.end = node def push(): list = List() list.push("1") list.push("2") list.push("3") list.push("4") push()
has comment: http://stackoverflow.com/comment/83234645
upvote count: 0

http://stackoverflow.com/comment/83142659
comment on: http://stackoverflow.com/q/48083981
has text: This schema violates the [Zero, One or Infinity Rule](http://en.wikipedia.org/wiki/Zero_one_infinity_rule) of [database normalization](http://en.wikipedia.org/wiki/Database_normalization). A secondary table with a one-to-many relationship for storing the IP addresses would give you N possible addresses, not this schema arbitrarily limited to four. Those column names are also a total wreck, some have spaces, some don't, there's no consistency at all. Keep your schema as clean as possible, it's important. Spaces in column names tend to be extremely annoying.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48079903
has comment: http://stackoverflow.com/comment/83133956
type: Question
has title: Is there a simple way to install the same Python libraries that I have in one environment to a new Python environment?
has body: I want to duplicate my Python development station. I need to be able to install, with pip, the same libraries that were installed on the original station. Is there a simple way to that instead of going into the pip list and installing all the libraries one by one ? The Main purpose is to be able to duplicate the same environment that I have in one station to another station with minimum overhead. I won't like to be required to track the existence or absence of the libraries by myself
linked to: http://stackoverflow.com/q/13537901
has comment: http://stackoverflow.com/comment/83133728
has comment: http://stackoverflow.com/comment/83134678
answer count: 1
duplicate of: http://stackoverflow.com/q/6600878
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48080052
type: UnansweredQuestion
tagged with: pip
tagged with: python
score: 2
duplicate of: http://stackoverflow.com/q/13537901
upvote count: 3
linked to: http://stackoverflow.com/q/6600878
has comment: http://stackoverflow.com/comment/83133890
downvote count: 1
has comment: http://stackoverflow.com/comment/83133918

http://stackoverflow.com/a/48109598
accepted answer of: http://stackoverflow.com/q/48109520
type: Answer
has comment: http://stackoverflow.com/comment/83195803
has body: You can use custom function with compare shifted groups with replace NaNs by backward filling by bfill, last convert boolean mask to integer by astype: df['flag'] = df.groupby('id')['company'].apply(lambda x :x.ne(x.shift().bfill())).astype(int) print (df) id company flag 0 1 A 0 1 1 A 0 2 1 B 1 3 2 C 0 4 2 C 0 5 2 C 0 6 3 D 0 7 3 E 1 8 3 F 1 And thank you, @pansen for better solution: df['flag'] = df.groupby("id")["company"].shift().bfill().ne(df['company']).astype(int) print (df) id company flag 0 1 A 0 1 1 A 0 2 1 B 1 3 2 C 0 4 2 C 0 5 2 C 0 6 3 D 0 7 3 E 1 8 3 F 1
upvote count: 5
answers question: http://stackoverflow.com/q/48109520
score: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48132256
accepted answer of: http://stackoverflow.com/q/48132195
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83241790
answers question: http://stackoverflow.com/q/48132195
upvote count: 1
type: AcceptedAnswer
has body: According to the following Beautiful Soup Documentation The elements that are returned by soup.find_all are not strings. They are objects. Except each object has their respective __str__ methods overridden for human readability. So you are not passing strings into search. But in fact customized beautiful soup objects. for element in lista: z = re.search(r"\((.......\))",element) if z: print(z.groups()) To fix, make sure to convert element into a string before calling the respective method. for element in lista: z = re.search(r"\((.......\))", str(element)) if z: print(z.groups())
type: Answer

http://stackoverflow.com/comment/83283948
score: 0
type: QuestionComment
has text: this `excell` issue, so need `byte` size `binascii.hexlify(string)[:32767*2]` because : excell limit `32768, ASCII, 0 to 255,single Byte`
type: Comment
comment on: http://stackoverflow.com/q/48151844

http://stackoverflow.com/q/48015136
score: 0
tagged with: pandas
tagged with: geopandas
answer count: 1
has body: I would like to combine several Json objects into a GeoJSON feature collection with LineStrings For example I have the following badly formatted json objects: {"lat":16.0269337,"lon":40.073042,"score":1,"ID":"13800006252028","TYPES":"Regional","N2C":"2","NAME":"Strada Statale della Val Sinni"} {"lat":16.0316522,"lon":41.6808931,"score":1,"ID":"13800006260148","TYPES":"Scenic","N2C":"2"} {"lat":16.0316523,"lon":41.6808932,"score":1,"ID":"13800006260148","TYPES":"Scenic","N2C":"2","NAME":"Giro del Gargano"} {"lat":16.0316522,"lon":41.6808931,"score":1,"ID":"13800006203620","TYPES":"Scenic","N2C":"2"} {"lat":16.0316522,"lon":41.6808931,"score":1,"ID":"13800006203620","TYPES":"Regional","N2C":"2","NAME":"Giro del Gargano"} {"lat":16.032322,"lon":40.6097567,"score":1,"ID":"13800005963252","TYPES":"Scenic","N2C":"2"} {"lat":16.032322,"lon":40.6097567,"score":1,"ID":"13800005963252","TYPES":"Regional","N2C":"2","NAME":"Via Appia"} I am aiming to do two things Use the IDs to create GeoJson linestrings if the ID &amp; same type is the same add the score of the matching json files up based on the score property.
has answer: http://stackoverflow.com/a/48015961
has title: Create new GeoJSON LineString from JSON objects using a property
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/json
tagged with: geojson
type: Question

http://stackoverflow.com/comment/83148381
comment on: http://stackoverflow.com/a/48086638
has text: `I need to print out each element of 'mylist' on a new line. However, I am not allowed to use loops (as in 'for i in mylist...') and I can't say:` <--- does exactly that.-
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48102119
tagged with: macos-high-sierra
type: Question
has comment: http://stackoverflow.com/comment/83184733
score: 0
has body: I was trying to install pydub to play a sound on one of my projects and when I finally got to the point where I was supposed to type in pip install pydub, I got smacked in the face with this red wall of error. Could someone please help me install pydub trough any means, regardless if it's pip or not. Sailendrans-MacBook-Pro:~ Sai$ pip install pydub Collecting pydub Using cached pydub-0.20.0-py2.py3-none-any.whl Installing collected packages: pydub Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/pydub'
has title: Error trying to pip install Pydub and Pygame on Mac OSX
tagged with: terminal
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83184422
answer count: 0

http://stackoverflow.com/comment/83061820
type: AnswerComment
has text: @mins I think I have understood... I've another idea, look at my edition.
type: Comment
comment on: http://stackoverflow.com/a/48044035
score: 0

http://stackoverflow.com/q/48016771
has comment: http://stackoverflow.com/comment/83003094
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83002945
tagged with: module
answer count: 0
has body: I'm making a simple image editing Tkinter program but when I try to import the PE_functions.py file I made to make the main.py code cleaner I get an error (they're in the same folder) saying: AttributeError: module 'PE_functions' has no attribute 'add_top_menu' main.py from tkinter import * import PE_functions root = Tk() PE_functions.add_top_menu() main_frame = Frame(root, width=500, height=400) main_frame.pack() root.mainloop() PE_functions.py from tkinter import * import main def add_top_menu(): # adds menu bar top_menu = Menu(main.root) main.root.config(menu=top_menu) # creates sub menu called "file" file_menu = Menu(top_menu, tearoff=False) top_menu.add_cascade(label="File", menu=file_menu) file_menu.add_command(label="New") file_menu.add_command(label="Open") file_menu.add_separator() file_menu.add_command(label="Save") file_menu.add_command(label="Save as") file_menu.add_separator() file_menu.add_command(label="Exit") # adds "edit" sub menu edit_menu = Menu(top_menu, tearoff=False) top_menu.add_cascade(label="Edit", menu=edit_menu) edit_menu.add_command(label="Flip") edit_menu.add_command(label="Rotate") edit_menu.add_command(label="Crop")
type: Question
has title: Importing module issue
score: 0
tagged with: python-import

http://stackoverflow.com/a/48103865
score: 0
answers question: http://stackoverflow.com/q/48103693
has body: try for song in [unicode(song, 'utf-8') for song in reader]: print(...)
type: Answer

http://stackoverflow.com/comment/83037257
has text: Through Django admin before and after the function is run.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48033528

http://stackoverflow.com/q/48065179
has body: I have a requirement to pull all the URLs from a webpage and data from the map if there is a map in the webpage. I was able to get all the URLs from the webpage by using Python Selenium but not able to get the data under the map. This is the sample URL. In Google, I searched for "tool rental" and got the following URL. In the following webpage there is a map, I was trying to get the data under the map. URL: https://www.google.com/search?q=tool+rental&rlz=1C1GCEA_en&oq=tool+rental&aqs=chrome.0.0l6.1735j0j7&sourceid=chrome&ie=UTF-8 Map: Desired Output: The Rental Center at The Home Depot Northside Tool Rental Northside Tool Rental I tried different options(find_eliment_by_xpath, find_eliment etc.) to get the above data but nothing worked. The following code I was using to get the URLs and data from maps. from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By driver = webdriver.Firefox(executable_path=r'C:\Chaitu\Projects\Media Marketing\brightlocal\geckodriver.exe') driver.get("https://www.google.com/search?q=tool+rental&rlz=1C1GCEA_en&oq=tool+rental&aqs=chrome.0.0l6.1735j0j7&sourceid=chrome&ie=UTF-8") driver.save_screenshot('image.png') element=driver.find_element_by_tag_name('body') element_png = element.screenshot_as_png with open("test2.png", "wb") as file: file.write(element_png) elems = driver.find_elements_by_xpath("//a") for elem in elems: print str(elem.get_attribute("href")) with open("url_list.txt",'w') as f: for elem in elems: if 'maps' in str(elem.get_attribute("href")) or ('google' not in str(elem.get_attribute("href")) and 'blogger' not in str(elem.get_attribute("href")) and 'youtube' not in str(elem.get_attribute("href")) and 'https' in str(elem.get_attribute("href"))): f.write(str(elem.get_attribute("href"))+"\n")
favorite count: 0
has title: Scraping the data from website under the map by using python Selinium
upvote count: 2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83110795
answer count: 0
score: 1
tagged with: selenium
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83103891
has comment: http://stackoverflow.com/comment/83110774
has comment: http://stackoverflow.com/comment/83103630
has comment: http://stackoverflow.com/comment/83134199
has comment: http://stackoverflow.com/comment/83103634

http://stackoverflow.com/q/48135593
tagged with: class
upvote count: 8
has comment: http://stackoverflow.com/comment/83248320
has comment: http://stackoverflow.com/comment/83248483
tagged with: python
tagged with: dictionary
has title: Why is the dictionary key being converted to an inherited class type?
has comment: http://stackoverflow.com/comment/83248417
has comment: http://stackoverflow.com/comment/83248338
has answer: http://stackoverflow.com/a/48135770
downvote count: 1
possible better answer: http://stackoverflow.com/a/48159976
has comment: http://stackoverflow.com/comment/83248428
has answer: http://stackoverflow.com/a/48159976
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83248367
has comment: http://stackoverflow.com/comment/83248452
has comment: http://stackoverflow.com/comment/83248353
score: 7
has body: My code looks something like this: class SomeClass(str): pass some_dict = {'s':42} &gt;&gt;&gt; type(some_dict.keys()[0]) str &gt;&gt;&gt; s = SomeClass('s') &gt;&gt;&gt; some_dict[s] = 40 &gt;&gt;&gt; some_dict # expected: Two different keys-value pairs {'s': 40} &gt;&gt;&gt; type(some_dict.keys()[0]) str Why did Python convert the object s to the string "s" while updating the dictionary some_dict?
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48135770
has comment: http://stackoverflow.com/comment/83248468
has comment: http://stackoverflow.com/comment/83248449
favorite count: 0

http://stackoverflow.com/a/48076465
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48076368
type: Answer
upvote count: 3
has body: This will simply count the number of times the expression "dance" appears import re print len(re.findall('dance\\b', string)) This website should give you more information about the regular expression lib. https://docs.python.org/2/library/re.html

http://stackoverflow.com/a/48142544
score: -1
answers question: http://stackoverflow.com/q/48142516
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83264461
has body: In general, throwing exceptions for non-exceptional situations is poor design. You want a defaultdict. from collections import defaultdict renames = defaultdict(lambda: None) # Add the elements to renames here ... Now, renames is a dictionary, except that if the key doesn't exist, it returns None rather than throwing, so you can just check if the value is None to see if it needs to be renamed.
downvote count: 1

http://stackoverflow.com/a/48159402
answers question: http://stackoverflow.com/q/48159340
downvote count: 0
has body: Use groupby + agg - a.astype(str).groupby(a.number, as_index=False).agg('; '.join) A number 0 abc; def 2; 2 1 ghi 3 Thanks to MaxU for the tune-up!
upvote count: 6
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48159340
has comment: http://stackoverflow.com/comment/83298438
has comment: http://stackoverflow.com/comment/83298809
type: Answer
score: 6

http://stackoverflow.com/q/48072046
favorite count: 0
has comment: http://stackoverflow.com/comment/83117676
tagged with: python
type: AnsweredQuestion
has title: How to extract characters from strings
has body: I run the code: from subprocess import Popen, PIPE p1 = Popen(['ip', 'addr'], stdout=PIPE) p2 = Popen(['grep', 'enp'], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() output=p2.communicate()[0] print(output) and I get the output: b'7: enp0s20f0u1c4i2: &lt;BROADCAST,MULTICAST,UP,LOWER_UP&gt; mtu 1500 qdisc pfifo_fast state UNKNOWN group default qlen 1000\n inet 172.20.10.2/28 brd 172.20.10.15 scope global dynamic enp0s20f0u1c4i2\n' How to extract the characters enp0s20f0u1c4i2 from the string of this output?
has comment: http://stackoverflow.com/comment/83117666
type: Question
accepted answer: http://stackoverflow.com/a/48072111
score: 0
upvote count: 1
downvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48072111

http://stackoverflow.com/comment/83221176
score: 0
type: Comment
type: QuestionComment
has text: @EliKorvigo I'm not really advocating an OOP style. Many design patterns address shortcomings of the implementation languages. In C++/Java we create `Functors`, which are function objects, which support function call syntax. We have to create them explicitly and Patterns like `Strategy`, `State`, and `Command` depend upon them for their implementation. However, as functions in Python are already objects (and instances of classes which implement `__call__`, thus enabling function call syntax) we don't have to implement it ourselves. So we just use a function. But it's still the Strategy pattern
comment on: http://stackoverflow.com/q/48121458

http://stackoverflow.com/comment/83324041
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48168862
has text: The troublesome old date-time classes used here in Java were outmoded years ago, supplanted by the *java.time* classes. `Instant.now().toString()` --> `2018-01-23T12:34:56.123456Z`

http://stackoverflow.com/q/48051390
downvote count: 0
has body: I'm working on a small program in python and using the numpy library. This is just for educational purpose and for fun. My maths background is poor and I try to understand what's going on with the dot function. I know what is an array and understand that a matrix is a N-dimensionnal array I also understand how to make a product of this two types, but it's still not clear when I make the products of two N-dimensionnal arrays. I'm doing some testing in the terminal and here's what I get : &gt;&gt;&gt; a = [[2, 4], [3, 7], [5, 1]] &gt;&gt;&gt; b = [[1, 6, 7], [3, 9, 2]] &gt;&gt;&gt; numpy.dot(a, b) array([[14, 48, 22], [24, 81, 35], [ 8, 39, 37]]) Please can a math guru help me to interpret this result ? Tell me if the problem is not clear to you, I'll develop if necessary. Edit: To be more precise about my testing methodology, one of this tests was to apply the dot function on a N-D array and a 1-D array: &gt;&gt;&gt; a = [[2, 4], [3, 7], [5, 1]] &gt;&gt;&gt; b = [1, 6] &gt;&gt;&gt; numpy.dot(a, b) array([26, 45, 11]) And here is my comprehension of this: "b" length must be the same length as any of the "a" subset, if not shapes are not aligned And the result is calculated like that: [a[0][0] * b[0] + a[0][1] * b[1], a[1][0] * b[0] + a[1][1] * b[1], a[2][0] * b[0] + a[2][1] * b[1]]
has title: What numpy.dot function really do with N-dimensional arrays?
answer count: 1
has comment: http://stackoverflow.com/comment/83074854
score: 1
has comment: http://stackoverflow.com/comment/83074732
favorite count: 0
has comment: http://stackoverflow.com/comment/83074570
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83074856
has answer: http://stackoverflow.com/a/48051482
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48051482

selenium-chromedriver
tags question: http://stackoverflow.com/q/48045663
tags question: http://stackoverflow.com/q/48118496
tags question: http://stackoverflow.com/q/48144078
tags question: http://stackoverflow.com/q/48028782
tags question: http://stackoverflow.com/q/48119282
tags question: http://stackoverflow.com/q/48115462
tags question: http://stackoverflow.com/q/48087399
tag name: selenium-chromedriver
tags question: http://stackoverflow.com/q/48071044
type: Tag
tags question: http://stackoverflow.com/q/48055427

http://stackoverflow.com/q/48125803
has title: How to write information from a list to a csv file using csv DictWriter?
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48125846
accepted answer: http://stackoverflow.com/a/48125846
upvote count: 2
has comment: http://stackoverflow.com/comment/83228309
answer count: 2
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has body: Using the csv module , Ive been trying to pass / write information from a list to a csv file in pythonusing the dictwriter and im getting a strange error , witch will be under the actual code. I want to know whats , the error in the code , and how can we fix it. import csv names = ['kisha' ,'smith' , 'kishasmith@gmail.com', 40000 , '1-1-2029' ,'janitor' ] with open('employees.csv' , 'w')as employee_file: fieldnames2 = ['first' , 'last' , 'email' , 'salary' , 'DOB' , 'occupation'] csvwriter = csv.DictWriter(employee_file , fieldnames = fieldnames2 , delimiter = ',') csvwriter.writeheader() for info in names: csvwriter.writerow(info) Ive seen other questions related to this topic but nun are applicable to me. ERROR: Traceback (most recent call last): File "C:\Users\Kxrk\Downloads\Codes\Employee project\new.py", line 10, in <module> csvwriter.writerow(info) File "C:\Users\Kxrk\AppData\Local\Programs\Python\Python36-32\lib\csv.py", line 155, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "C:\Users\Kxrk\AppData\Local\Programs\Python\Python36-32\lib\csv.py", line 148, in _dict_to_list wrong_fields = rowdict.keys() - self.fieldnames AttributeError: 'str' object has no attribute 'keys' [Finished in 0.1s]
tagged with: python
possible better answer: http://stackoverflow.com/a/48125850
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48125850

http://stackoverflow.com/a/48176171
upvote count: 1
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83343535
type: AcceptedAnswer
has body: Per the code you've provided, you've got a logic error between what remove expects (a single item to remove from the list) and what you're giving it (a list of items). You initialize your instance with: D1=Deck(['2h','Jh']) so self.plr_cur_value is ['2h','Jh'], which means your remove call is equivalent to: self.global_l_init.remove(['2h','Jh']) remove looks through your global_l_init list (which only has length 2 str in it), trying to see if it contains a length 2 list of length 2 str (which it doesn't, it doesn't contain any lists at all). If the goal is to remove each of the elements from global_l_init, you need to change: self.global_l_init.remove(self.plr_cur_value) to: for card in self.plr_cur_value: self.global_l_init.remove(card) to make it remove each card individually. Note that list is a suboptimal data structure when you need to repeatedly perform membership testing (O(n)), or perform random access list insertions or removals (O(n) each). Since all your values are unique and order-insensitive, you'd be better off using a set here, which has O(1) insertion, deletion and membership testing: class Deck(object): #Cards' value d={'2h':2,'2d':2,'2s':2,'2c':2,'3h':3,'3d':3,'3s':3,'3c':3, '4h':4,'4d':4,'4s':4,'4c':4,'5h':5,'5d':5,'5s':5,'5c':5, '6h':6,'6d':6,'6s':6,'6c':6,'7h':7,'7d':7,'7s':7,'7c':7, '8h':8,'8d':8,'8s':8,'8c':8,'9h':9,'9d':9,'9s':9,'9c':9, '10h':10,'10d':10,'10s':10,'10c':10,'Jh':10,'Jd':10,'Js':10, 'Jc':10,'Qh':10,'Qd':10,'Qs':10,'Qc':10,'Kh':10,'Kd':10,'Ks':10,'Kc':10, 'Ah':10,'Ad':10,'As':10,'Ac':10,'Ah':1,'Ad':1,'As':1,'Ac':1} # Simplest way to make set here is to reuse d to make global_l_init w/o repeating yourself: global_l_init = set(d) def __init__(self,plr_cur_value): self.plr_cur_value = set(plr_cur_value) # Convert to set on initialization def deck_change(self): # Optionally, make sure the cards are in the shared set before removing them # to match list.remove behavior of raising ValueError when card not found if not (self.plr_cur_val…
accepted answer of: http://stackoverflow.com/q/48157353
answers question: http://stackoverflow.com/q/48157353
type: Answer

http://stackoverflow.com/comment/83167722
has text: Beyond that, I still don't see why you'd *expect* the code in `searcholdvalue` to be entered -- you aren't actually calling it anywhere. (I also don't see why you're defining it inside a nested scope rather than defining it at top level and then *invoking* it where you need it).
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48095895
type: Comment

http://stackoverflow.com/q/48086812
has answer: http://stackoverflow.com/a/48086925
has answer: http://stackoverflow.com/a/53746966
accepted answer: http://stackoverflow.com/a/53746966
upvote count: 2
tagged with: stackexchange-api
score: 2
type: AnsweredQuestion
type: Question
answer count: 2
has title: Stackexchange API: fetch answers to a specific stack post
downvote count: 0
favorite count: 0
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/48086925
tagged with: python
has body: I am using the stackAPI Python wrapper to interface with the stackexchange api. I am trying to fetch the top most popular questions above a vote count threshold; and for each of those questions the top answers above a certain vote count. SITE = StackAPI("stackoverflow") SITE.max_pages=2 SITE.page_size=100 questions = SITE.fetch('questions', min=10, sort='votes') for quest in questions['items']: if 'title' not in quest: continue quest_id = quest['question_id'] title = quest['title'] tags = [] if 'tags' in quest: tags = quest['tags'] #body = quest['body'] body = "" if 'body' in quest: body = quest['body'] answers = SITE.fetch('answers', id=[quest_id],min=10, sort='votes') for answer in answers['items']: _stuck here_ This is where I am stuck, how to fetch answers for the above question_id this query is returning some random answer_ids. How do fetch the question-&lt; answers

http://stackoverflow.com/comment/83055925
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48042559
has text: But what does that *mean?* If you don't actually have a goal you're failing to reach, the question is unanswerable. If you're just experimenting, what about this has surprised you?
type: Comment

http://stackoverflow.com/q/48022943
has comment: http://stackoverflow.com/comment/83019941
accepted answer: http://stackoverflow.com/a/48023209
has comment: http://stackoverflow.com/comment/83019296
has comment: http://stackoverflow.com/comment/83015357
has title: How is this list expanded with the slicing assignment?
type: Question
has body: I came across the following code (sort of): my_list = [1, [2, 3, 4], 5] my_list[1:2] = my_list[1] After running these two lines, the variable my_list will be [1, 2, 3, 4, 5]. Pretty useful for expanding nested lists. But why does it actually do what it does? I would have assumed that the statement my_list[1:2] = my_list[1] would do one of the following: simply put [2, 3, 4] into the second position in the list (where it already is) give some kind of "too many values to unpack" error, from trying to put three values (namely 2,3,4) into a container of only length 1 (namely my_list[1:2]). (Repeating the above with a Numpy array instead of a list results in a similar error.) Other questions (e.g. How assignment works with python list slice) tend to not pay much attention to the discrepancy between the size of the slice to be replaced, and the size of the items you're replacing it with. (Let alone explaining why it works the way it does.)
has answer: http://stackoverflow.com/a/48023285
answer count: 6
linked to: http://stackoverflow.com/q/509211
favorite count: 0
possible better answer: http://stackoverflow.com/a/48023253
has answer: http://stackoverflow.com/a/48024032
has answer: http://stackoverflow.com/a/48023253
linked to: http://stackoverflow.com/q/10623302
has answer: http://stackoverflow.com/a/48023345
has comment: http://stackoverflow.com/comment/83016614
tagged with: python
has answer: http://stackoverflow.com/a/48023209
has answer: http://stackoverflow.com/a/48023956
upvote count: 14
score: 12
downvote count: 2
duplicate of: http://stackoverflow.com/q/10623302
type: AnsweredQuestion

http://stackoverflow.com/q/48027155
tagged with: plot
type: Question
has comment: http://stackoverflow.com/comment/83330159
tagged with: graph
tagged with: matplotlib
linked to: http://stackoverflow.com/q/42622146
score: 0
tagged with: visualization
has comment: http://stackoverflow.com/comment/83029279
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83025684
has body: I tried to show a large Matplotlib Pyplot figure (figsize=(9, 36)) from a Python command line code in Windows 7. It gave this warning and generated a figure with all subplots squeezed: QWindowsWindow::setGeometry: Unable to set geometry 1350x5466+8+30 on QWidgetWindow/ 'MainWindowClassWindow'. Resulting geometry: 1350x882+8+30 (frame: 8, 30, 8, 8, custom margin: 0, 0, 0, 0, minimum size: 67x66, maximum size: 16777215x16777215). Is there any way to solve the issue and plot the intact figure?
type: UnansweredQuestion
tagged with: python
has title: How to display large Matplotlib window?
answer count: 0
has comment: http://stackoverflow.com/comment/83026991

http://stackoverflow.com/comment/83031836
score: 0
type: AnswerComment
type: Comment
has text: That `i<=7` could be `i==7`.
comment on: http://stackoverflow.com/a/48030737

http://stackoverflow.com/q/48152309
tagged with: python
has comment: http://stackoverflow.com/comment/83283623
accepted answer: http://stackoverflow.com/a/48152366
has title: Pandas Group by three columns but retain all other columns
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91487331
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/48152369
type: Question
has comment: http://stackoverflow.com/comment/83283564
has body: I have data frame like this: offer_id affiliate_id affiliate_source affiliate_sub5 advertiser_id Payout_cent Revenue_cents 428572 1327 14331605 14331605 291 50 30 428572 1327 1465 1465 291 50 30 428572 1327 1336 1336 291 50 30 428572 1327 14331605 14331605 291 50 30 428572 1327 14331605 14331605 291 50 30 I am grouping three columns "offer_id", "affiliate_id", "affiliate_source" Operation: df1.groupby(['offer_id', 'affiliate_id', 'affiliate_source'])"payout_cents", "revenue_cents".sum() Result: offer_id affiliate_id affiliate_source payout_cents revenue_cents 428572 1327 14331605 90 150 1465 30 50 1336 30 50 Issue: I need to get other columns also like "advertiser_id" and "affiliate_sub5" after group operation. Thanks.
tagged with: dataframe
answer count: 2
has comment: http://stackoverflow.com/comment/83283032
tagged with: pandas
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48152369
has answer: http://stackoverflow.com/a/48152366

http://stackoverflow.com/q/48133559
tagged with: python
has title: How can I download files from a private repo with ssh for bitbucket/github?
accepted answer: http://stackoverflow.com/a/48200407
downvote count: 1
type: AnsweredQuestion
tagged with: paramiko
type: Question
upvote count: 4
tagged with: bitbucket
has body: I have looked through docs and cannot find anywhere an example of how this might be achieved. This question relates to this, in that I want to distribute updates but only to those that have a ssh key rather than using simple auth. It works by looking at versions.gz file and then getting the most recent download. Is this possible with ssH? import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ##ssh://git@bitbucket.org/Tysondogerz/ssh/downloads ssh.connect('104.192.143.2', 8080, username='https://bitbucket.org/Tysondogerz/ssh/downloads/', password="", key_filename='C:\\Users\\Django\\.ssh\\id_rsa') #TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Is there a way to authenticate others to download updates from my repository, or is this just a limitation of bitbucket and you must use public repo’s and to use private repo's give out your password with basic auth and cross fingers.
answer count: 1
has comment: http://stackoverflow.com/comment/83382088
linked to: http://stackoverflow.com/q/48047296
has comment: http://stackoverflow.com/comment/83382052
has comment: http://stackoverflow.com/comment/83381969
tagged with: github
favorite count: 0
has answer: http://stackoverflow.com/a/48200407
score: 3
has comment: http://stackoverflow.com/comment/83377245
tagged with: ssh

http://stackoverflow.com/q/48158688
upvote count: 11
favorite count: 0
has title: Save Pandas describe for human readibility
score: 11
has answer: http://stackoverflow.com/a/48158748
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48158748
type: Question
linked to: http://stackoverflow.com/q/35634238
has comment: http://stackoverflow.com/comment/83297044
answer count: 1
has body: working on pandas describe function. simple enough code: df['Revenue'].describe() output is : perfect. my issue is i want to be able to save this data as either a png or a table so that i can place in a single page. this is for my EDA (exploratory data analysis) i have 6 main charts or information that i want to evaluate on each feature. each chart will be a seperate png file. i will then combine into one pdf file. i iterate over 300 + features so doing one at a time is not an option especially seeing as it is done monthly. if you know of a way to save this table as a png or other similar file format that would be great. thanks for the look
downvote count: 0
duplicate of: http://stackoverflow.com/q/35634238
has comment: http://stackoverflow.com/comment/83296897
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/83122075
score: 0
type: AnswerComment
type: Comment
has text: Thanks for your detailed answer, Torek! So if I understand properly, it is not a good idea to clear all variables at the beginning of the script, since the "new" Python imports the main module to allow the multiprocessing code to access the entire program...
comment on: http://stackoverflow.com/a/48064653

http://stackoverflow.com/q/48072486
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48642005
tagged with: python
has answer: http://stackoverflow.com/a/48755812
upvote count: 4
has body: I have a testSuite in Python with several test cases using unit test framework. I am using import unit test for that If a test step in test case fails, test case goes to teardown class. I would like to continue rest of the test case even if one test case fails. The default behaviour of a unit test: If any test step fails, it goes to tear down class and end the test case. Test step: I mean assert equal and like this inbuilt proc which defines whether it is a failure or pass
has comment: http://stackoverflow.com/comment/84279756
type: Question
score: 3
has answer: http://stackoverflow.com/a/48737184
has comment: http://stackoverflow.com/comment/84518858
tagged with: python-unittest
has title: Run test-case in case of failure step in unit test python
answer count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/84279566

http://stackoverflow.com/q/48166014
has answer: http://stackoverflow.com/a/48166309
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48166057
has body: I have a dataframe and want to eliminate duplicate rows, that have same values, but in different columns: df = pd.DataFrame(columns=['a','b','c','d'], index=['1','2','3']) df.loc['1'] = pd.Series({'a':'x','b':'y','c':'e','d':'f'}) df.loc['2'] = pd.Series({'a':'e','b':'f','c':'x','d':'y'}) df.loc['3'] = pd.Series({'a':'w','b':'v','c':'s','d':'t'}) df Out[8]: a b c d 1 x y e f 2 e f x y 3 w v s t Rows [1],[2] have the values {x,y,e,f}, but they are arranged in a cross - i.e. if you would exchange columns c,d with a,b in row [2] you would have a duplicate. I want to drop these lines and only keep one, to have the final output: df_new Out[20]: a b c d 1 x y e f 3 w v s t How can I efficiently achieve that?
type: Question
has answer: http://stackoverflow.com/a/48166341
score: 5
upvote count: 5
tagged with: duplicates
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48166057
has title: Pandas find Duplicates in cross values
downvote count: 0
has comment: http://stackoverflow.com/comment/83311094
favorite count: 0
possible better answer: http://stackoverflow.com/a/48166309

http://stackoverflow.com/q/48147413
has body: My list contains the following elements: &gt;&gt;&gt; s = "foo a=b c=d e=f" &gt;&gt;&gt; s.split() ['set', 'a=b', 'c=d', 'e=f'] &gt;&gt;&gt; splitted = s.split() &gt;&gt;&gt; splitted[1:] ['a=b', 'c=d', 'e=f'] Now I want to use map to get the following result: [{'a': 'b'}, {'c': 'd'}, {'e': 'f'}] I tried the following, but this gives me an IndexError: &gt;&gt;&gt; map(lambda x : dict((a[0], a[1]) for a in x.split('=')) , splitted[1:]) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 1, in &lt;lambda&gt; File "&lt;stdin&gt;", line 1, in &lt;genexpr&gt; IndexError: string index out of range
has comment: http://stackoverflow.com/comment/83273074
favorite count: 0
possible better answer: http://stackoverflow.com/a/48147508
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/48148045
linked to: http://stackoverflow.com/q/46263897
type: AnsweredQuestion
score: 3
type: Question
has answer: http://stackoverflow.com/a/48147508
has comment: http://stackoverflow.com/comment/83273004
has title: How to map list of strings containing key value to dict in Python?
has answer: http://stackoverflow.com/a/48147517
accepted answer: http://stackoverflow.com/a/48147517
answer count: 3
tagged with: functional-programming
downvote count: 1

http://stackoverflow.com/q/48154938
linked to: http://stackoverflow.com/q/33791279
has comment: http://stackoverflow.com/comment/83289285
accepted answer: http://stackoverflow.com/a/48155333
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48155077
has title: Add one to numbers matching a certain regex in a string
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48155816
has comment: http://stackoverflow.com/comment/83333178
has comment: http://stackoverflow.com/comment/83289016
score: 5
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/48155816
has answer: http://stackoverflow.com/a/48155094
has answer: http://stackoverflow.com/a/48158200
has answer: http://stackoverflow.com/a/48155333
has body: I have a Python string that looks something like this: "5 pounds cauliflower, cut into 1-inch florets (about 18 cups) 2 large leeks, 1 teaspoons salt 3 cups of milk" And I need to add 1 to every number that appears before the keyword cup. The result needs to be: "5 pounds cauliflower, cut into 1-inch florets (about 19 cups) 2 large leeks, 1 teaspoons salt 4 cups of milk" I have something along the lines of: import re p = re.compile('([0-9]+) cup') for i in p.finditer(s): # do something with int(i.group(1)) + 1 I can't figure out how to replace only the number that I find in each iteration. I also have an edge case where I might need to replace 9 with 10, so I can't simply get the index of the number and replace that digit with the new one, because the new number may be longer. Solutions not involving regexes are also welcome.
upvote count: 5
answer count: 5

http://stackoverflow.com/comment/83174714
comment on: http://stackoverflow.com/a/48099772
score: 1
has text: and the output it ain't the same as mine, why is that so ?
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83172071
type: QuestionComment
comment on: http://stackoverflow.com/q/48090535
has text: This would be much, much simpler in a python. Do you require a solution that only uses robot keywords? There are also pre-built libraries for dealing with csv files. Is there a reason you aren't using one of them?
score: 0
type: Comment

http://stackoverflow.com/q/48072862
linked to: http://stackoverflow.com/q/43018576
tagged with: scrapy
type: Question
downvote count: 0
has body: I am scraping a website and it has this JSON data in return. https://pastebin.com/R50eTqrD this is output of print( repr( string ) ) https://pastebin.com/VH6JrDMG this is output of print( string ) I am doing resp = json.loads(resp) But its giving me this error ValueError: Invalid \escape: line 1 column 170 (char 169) I found a solution here and it suggested me to do resp = json.loads(HTMLParser().unescape(resp.decode('unicode-escape'))) But it now throws this error UnicodeEncodeError: 'ascii' codec can't encode characters in position 51-59: ordinal not in range(128) I have tried several solutions like json.loads(HTMLParser().unescape(resp.decode('unicode-escape')).encode("utf-8")) and many more but none of it worked for me.
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83119759
answer count: 1
has comment: http://stackoverflow.com/comment/83119749
has title: ValueError: Invalid \escape: error while doing json.loads()
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/83119615
has answer: http://stackoverflow.com/a/48073073
has comment: http://stackoverflow.com/comment/117101667

http://stackoverflow.com/comment/119309664
type: Comment
score: 3
comment on: http://stackoverflow.com/a/54026228
type: AnswerComment
has text: aoihttp also advises to use a single session for your entire application to improve connection pooling. I don't see how you can do this in a reasonable way with this use pattern

http://stackoverflow.com/comment/83052878
comment on: http://stackoverflow.com/q/48041147
type: Comment
score: 1
has text: Please can you add the error message thrown by the exception ?
type: QuestionComment

http://stackoverflow.com/a/48080325
has body: This is the approach using inbox itertools, you don't need to install any extra package. Then this is how to write it in a pythonistic way also using dictionary and list comprehension. Step by step approach: #reading all file at once import csv with open('EGLOINDOORCSV.csv') as csvfile: l=[r for r in csv.reader(csvfile, delimiter=r',')][1:] #skip header #itertools requires sorted data. Sorting by second field. key=lambda x: x[1] l = sorted( l, key = key) #grouping to an aux dictionary from itertools import groupby d={ k: "///".join( x[0] for x in g) for k,g in groupby( l, key) } #updating third column from aux dictionary for x in l: x[2]=d[x[1]] Et voilà! #this is the content of l, ready to go back to a new csv [ ['ExOne', 'GroupOne', 'ExOne///ExTwo///ExThree'], ['ExTwo', 'GroupOne', 'ExOne///ExTwo///ExThree'], ['ExThree', 'GroupOne', 'ExOne///ExTwo///ExThree'], ['ExSix', 'GroupThree', 'ExSix'], ['ExFour', 'GroupTwo', 'ExFour///ExFive'], ['ExFive', 'GroupTwo', 'ExFour///ExFive'], ] Disclaimer: This is a vanilla solution, all in the box, but remember, pandas is your friend handling data, take in mind to install it and move to a pandas solution if you need to manage lots of data. Raw data $cat EGLOINDOORCSV.csv Martial,Serial,Related ExOne,GroupOne, ExTwo,GroupOne, ExThree,GroupOne, ExFour,GroupTwo, ExFive,GroupTwo, ExSix,GroupThree,
has comment: http://stackoverflow.com/comment/83134841
score: 1
has comment: http://stackoverflow.com/comment/83134761
answers question: http://stackoverflow.com/q/48079783
has comment: http://stackoverflow.com/comment/83134764
has comment: http://stackoverflow.com/comment/83137669
downvote count: 0
has comment: http://stackoverflow.com/comment/83136373
type: Answer
upvote count: 1

http://stackoverflow.com/q/48143749
upvote count: 3
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83266245
favorite count: 0
has comment: http://stackoverflow.com/comment/83265886
linked to: http://stackoverflow.com/q/47633511
tagged with: multidimensional-array
has body: What does the result from object.__flags__ mean? And how to interpret it? In [55]: str.__flags__ Out[55]: 269227008 In [56]: list.__flags__ Out[56]: 34362368 In [57]: tuple.__flags__ Out[57]: 67916800 In [58]: object.__flags__ Out[58]: 791552 In [59]: ndarray.__flags__ Out[59]: 791552 Also, most importantly, why do we get the same result for object.__flags__ and ndarray.__flags__ ?
tagged with: python
has comment: http://stackoverflow.com/comment/83265643
has title: Understanding object.__flags__ and ndarray.__flags__
accepted answer: http://stackoverflow.com/a/48158761
score: 2
type: AnsweredQuestion
tagged with: oop
has comment: http://stackoverflow.com/comment/83270660
has comment: http://stackoverflow.com/comment/83265640
has answer: http://stackoverflow.com/a/48158761
type: Question
tagged with: numpy

http://stackoverflow.com/comment/83169128
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48096510
has text: You never said *what* is initial solution. If you'd order `itertools.combinations(a, group_count)` different way you might get different "initial" solution". What I've listed in my answer is "groups" of solutions actually, (each group has 2 elements) not additional combinations for `(1,2,3),(1,4,5)`.
score: 0

http://stackoverflow.com/q/48019814
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/48019856
downvote count: 1
type: Question
answer count: 2
has title: In python, how to use traceback to assign the error message to a variable?
has body: import traceback try: 1/0 except Exception,e: traceback.print_exc() The output is as follow: Traceback (most recent call last): File "test_traceback.py", line 3, in &lt;module&gt; 1/0 ZeroDivisionError: integer division or modulo by zero However I don't want to use traceback.print_exc() to print the output. Instead, I want to save the output to a variable. How can I do that?
linked to: http://stackoverflow.com/q/8238360
has comment: http://stackoverflow.com/comment/83008693
favorite count: 0
has answer: http://stackoverflow.com/a/48019857
tagged with: exception
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48023385
has comment: http://stackoverflow.com/comment/83016468
has comment: http://stackoverflow.com/comment/83016866
has comment: http://stackoverflow.com/comment/83016739
has comment: http://stackoverflow.com/comment/83017240
has comment: http://stackoverflow.com/comment/83016207
has comment: http://stackoverflow.com/comment/83016704
has comment: http://stackoverflow.com/comment/83015915
type: Question
has answer: http://stackoverflow.com/a/48024117
has comment: http://stackoverflow.com/comment/83016036
has comment: http://stackoverflow.com/comment/83017055
has comment: http://stackoverflow.com/comment/83016810
has comment: http://stackoverflow.com/comment/83016270
has comment: http://stackoverflow.com/comment/83015930
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/83017083
has comment: http://stackoverflow.com/comment/83016879
answer count: 1
has comment: http://stackoverflow.com/comment/83015978
has comment: http://stackoverflow.com/comment/83016638
has body: I am using numpy to create an array out of a .csv file. This file's top row is made up of text, so I copied this command from the article I was using to leave it out when using float(I have left in the whole code for context. The command is the [1:] in the last line) import numpy as np import csv with open("atest.csv", 'r') as f: wines = list(csv.reader(f, delimiter=";")) print(wines[:3]) wines_array = np.array(wines[1:], dtype=np.float) However, I still get this error message: wines_array = np.array(wines[1:], dtype=np.float) ValueError: could not convert string to float: 'fixed acidity' This indicates that it has not left out the top row. Does anyone have any help? EDIT This is my .csv file: "fixed acidity";"volatile acidity";"citric acid";"residual sugar";"chlorides";"free sulfur dioxide";"total sulfur dioxide";"density";"pH";"sulphates";"alcohol";"quality" 7.4;0.7;0;1.9;0.076;11;34;0.9978;3.51;0.56;9.4;5 7.8;0.88;0;2.6;0.098;25;67;0.9968;3.2;0.68;9.8;5 The first line is all one row in my file.
has comment: http://stackoverflow.com/comment/83017200
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83017072
tagged with: python
has title: How to fix numpy string error
has comment: http://stackoverflow.com/comment/83016855
has comment: http://stackoverflow.com/comment/83015902

http://stackoverflow.com/q/48137451
has comment: http://stackoverflow.com/comment/83252486
has answer: http://stackoverflow.com/a/48137645
has body: Very often I use the following indexing trick: E[y, np.arange(E.shape[1])] -= 1 E is a 2-D array, y is 1-D array and has the same length as E.shape[1], which is used in computing the softmax loss for backprop. If I want to mask some specific label(e.g., value 2) in y I do that by: mask = ~(y == 2) E[y[mask], np.range(E.shape[1])[mask]] -= 1 for a generated example: E = np.arange(32).reshape(4, 8) array([[ 0, 1, 2, 3, 4, 5, 6, 7], [ 8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31]]) y = np.random.randint(4, size=8) array([2, 0, 0, 1, 2, 2, 1, 1]) Without masking (in the normal case), we can write: E[y, np.arange(E.shape[1])]=100 E array([[ 0, 100, 100, 3, 4, 5, 6, 7], [ 8, 9, 10, 100, 12, 13, 100, 100], [100, 17, 18, 19, 100, 100, 22, 23], [ 24, 25, 26, 27, 28, 29, 30, 31]]) then with mask, we can do: mask = ~(y == 2) E[y[mask], np.arange(t.shape[1])[mask]] = 1000 E array([[ 0, 1000, 1000, 3, 4, 5, 6, 7], [ 8, 9, 10, 1000, 12, 13, 1000, 1000], [ 100, 17, 18, 19, 100, 100, 22, 23], [ 24, 25, 26, 27, 28, 29, 30, 31]]) And in the 3-D case, we can do a similar thing for basic indexing without a mask: m, n = E.shape[1:] I, J = np.ogrid[:m, :n] E[y, I, J] -= 1 But I don't know how to perform mask like operations in 3-D or higher dimensional arrays, can someone help?
downvote count: 0
has title: numpy advanced indexing : how to mask specific labels out in 3-D or higher dimensional array
favorite count: 0
has comment: http://stackoverflow.com/comment/83252427
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/48137973
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48137645
has answer: http://stackoverflow.com/a/48137973
type: Question
tagged with: numpy
answer count: 2

http://stackoverflow.com/a/48039570
score: 2
downvote count: 0
has body: You can use regex and str.capitalize(): import re s = " this is a sample sentence. This is a sample second sentence." new_s = '. '.join(i.capitalize() for i in re.split('\.\s', re.sub('^\s+', '', s))) Output: 'This is a sample sentence. This is a sample second sentence.'
answers question: http://stackoverflow.com/q/48039486
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/83049554

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/48058761

http://stackoverflow.com/comment/83286929
type: Comment
has text: My answer is not setting a class attribute. Setting a class attribute would be something like `change_size_modifies = 'size'` at class scope instead of `change_size.modifies = 'size'`. Also, the `wrapper` in your decorator is unnecessary (you could just set the attributes on the original `f` and return `f`), and your syntax is invalid; you shouldn't quote `modifies`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48146924

http://stackoverflow.com/comment/83045494
comment on: http://stackoverflow.com/q/48037627
type: Comment
type: QuestionComment
has text: Do not post pictures please instead try to provide a reproducible code for your datasets or at least provide text form of your datasets, look here https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples
score: 2

http://stackoverflow.com/comment/83015489
comment on: http://stackoverflow.com/q/48019283
has text: Incidentally, just to be sure: you do understand that `STANDARD_IA` costs **more** than `STANDARD` when the object is downloaded more than once per month, right? `STANDARD_IA` saves money on storage, but charges a "data retrieval" fee for each download... hence the name *"infrequent access."* You don't want to use this storage class for objects accessed more frequently than about once per month.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48162075
has comment: http://stackoverflow.com/comment/83315452
tagged with: python
tagged with: apache-nifi
has comment: http://stackoverflow.com/comment/83307453
has title: How best to interact with AWS RDS Postgres via NiFi
possible better answer: http://stackoverflow.com/a/48169766
answer count: 2
has answer: http://stackoverflow.com/a/48169766
tagged with: amazon-rds
upvote count: 1
has answer: http://stackoverflow.com/a/48170299
has body: I have a FlowFile and I want to insert the attributes into RDS. If this was a local machine, I'd create a DBCPConnectionPool, reference a JDBC driver, etc. With RDS, what am I supposed to do? Something similar (how would I do this on AWS)? Or am I stuck using ExecuteScript? If it's the later, is there a Python example for how to do this?
accepted answer: http://stackoverflow.com/a/48170299
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question

sensors
type: Tag
tag name: sensors
tags question: http://stackoverflow.com/q/48071393

http://stackoverflow.com/comment/83049286
comment on: http://stackoverflow.com/q/48039409
has text: brilliant. I did not realize that `getattr` returns the method attribute unless it is appended with parentheses. I was only familiar with `getattr` usage of type attributes. If you add an answer, @SahilDahiya, I will happily accept it.
score: 0
type: Comment
type: QuestionComment

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/48119015
tags question: http://stackoverflow.com/q/48088137
tags question: http://stackoverflow.com/q/48104291
type: Tag

http://stackoverflow.com/comment/83247188
comment on: http://stackoverflow.com/q/48134942
has text: @chrisz yes, can we also do that using regex? :)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83266470
comment on: http://stackoverflow.com/q/48142723
type: Comment
has text: That moment when you realize that you had your template files one level up and not actually in your template folders :( Thanks for the help anyways man.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48093413
has body: You're running Python in a virtual environment (venv), the packages you installed via pip cannot be found in this environment. At the project interpreter, click the plus (+) sign at the bottom and add your packages there. Click the + at the bottom Search for, and install your package
score: 7
upvote count: 7
answers question: http://stackoverflow.com/q/48093363
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48093363

http://stackoverflow.com/a/48060212
upvote count: 2
has body: As Daniel suggested ,use pass a dictionary object here to pass the key value pair and it would work .Your changed code would like the following . from elasticsearch import Elasticsearch from elasticsearch_dsl import Search es_client = Elasticsearch(['http://10.220.3.40'], port='9200') param1 = 'xyz' s = Search(using=es_client, index="index1", doc_type="sampledoc").filter("term", Key=param1) print("Query 1 :"+str(s.to_dict())) dictionary_variable = {"Key2":param1} s = Search(using=es_client, index="index1", doc_type="sampledoc").filter("term", ** dictionary_variable) print("Query 2 :"+str(s.to_dict()))
answers question: http://stackoverflow.com/q/48059289
accepted answer of: http://stackoverflow.com/q/48059289
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/48065819
accepted answer of: http://stackoverflow.com/q/48065117
answers question: http://stackoverflow.com/q/48065117
has comment: http://stackoverflow.com/comment/84340693
type: AcceptedAnswer
downvote count: 0
has body: The way to do this is to use the Resample function with fixed/arbitrary size and spacing. Below is a code snippet showing construction of this "reference_image" space: reference_origin = np.zeros(dimension) reference_direction = np.identity(dimension).flatten() reference_size = [128]*dimension # Arbitrary sizes, smallest size that yields desired results. reference_spacing = [ phys_sz/(sz-1) for sz,phys_sz in zip(reference_size, reference_physical_size) ] reference_image = sitk.Image(reference_size, data[0].GetPixelIDValue()) reference_image.SetOrigin(reference_origin) reference_image.SetSpacing(reference_spacing) reference_image.SetDirection(reference_direction) For a turnkey solution have a look at this Jupyter notebook which illustrates how to do data augmentation with variable sized images in SimpleITK (code above is from the notebook). You may find the other notebooks from the SimpleITK notebook repository of use too.
has comment: http://stackoverflow.com/comment/83106424
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/84294430
type: Answer
has comment: http://stackoverflow.com/comment/83109752

http://stackoverflow.com/comment/83264946
has text: The answer to your question is yes, though the details involving how to do so depend on your program.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48143377

http://stackoverflow.com/q/48016280
has comment: http://stackoverflow.com/comment/83002454
has comment: http://stackoverflow.com/comment/83081686
tagged with: python
has comment: http://stackoverflow.com/comment/83002403
has comment: http://stackoverflow.com/comment/83081653
type: Question
has comment: http://stackoverflow.com/comment/83002130
has answer: http://stackoverflow.com/a/48054866
linked to: http://stackoverflow.com/q/42280234
answer count: 1
has comment: http://stackoverflow.com/comment/83081661
has comment: http://stackoverflow.com/comment/83002444
score: 0
has comment: http://stackoverflow.com/comment/83002462
has title: Updating a object already in a group
tagged with: pygame
has body: I am attempting to create a bullet for my 2d shooter game. I have created the bullet and it is displayed on the screen when the user presses the left mouse button, however I must now make it move. Each bullet is added to the bullet group. What would be the easiest way to update the position of the bullet? This is the while loop. GameClass.Game.getevent is called, which states that if lmb is pressed, then the code below it will be run. while play: display.fill(WHITE) GameClass.Game.getevent(player1) platforms.draw(display) sprites.draw(display) bullets.draw(display) pygame.display.update() The following is part of a different file. The shoot function is part of the 'player' class, which has been cut off due to irrelevance. def shoot(self): bullet=Bullet(5,self.bullets,self.x,self.y) self.bullets.add(bullet) class Bullet(pygame.sprite.Sprite): def __init__(self,speed,bullets,x,y): super().__init__() self.speed=speed self.image=pygame.Surface((10,10)) self.rect=self.image.get_rect() self.bullets=bullets self.x=x self.y=y Bullet.movebullet(self) def movebullet(self): self.rect.center=((self.x+self.speed),self.y) What would be the best way of updating the position of each individual bullet in the group?
has comment: http://stackoverflow.com/comment/83019844
type: UnansweredQuestion

http://stackoverflow.com/q/48028391
upvote count: 0
has answer: http://stackoverflow.com/a/48028461
favorite count: 0
has title: Replace a character with all alphabet in a string and store the generate the output in a list with Python
linked to: http://stackoverflow.com/q/47983212
tagged with: python
tagged with: nlp
answer count: 4
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48028509
tagged with: list
has answer: http://stackoverflow.com/a/48028458
has answer: http://stackoverflow.com/a/48028439
has body: I want to replace each character in a string with all the alphabet and save the output in a list to work with it lately in a NLP project. For example var='abc' Output expected ['bbc','cbc','dbc','ebc',...,'aac','acc','adc','aec',...,'aba','abb','abd','abe'...] How can I do this with Python? Thanks /Tried some codes but no luck
downvote count: 1
possible better answer: http://stackoverflow.com/a/48028458
tagged with: alphabetical
type: Question
score: -1
has comment: http://stackoverflow.com/comment/83026902
has comment: http://stackoverflow.com/comment/83026900
accepted answer: http://stackoverflow.com/a/48028439

http://stackoverflow.com/comment/83280996
comment on: http://stackoverflow.com/q/48150823
has text: The server cannot close the connection, but the server can send a close message to clients. [Read this](https://en.wikipedia.org/wiki/Client%E2%80%93server_model)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83103680
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48064662
has text: @David apologies, fixed now. Please see my recent edit.
type: AnswerComment

http://stackoverflow.com/comment/83179743
comment on: http://stackoverflow.com/a/48102203
type: Comment
score: 1
type: AnswerComment
has text: Sure. Lists are a mutable data structure. And so there is no guarantee that the contents of a list does not change over time. That means it cannot be used in a hashing function (which the set uses). The tuple, on the other hand, is immutable, and hence hashable.

http://stackoverflow.com/comment/83067979
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48047731
type: Comment
has text: You don't need a custom user model for that. Just [write your own password validator](https://docs.djangoproject.com/en/2.0/topics/auth/passwords/#writing-your-own-validator) and add it to the `AUTH_PASSWORD_VALIDATORS`.

http://stackoverflow.com/comment/82999463
type: QuestionComment
type: Comment
has text: Yes I found it.
score: 0
comment on: http://stackoverflow.com/q/48015030

http://stackoverflow.com/comment/83134542
has text: @IljaEverilä Edited to remove `Node` ref and `back_populates`.
comment on: http://stackoverflow.com/q/48068573
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48061873
tagged with: python
has comment: http://stackoverflow.com/comment/83096800
tagged with: google-finance
answer count: 0
has comment: http://stackoverflow.com/comment/83096364
has comment: http://stackoverflow.com/comment/83096530
type: UnansweredQuestion
has title: How to update python googlefinance.client to 1.3.1?
type: Question
tagged with: ubuntu
score: 0
has body: Python's googlefinance.client has stopped working after Google changed hostname for finance. I need to update googlefinance.client to 1.3.1. How can I make my ubuntu upgrade googlefinance.client package to latest version? So far, I tried: sudo -H pip install googlefinance.client googlefinance --upgrade But it only updates to 1.3.0. Any help?

http://stackoverflow.com/comment/83005150
score: 1
type: QuestionComment
has text: @Ryan, I was thinking about `re.DEBUG` flag, but working with the `sre_parse.parse` is indeed easier. I didn't even know it was there. Thanks!
type: Comment
comment on: http://stackoverflow.com/q/48017666

http://stackoverflow.com/comment/83140669
type: QuestionComment
comment on: http://stackoverflow.com/q/48083081
type: Comment
has text: Can you post the code for how you did this with `dict`s?
score: 0

http://stackoverflow.com/a/48089117
has body: You should think of DataFrames as a collection of columns. Therefore when you do df[4] you get the 4th column of df, which is of type Pandas Series. Afer this when you do df[4][1] you get the 1st element of this Series, which corresponds to the 1st row and 4th column entry of the DataFrame, which is what df.iloc[1,4] does exactly. Therefore, no inconsistency at all, but beware: This will work only if you don't have any column names, or if your column names are [0,1,2,3,4]. Else, it will either fail or give you a wrong result. Hence, for positional indexing you must stick with iloc, or loc for name indexing.
answers question: http://stackoverflow.com/q/48088965
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/83152775
score: 2
accepted answer of: http://stackoverflow.com/q/48088965
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48130879
score: -1
upvote count: 0
has body: Try this from datetime import datetime def get_closes_time(current_time , list_of_times ): closest_time=list_of_times[0] FMT = '%I:%M:%S %p' for each in list_of_times: dif_1= abs(datetime.strptime(each, FMT) - datetime.strptime(current_time, FMT)) dif_2= abs(datetime.strptime(closest_time, FMT) - datetime.strptime(current_time, FMT)) if dif_1&lt;dif_2: closest_time=each return closest_time
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/48130188

http://stackoverflow.com/comment/83088650
type: Comment
has text: please add some sample code and some elements of your dataset in order to help
comment on: http://stackoverflow.com/q/48058044
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83220061
has text: @VivekKumar, thanks for providing the link. I will read it.
comment on: http://stackoverflow.com/q/48103882
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48066638
score: 0
accepted answer: http://stackoverflow.com/a/48071494
answer count: 1
has body: I have an input field that should save the content to a database: {% for comment in comments %} &lt;div class="row"&gt; {{ comment.content }} &lt;/div&gt; {% endfor %} &lt;div class="row"&gt; &lt;form action="." method="POST"&gt; &lt;textarea class="form-control" name="contents" placeholder="Enter a comment"&gt;&lt;/textarea&gt; &lt;input type="submit" class="btn btn-warning" value="save"&gt; &lt;/form&gt; &lt;/div&gt; in flask_app I check whether it is a POST or GET method. If it is POST it should reload the page with a redirect. However, it always returns me to "home". @app.route('/photography', methods=["GET", "POST"]) def show_photography(): if request.method == "GET": return render_template('photography.html', comments=Comment.query.all()) elif request.method == "POST": comment = Comment(content=request.form["contents"]) db.sesson.add(comment) db.session.commmit() return 'welcome to flask!' else: flash('error message via flash') return 'welcome to flaks' was just a test, it still redirects me to home after clicking the button. Can anyone help me?
tagged with: http-redirect
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48071494
has title: Flask button redirects falsely to index
type: Question
tagged with: flask

ipython-parallel
type: Tag
tag name: ipython-parallel
tags question: http://stackoverflow.com/q/48161810

http://stackoverflow.com/comment/83195316
type: Comment
has text: @Miguel the `add(ImageProcessor p)` method does probably not exist, because of the ambiguity for different images types (grey, rgb, etc., see https://imagej.nih.gov/ij/developer/api/ij/process/ImageProcessor.html#getNChannels--)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48102357

http://stackoverflow.com/q/48142682
upvote count: 1
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
has comment: http://stackoverflow.com/comment/83263537
has comment: http://stackoverflow.com/comment/83263577
type: UnansweredQuestion
tagged with: mime-types
tagged with: python
has title: Extract embedded pdf document from a webpage
has body: I am trying to write a Python program that is able to extract a PDF file that is embedded in a website, e.g., in a PDF viewer. However, I haven't yet been able to find a robust way to accomplish this. Is there a way or best practice to identify PDFs based on MIME-type maybe?
has comment: http://stackoverflow.com/comment/83263608
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/312230
type: Question
has comment: http://stackoverflow.com/comment/83263503
favorite count: 0
linked to: http://stackoverflow.com/q/26230485
has answer: http://stackoverflow.com/a/48142826

http://stackoverflow.com/q/48145435
tagged with: python
has comment: http://stackoverflow.com/comment/83269069
tagged with: keyerror
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48145980
upvote count: 2
downvote count: 2
linked to: http://stackoverflow.com/q/1373164
type: Question
has title: Creating variables from list and accessing globally
possible better answer: http://stackoverflow.com/a/48236873
has answer: http://stackoverflow.com/a/48236873
has body: I’m writing a program that pulls a list of departments from a database. I want to avoid hardcoding this since the list may change. I want to create a variable for each department to populate questions into a GUI. The problem I have is that I can create variables from the database list using the vars() function. I’m then storing the list of variable names so I can reference them elsewhere in my program. As long as I do everything in the same def, there is no problem. But I don’t know how to reference the dynamically created variables in a separate function. Since I won’t know the variable names ahead of time, I don’t know how to make them available in other functions. deptList = ['deptartment 1', 'deptartment 2', 'deptartment 3', 'deptartment 4', 'deptartment4'] varList=[] def createVariables(): global varList for i in range(len(deptList)): templst=deptList[i].replace(' ', '') varList.append(templst+'Questions') globals()['{}'.format(varList[i])] = [] def addInfo(): global varList print('varlist',vars()[varList[1]]) #Keyerror createVariables() print(varList) vars()[varList[1]].append('This is the new question') print('varlist',vars()[varList[1]]) #Prints successfully addInfo()
has comment: http://stackoverflow.com/comment/83269807
has comment: http://stackoverflow.com/comment/83269106
answer count: 2
has answer: http://stackoverflow.com/a/48145980
tagged with: variables
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/83269107

http://stackoverflow.com/q/48125278
tagged with: javascript
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/83227607
has comment: http://stackoverflow.com/comment/83227625
accepted answer: http://stackoverflow.com/a/48125542
tagged with: python
has title: Vue.js in Django Templates
tagged with: django-templates
tagged with: django
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48125542
has comment: http://stackoverflow.com/comment/83227704
has answer: http://stackoverflow.com/a/59444714
type: Question
upvote count: 4
answer count: 2
has body: I am trying to use Vue.js in Django templates. One such template is the following: {% load static %} Hello message I changed Vue's interpolation delimiters to [[ ]] to avoid conflict with Django. My script.js looks as follows: $(function() { var app = new Vue({ el: '#myApp', delimiters: ['[[', ']]'], data: { message: 'Hello, world!' } }); }); Unfortunately, the HTML rendered contains message . Has anyone else faced a similar issue?
tagged with: vue.js
possible better answer: http://stackoverflow.com/a/59444714
downvote count: 0

http://stackoverflow.com/comment/83130410
type: AnswerComment
comment on: http://stackoverflow.com/a/48078169
has text: Hmmm, i see problem in `Sample Output:` - is guaranteed unique `item_code`? If not how it match? I get NaN because working with your sample data.
type: Comment
score: 0

http://stackoverflow.com/comment/83078486
type: QuestionComment
comment on: http://stackoverflow.com/q/48053139
score: 3
has text: you could give `abs()` a try .... [doku](https://docs.python.org/3/library/functions.html#abs)
type: Comment

http://stackoverflow.com/comment/83226903
comment on: http://stackoverflow.com/q/48120106
score: 0
type: Comment
type: QuestionComment
has text: Ok, to follow up on @KirkBroadhurst's comment `[1s] [3e] [2s] [4e] [3s] [5e]` would be legal and should result in `[1s] [2s] [4e] [5e]`? Meaning the end points to merge may be non-adjacent?

http://stackoverflow.com/q/48016194
type: Question
tagged with: numpy
tagged with: theano
has comment: http://stackoverflow.com/comment/83003698
downvote count: 0
has title: Converting PyMC2 ERGMs example to PyMC3: different results
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/32304160
has comment: http://stackoverflow.com/comment/83021225
answer count: 0
tagged with: pymc3
score: 1
has body: I'm trying to convert this PyMC2 example of an ERGM to PyMC3. Using the documentation and other examples, I have come up with this code. It runs without throwing errors, but gives the wrong answers (the estimates are ~0). This first part is just setup: it is almost identical to the tutorial and works correctly. import pymc3 as pm import networkx as nx import csv import theano.tensor as tt from theano.compile.ops import as_op with open("grey_adjacency.tsv") as f: first_line = f.readline() adj = np.loadtxt("grey_adjacency.tsv", delimiter="\t",skiprows=1, usecols=list(range(1,45))) G = nx.from_numpy_matrix(adj) names = [name.strip() for name in first_line.split("\t")[1:]] G = nx.relabel_nodes(G, {i: names[i] for i in range(44)}) node_attributes = [] with open("grey_nodes.tsv") as f: reader = csv.DictReader(f, dialect=csv.excel_tab) for row in reader: node_attributes.append(row) for node in node_attributes: name = node["name"] for key, val in node.items(): if key == "name": continue G.node[name][key] = val matrix = nx.to_numpy_matrix(G) matrix[np.triu_indices_from(matrix)] = 0 def edge_count(G): size = len(G) ones = np.ones((size, size)) # Zero out the upper triangle: if not G.is_directed(): ones[np.triu_indices_from(ones)] = 0 return ones def node_match(G, attrib): size = len(G) attribs = [node[1][attrib] for node in G.nodes(data=True)] match = np.zeros(shape=(size, size)) for i in range(size): for j in range(size): if i != j and attribs[i] == attribs[j]: match[i,j] = 1 if not G.is_directed(): match[np.triu_indices_from(match)] = 0 return match # Create the gender-match matrix gender_match_mat = node_match(G, "sex") This next part is where I am having trouble converting the old PyMC2 code to use PyMC3: @as_op(itypes=[tt.dmatrix, tt.dmatrix], otypes=[tt.dmatrix]) def probs(t1, t2): probs = 1/(1+np.exp(-1*sum([t1, t2]))) probs[np.diag_indices_from(probs)] = 0 probs[np.triu_indices_from(probs)] = 0 return probs with pm.Model(): density_coef = pm.Normal("density", mu=0, sd…
upvote count: 1

http://stackoverflow.com/comment/83220687
has text: Thanks Dan, but i'd also like the section identifier in each list entry as well if that's posslbe
type: AnswerComment
comment on: http://stackoverflow.com/a/48121946
score: 0
type: Comment

http://stackoverflow.com/q/48088582
has answer: http://stackoverflow.com/a/48088597
has answer: http://stackoverflow.com/a/48098949
linked to: http://stackoverflow.com/q/15564844
type: AnsweredQuestion
score: 7
tagged with: web-scraping
upvote count: 7
tagged with: scrapy
type: Question
accepted answer: http://stackoverflow.com/a/48098949
linked to: http://stackoverflow.com/q/11528739
has answer: http://stackoverflow.com/a/48088675
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/11707879
has body: I'm trying to build a system to run a few dozen Scrapy spiders, save the results to S3, and let me know when it finishes. There are several similar questions on StackOverflow (e.g. this one and this other one), but they all seem to use the same recommendation (from the Scrapy docs): set up a CrawlerProcess, add the spiders to it, and hit start(). When I tried this method with all 325 of my spiders, though, it eventually locks up and fails because it attempts to open too many file descriptors on the system that runs it. I've tried a few things that haven't worked. What is the recommended way to run a large number of spiders with Scrapy? Edited to add: I understand I can scale up to multiple machines and pay for services to help coordinate (e.g. ScrapingHub), but I'd prefer to run this on one machine using some sort of process pool + queue so that only a small fixed number of spiders are ever running at the same time.
has title: Running dozens of Scrapy spiders in a controlled manner
favorite count: 0
possible better answer: http://stackoverflow.com/a/48088597
tagged with: python

http://stackoverflow.com/comment/83028122
type: QuestionComment
comment on: http://stackoverflow.com/q/48028950
score: 0
type: Comment
has text: @JonClements lol sorry, a typo. Let me change it.

http://stackoverflow.com/comment/83568324
has text: The `sam local invoke "HelloWorld" -e event.json` command is going to spin up a docker container and communicate with it. I am curious if that communication is done on the same port as `sam local api`.
comment on: http://stackoverflow.com/a/48289387
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83278416
has text: **why?** Sounds like an [xy problem](http://xyproblem.info). What are you *actually* trying to achieve.
type: QuestionComment
type: Comment
score: 3
comment on: http://stackoverflow.com/q/48150091

http://stackoverflow.com/q/48129123
favorite count: 0
has comment: http://stackoverflow.com/comment/83234987
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89424833
tagged with: django-channels
tagged with: django
has body: According to the Django channel docs, You get access to a user’s normal Django session using the http_session decorator - that gives you a message.http_session attribute that behaves just like request.session. You can go one further and use http_session_user which will provide a message.user attribute as well as the session attribute. Is there anyway I can set a session variable like so? I did try it, and I get an error saying NoneType is not iterable. if 'username' not in message.http_session: message.http_session['username'] = 'temp' In other words, message.http_session returns a NoneType. I've tried using the decorators @http_session and @channel_session_user_from_http, but they didn't help either.
tagged with: python
type: Question
has title: Set Django session variables through channels (http_session)
score: 2
has answer: http://stackoverflow.com/a/61648709
tagged with: session
downvote count: 0
tagged with: channel
answer count: 1

http://stackoverflow.com/q/48031568
type: UnansweredQuestion
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/31376043
type: Question
has comment: http://stackoverflow.com/comment/83033518
has title: How to append a database table created by a django model
tagged with: database
has body: I am following the tutorials https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html on making a simple user registration website. The key model defined in model.py is from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() which creates the table profile in the database. My question is how do we append this table to include information like user's first/last name and email. I know those information is stored in auth_user, but it would nice to have everything on one table. I am new to django platform. Any explanation or reference is greatly appreciated.
tagged with: postgresql
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83033419
has answer: http://stackoverflow.com/a/48031885

http://stackoverflow.com/comment/83254320
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48137976
has text: Not really.... if you check for all the standard keras loss function, they only apply the mean on the last axis as well. This allows you to further use their functions with balance coefficients and other stuff.
score: 0

http://stackoverflow.com/comment/83087439
comment on: http://stackoverflow.com/a/48057622
type: Comment
has text: What's the purpose of the `zip` here? Just `for book in books: shutil.move(book, 'DirHtml')` would be a lot simpler, clearer, and more efficient.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83092676
score: 0
comment on: http://stackoverflow.com/q/48052562
has text: a little update : i managed to install the package, (needed apt-get upgrade..) but when i try to import that package it doesnt recognize it. "no module named alsaaudio..."
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48162230
has comment: http://stackoverflow.com/comment/83304293
downvote count: 0
has comment: http://stackoverflow.com/comment/83304183
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/35157367
has comment: http://stackoverflow.com/comment/83304404
upvote count: 3
has body: I want to search for pre-defined list of keywords in a given article and increment the score by 1 if keyword is found in article. I want to use multiprocessing since pre-defined list of keyword is very large - 10k keywords and number of article is 100k. I came across this question but it does not address my question. I tried this implementation but getting None as result. keywords = ["threading", "package", "parallelize"] def search_worker(keyword): score = 0 article = """ The multiprocessing package also includes some APIs that are not in the threading module at all. For example, there is a neat Pool class that you can use to parallelize executing a function across multiple inputs.""" if keyword in article: score += 1 return score I tried below two method but getting three None as result. Method1: pool = mp.Pool(processes=4) result = [pool.apply(search_worker, args=(keyword,)) for keyword in keywords] Method2: result = pool.map(search_worker, keywords) print(result) Actual output: [None, None, None] Expected output: 3 I think of sending the worker the pre-defined list of keyword and the article all together, but I am not sure if I am going in right direction as I don't have prior experience of multiprocessing. Thanks in advance.
has comment: http://stackoverflow.com/comment/83304000
has comment: http://stackoverflow.com/comment/83303856
type: Question
tagged with: python-multiprocessing
tagged with: multiprocessing
score: 3
has comment: http://stackoverflow.com/comment/83303969
has comment: http://stackoverflow.com/comment/83303928
has title: How to share data between all process in Python multiprocessing?
has answer: http://stackoverflow.com/a/48173479
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/48192658

http://stackoverflow.com/comment/83106493
comment on: http://stackoverflow.com/q/48062717
has text: `for i in range (0,r): maker.right(n)` performs the same rotation as `rn = r * n; maker.right(rn)`, except the 2nd version is much more efficient, especially when `r` is large. Also `maker2.right(n*-1)` should be written as `maker2.right(-n)`, or in the no-loop version `maker2.right(-rn)`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83137724
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48079643
has text: What does setting (recursive=False) do in the code?
type: AnswerComment

http://stackoverflow.com/q/48090998
duplicate of: http://stackoverflow.com/q/26752464
linked to: http://stackoverflow.com/q/14762181
has title: Double y axis with matching gridlines
downvote count: 0
has answer: http://stackoverflow.com/a/48092183
type: Question
type: AnsweredQuestion
tagged with: matplotlib
linked to: http://stackoverflow.com/q/26752464
linked to: http://stackoverflow.com/q/12608788
has body: I'd like to produce a matplotlib line chart with two variables displayed on two separate y axes with matching gridlines. That's all pretty straight forward except the matching gridlines part. Below are some reproducible snippets including by best attempts. A complete snippet can be found at the very end. Reproducible data frame with initial plot Following the suggestions from Adding a y-axis label to secondary y-axis in matplotlib I'm able to produce this: import pandas as pd import numpy as np import matplotlib.pyplot as plt # Dataframe with some random numbers np.random.seed(123) rows = 4 df = pd.DataFrame(np.random.randint(90,110,size=(rows, 2)), columns=list('AB')) datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist() df['dates'] = datelist df = df.set_index(['dates']) df.index = pd.to_datetime(df.index) df['B'] = df['A'] * np.random.uniform(0.6,1.4, size = 4) # Plot 1 fig, ax = plt.subplots() t = df.index ax.plot(t, df['A']) ax2 = ax.twinx() ax2.plot(t, df['B'], color='red') ax2.yaxis.grid(which="major", color='green', linestyle='--') ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.show() Plot 1 As you can see, matplotlib selects sensible intervals for both variables, but the gridlines for the y axes don't match very well. Following the suggestions from Align secondary y-axis ticks with stripplot on primary x-axis I'm able to align them, but that naturally leaves out some values: Plot 2 # Plot 2 fig, ax = plt.subplots() t = df.index ax.plot(t, df['A']) ax2 = ax.twinx() ax2.plot(t, df['B'], color='red') #-- ax2.set_ylim(ax.get_ylim()) ax2.yaxis.grid(which="major", color='green', linestyle='--') ax.legend(loc='upper left') ax2.legend(loc='upper right') plt.show() My next attempt was to retrieve the interval of the secondary y axis using ax2int = ax2.get_ylim()[1] - ax2.get_ylim()[0] and divide it by the number of gridlines on the primary axis to make them match. And then follow the suggestions from Changing th…
score: 5
has comment: http://stackoverflow.com/comment/83158278
answer count: 1
linked to: http://stackoverflow.com/q/46631419
favorite count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/83161189
tagged with: python
accepted answer: http://stackoverflow.com/a/48092183

http://stackoverflow.com/comment/83160306
type: AnswerComment
type: Comment
has text: I tried but the same error occurs. I know this way to create tables manually.
comment on: http://stackoverflow.com/a/48092195
score: 0

joystick
type: Tag
tags question: http://stackoverflow.com/q/48032472
tag name: joystick

http://stackoverflow.com/comment/83315480
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48166533
has text: @yok, as i already said before that error means that the `value` (Y-axis) column (`count` in your case) has non-numeric dtype (object, datetime, etc.)

http://stackoverflow.com/q/48021121
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83011899
linked to: http://stackoverflow.com/q/45684275
type: Question
has body: This question is similar to this one, but there is a difference: here instead of a single value, I have a list of values in one column of dataframe. Let's say we have a pandas dataframe with one column named words. It contains the index of words which are available in a document. For example, in the following dataframe, there are two documents where the first one contains words ['a','b'] and the second contains ['a','c','d']. df = pd.DataFrame() df['words'] = [['a','b'],['a','c','d']] I want to convert the words column to different binary columns, one column for each word. The above dataframe will be converted to: df['a'] = [True, True] df['b'] = [True, False] df['c'] = [False, True] df['d'] = [False, True] For now, I have the following code, where it iterates over different words w available in the words column. df[w] = [w in word_list for word_list in df['words']] Obviously, it is very slow. Is there an efficient way to do this?
has answer: http://stackoverflow.com/a/48021192
duplicate of: http://stackoverflow.com/q/45684275
tagged with: dataframe
score: 0
answer count: 1
has title: Efficient way to do a kind of one-hot coding in pandas
accepted answer: http://stackoverflow.com/a/48021192
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/83263201
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48141761
has text: you use `Tk` in `POS`, `MasterFilePopUp()` and `popupmsg`. You can also use second `mainloop` in `popupmsg`. And you run `MasterFilePopUp` before `POS` so it runa `mailoop()` automatically. And it makes problem.

http://stackoverflow.com/comment/83115441
has text: Many thanks. I am using lxml.clean and it is stripping out a lot of this and seems to be one popular sanitizer.. But I will also checkout the others you mentioned. Btw, when you say 'iframe breakout' what do you mean ? Also I am thinking of 'sandbox'ing the iframe - is that generally recommended in such cases ?
type: Comment
comment on: http://stackoverflow.com/a/48051716
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83341130
has text: Further note that, `mb['menu'] = submenu` is practically singular option configuration equivalent of `mb.config(menu=submenu)` and `mb.configure(menu=submenu)`.
comment on: http://stackoverflow.com/a/48166688
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/a/48118131
type: Answer
answers question: http://stackoverflow.com/q/48116484
downvote count: 1
has body: The actual kernel values are learned during the learning process, that's why you only need to set the number of kernels and their size. What might be confusing is that the learned kernel values actually mimic things like Gabor and edge detection filters. These are generic to many computer vision applications, but instead of being engineered manually, they are learned from a big classification dataset (like ImageNet). Also the kernel values are part of a feature hierarchy that can be used directly as features for a variety of computer vision problems. In that terms they are also generic.
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83215491

http://stackoverflow.com/comment/83231102
type: QuestionComment
has text: I see no threading in that code. Read the following: https://wiki.wxpython.org/LongRunningTasks
score: 0
comment on: http://stackoverflow.com/q/48113110
type: Comment

http://stackoverflow.com/comment/83075879
score: 2
comment on: http://stackoverflow.com/a/48051213
type: AnswerComment
has text: What part of this do you not understand? How did you try to implement it, and where did it go wrong?
type: Comment

http://stackoverflow.com/a/48026720
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48026545
answers question: http://stackoverflow.com/q/48026545
upvote count: 1
has body: Is there any way to use the value of an argument to dynamically set the default of a keyword argument? Unfortunately no. This can be shown with a simpler example: &gt;&gt;&gt; def func(a, b=a): return a, b Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; def func(a, b=a): NameError: name 'a' is not defined As said in the comments, Python keyword argument values are evaluated when the function is defined, but the value of any arguments are not know until the function is called. Thus, something like this in Python simply isn't feasible. However, you can make your code more compact by using the ternary operator: def foo(lst, r=0, l=None): l = l if l is not None else len(lst) print(r, l)
type: Answer
has comment: http://stackoverflow.com/comment/83024046
downvote count: 0

http://stackoverflow.com/q/48168862
has comment: http://stackoverflow.com/comment/83317013
has answer: http://stackoverflow.com/a/48168941
score: -1
tagged with: date
type: Question
answer count: 1
has body: I am pretty new to python below is java code for converting that I wrote for converting a date obj to ISO format. I want similar code for python I have searched a long and tried few solutions but none of them have worked so far. private String getISOTimestamp(Long timeStamp) { Date date = new Date(timeStamp); String pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'"; SimpleDateFormat sdf = new SimpleDateFormat(pattern); String isoTS = sdf.format(date); return isoTS; }
favorite count: 0
accepted answer: http://stackoverflow.com/a/48168941
tagged with: datetime
tagged with: python
has title: python ISO 8601 format
downvote count: 2
upvote count: 1
tagged with: timestamp
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83324041
has comment: http://stackoverflow.com/comment/83317262

http://stackoverflow.com/comment/83120445
has text: Both are constants, and yeah, `set` ~ `HashSet` and `dict` is `HashTable`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48073380
type: QuestionComment

http://stackoverflow.com/q/48171283
has comment: http://stackoverflow.com/comment/83322151
type: Question
has comment: http://stackoverflow.com/comment/83322671
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83324673
has comment: http://stackoverflow.com/comment/83325037
has body: We have the x and y values, and I am taking their log, by logx = np.log10(x) and logy = np.log10(y). I am trying to compute the derivative of logy w.r.t logx, so dlogy/dlogx. I used to do this successfully using numpy gradient, more precisely derivy = np.gradient(logy,np.gradient(logx)) but for some strange reason it doesn't seem to work anymore yielding the error: "Traceback (most recent call last): File "derivlog.py", line 79, in &lt;module&gt; grady = np.gradient(logy,np.gradient(logx)) File "/usr/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 1598, in gradient raise ValueError("distances must be scalars") ValueError: distances must be scalars" Context: When trying to detect power-laws, of the kind y ~ x^t, given the values of y as a function of x, one wants to exctract essentially the power t, so we take logs which gives log y ~ t*log x and then take the derivative in order to extract t. Here's a minimal example for recreating the problem: x=[ 3. 4. 5. 6. 7. 8. 9. 10. 11.] y = [ 1.05654 1.44989 1.7939 2.19024 2.62387 3.01583 3.32106 3.51618 3.68153] Are there other (more suited) methods in python for taking such numerical derivatives?
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/83322107
has comment: http://stackoverflow.com/comment/83323020
answer count: 1
has comment: http://stackoverflow.com/comment/83324587
has answer: http://stackoverflow.com/a/48172836
accepted answer: http://stackoverflow.com/a/48172836
has comment: http://stackoverflow.com/comment/83322347
has comment: http://stackoverflow.com/comment/83325260
has comment: http://stackoverflow.com/comment/83324191
has comment: http://stackoverflow.com/comment/83322584
tagged with: python
has title: Derivative of log plot in python
has comment: http://stackoverflow.com/comment/83323821
tagged with: derivative
has comment: http://stackoverflow.com/comment/83323065

http://stackoverflow.com/a/48044403
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48041609
downvote count: 0
has body: hum, if you try to get it run with PyQt4, maybe "pip uninstall PyQt5", and even remove directory "python-3.6.4.amd64\Lib\site-packages\PyQt5" manually after that.

http://stackoverflow.com/a/48055440
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83102034
accepted answer of: http://stackoverflow.com/q/48055379
type: Answer
answers question: http://stackoverflow.com/q/48055379
has comment: http://stackoverflow.com/comment/83109352
has body: It's easier to see what's happening if you break down the steps. Instead of self.my_df.loc[2, "B"] = "x" consider temp = self.my_df # Clearly this should call the get method temp.loc[2, "B"] = "x" # Changes the pandas object These two snippets achieve the same result. The setter will not be called, since you are not assigning to the my_df property of the my_obj object. You are retrieving the contents of self.my_df (which is a dataframe), and then manipulating it. A my_obj object only holds a reference to a DataFrame, so unless you point my_df to a different object, the setter will not be called. With your code, the my_obj object still points to the same dataframe, but you have manipulated the dataframe's contents.
score: 0

http://stackoverflow.com/q/48130929
has title: How to compare a python dictionary key with a part of another dictionary's key? something like a .contains() function
upvote count: 1
type: Question
score: 1
possible better answer: http://stackoverflow.com/a/48131022
answer count: 2
has answer: http://stackoverflow.com/a/48131022
has answer: http://stackoverflow.com/a/48131007
downvote count: 0
favorite count: 0
tagged with: compare
tagged with: python
tagged with: dictionary
has body: Most of my small-scale project worked fine using dictionaries, so changing it now would basically mean starting over. Let's say I have two different dictionaries(dict1 and dict2). One being: {'the dog': 3, 'dog jumped': 4, 'jumped up': 1, 'up onto': 8, 'onto me': 13} Second one being: {'up': 12, 'dog': 22, 'jumped': 33} I want to find wherever the first word of the first dictionary is equal to the word of the second one. These 2 dictionaries don't have the same length, like in the example. Then after I find them, divide their values. So what I want to do, sort of using a bit of Java is: for(int i = 0;i&lt;dict1.length(),i++){ for(int j = 0;j&lt;dict2.length(),j++){ if(dict1[i].contains(dict2[j]+" ") // not sure if this works, but this // would theoretically remove the // possibility of the word being the // second part of the 2 word element dict1[i] / dict2[j] What I've tried so far is trying to make 4 different lists. A list for dict1 keys, a list for dict1 values and the same for dict2. Then I've realized I don't even know how to check if dict2 has any similar elements to dict1. I've tried making an extra value in the dictionary (a sort of index), so it would kind of get me somewhere, but as it turns out dict2.keys() isn't iterable either. Which would in turn have me believe using 4 different lists and trying to compare it somehow using that is very wrong.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48131007

http://stackoverflow.com/a/48129284
score: 4
upvote count: 4
downvote count: 0
type: Answer
has body: I just learned about PEP 518 -- Specifying Minimum Build System Requirements for Python Projects that addresses this exact problem. In short, this accepted PEP proposes to store dependencies in TOML format, in a file named pyproject.toml. For most Python projects the contents of this file will be: [build-system] # Minimum requirements for the build system to execute. requires = ["setuptools", "wheel"] # PEP 508 specifications. In the case of this specific question, we just need to replace "setuptools" with "setuptools&gt;=36.2.1". The bad news is that pip does not support this yet. The good news is that it is implemented and will probably be shipped with pip 9.1.
answers question: http://stackoverflow.com/q/48048745

http://stackoverflow.com/q/48070944
accepted answer: http://stackoverflow.com/a/48071003
tagged with: python
has title: deleting specific strings python
type: AnsweredQuestion
type: Question
tagged with: numpy
answer count: 1
has body: I have the following in a python 3 numpy.ndarray: {"_id" : "123", "text" : "some writing"} {"_id" : "456", "text" : "some more writing"} {"_id" : "789", "text" : "some more more writing"} Question: How do I delete {"_id" : and "text" : to get the following: {"123", "some writing"} {"456", "some more writing"} {"789", "some more more writing"}
has answer: http://stackoverflow.com/a/48071003
score: 0
has comment: http://stackoverflow.com/comment/83115568
has comment: http://stackoverflow.com/comment/83115565

http://stackoverflow.com/comment/84282117
score: 7
type: AnswerComment
comment on: http://stackoverflow.com/a/48642005
type: Comment
has text: That means you're testing multiple things in one test. Don't do this. In one test, test up to the first failure point to make sure it's working. In another test, run the same setup, but don't check for that failure, (another test is taking care of that), check for the next failure instead. And so on. This could also be evidence that the function you're testing is too large.

http://stackoverflow.com/a/48137149
has comment: http://stackoverflow.com/comment/83254588
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83254523
has comment: http://stackoverflow.com/comment/83263218
has comment: http://stackoverflow.com/comment/83263391
has comment: http://stackoverflow.com/comment/83263145
has comment: http://stackoverflow.com/comment/83254097
has comment: http://stackoverflow.com/comment/83254574
has comment: http://stackoverflow.com/comment/83253613
has comment: http://stackoverflow.com/comment/83254579
upvote count: 1
has comment: http://stackoverflow.com/comment/83254167
has comment: http://stackoverflow.com/comment/83253852
answers question: http://stackoverflow.com/q/48136811
has body: I can't replicate - it works for me. Here are possible issues: Did you clone/download the entire pyttrex project? Is your average_true_range.py file still in the same folder (pyttrex/pytrrex) as your __init__.py file? Is the first defined function in __init__.py still: def ohlc(*args, **kwargs): Or have you removed or altered the name of the function? Have you edited any of the files to create or import a different function, variable, etc. named ohlc that could cause a name conflict with the import statement in average_true_range.py?
type: Answer
has comment: http://stackoverflow.com/comment/83255009
has comment: http://stackoverflow.com/comment/83258961
has comment: http://stackoverflow.com/comment/83264299

http://stackoverflow.com/q/48042757
favorite count: 0
tagged with: python
type: UnansweredQuestion
downvote count: 1
has title: Python path rules
score: -1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/48042835
answer count: 1
tagged with: pythonpath
has comment: http://stackoverflow.com/comment/83056174
has body: I've started a project using Object Oriented Programming but I have some trouble understanding some basic rules about paths. Here's the arborescence of my project: Project/ main.py classes/ Database.py database/ Project.db main.py import sys sys.path.insert(0, 'classes/') from Database import Database Database.py import sys sys.path.insert(0, '../database/') import sqlite3 # in my Database class def connect(self): self.conn = sqlite3.connect('database/{}.db'.format(self.name)) self.c = self.conn.cursor() Instantiation in main.py VS in Database.py ProjectDatabase = Database('Project') ProjectDatabase.connect() If I make the instantiation in the main.py file and run it then I don't need to change anything in the Database.py file. But, if I make the instantiation in the Database.py file and run it then I need to change the connect method to this : def connect(self): self.conn = sqlite3.connect('../database/{}.db'.format(self.name)) self.c = self.conn.cursor() I don't understand why I need to do that and why I don't have to change the sys.path.insert() command in Database.py if I make the instantiation in the main.py file... Why shouldn't it be just sys.path.insert('database/') instead ? I hope I'm being clear here, I just don't get how we should write paths inside our scripts depending on what script we intend to run and depending on if there are embedded scripts into others such as classes call into a main program. Thanks for your explanations!

http://stackoverflow.com/comment/83262253
type: Comment
comment on: http://stackoverflow.com/a/48141963
type: AnswerComment
has text: I tried this way too, same error. Django, htmlib and other dependences is installed just fine but as I said, there is no django_bleach folder in the lib directory as when it is installed via pip install django-bleach. I will update my question listing the lib folder
score: 0

http://stackoverflow.com/comment/83027337
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48028416
has text: I don't understand why you don't use something like [this](https://docs.scipy.org/doc/scipy-0.19.1/reference/generated/scipy.interpolate.InterpolatedUnivariateSpline.html) for example.

http://stackoverflow.com/comment/83234278
has text: @K.Wanter Unfortunately I have no experience with `pdb`. Maybe you could give [this](https://stackoverflow.com/questions/10140198/python-debugger-pdb-stopped-handlying-up-down-arrows-shows-a-instead) a try.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48124236
type: Comment

http://stackoverflow.com/a/76090447
answers question: http://stackoverflow.com/q/48053979
has body: This code will work for variable lengths of lists too: a = ['aaaaaaa', 'b', 'c'] b = ['1', '000000000000', '0', '2'] max_a = max(len(x) for x in a) max_b = max(len(y) for y in b) if len(a)>len(b): new_b = b + [' ']*(len(a)-len(b)) for i in range(len(a)): print(f"{a[i]:{max_a}}|{new_b[i]:{max_b}}") else: new_a = a + [' ']*(len(b)-len(a)) for j in range(len(b)): print(f"{new_a[j]:{max_a}}|{b[j]:{max_b}}") Output: aaaaaaa|1 b |000000000000 c |0 |2
has comment: http://stackoverflow.com/comment/134228826
score: 0
type: Answer

http://stackoverflow.com/a/48073492
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83252858
upvote count: 7
answers question: http://stackoverflow.com/q/48072098
score: 7
has body: python has built in support for file operations: https://docs.python.org/2/library/stdtypes.html#bltin-file-objects instead of print(message) you can do: file_path = '/example/file.txt' #choose your file path with open(file_path, "w") as output_file: output_file.write(message + "\n") note that the + "\n" is so that each message will be written to a new line in the file since python won't put it there on its own
accepted answer of: http://stackoverflow.com/q/48072098
has comment: http://stackoverflow.com/comment/83150741

http://stackoverflow.com/a/48101205
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48073635
answers question: http://stackoverflow.com/q/48073635
score: 5
type: AcceptedAnswer
upvote count: 5
has body: To use role based authentication you need to add a second check after the password step is passed. You have two options. The more straightforward is to add the role check in each of your endpoint functions. If you want something more sophisticated that avoids code duplication, then you can define a custom decorator, such as the one I have used here: https://github.com/miguelgrinberg/flasky/blob/master/app/decorators.py. You will need to adapt it to use your own user object instead of current_user, but other than that this is a good example: def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator So then in your route, you do this: @app.route('/api/something') @auth.login_required @permission_required('admin') def something(): pass
type: Answer

http://stackoverflow.com/q/48158984
downvote count: 1
type: Question
score: 3
has comment: http://stackoverflow.com/comment/83297714
has comment: http://stackoverflow.com/comment/83297654
has comment: http://stackoverflow.com/comment/83297657
has comment: http://stackoverflow.com/comment/83297631
tagged with: dataframe
tagged with: multi-index
has answer: http://stackoverflow.com/a/48159101
has comment: http://stackoverflow.com/comment/83297691
has title: Using df.query on MultiIndex gives UndefinedVariableError
upvote count: 4
has comment: http://stackoverflow.com/comment/83297670
answer count: 1
accepted answer: http://stackoverflow.com/a/48159101
favorite count: 0
has comment: http://stackoverflow.com/comment/85886445
tagged with: pandas
has comment: http://stackoverflow.com/comment/85884817
tagged with: python
has comment: http://stackoverflow.com/comment/85886460
type: AnsweredQuestion
has body: I have two dataframes df Out[162]: colA colB L0 L1 L2 A1 B1 C1 1 2 C2 3 4 B2 C1 5 6 C2 7 8 A2 B3 C1 9 10 C2 11 12 B4 C1 13 14 C2 15 16 df1 Out[166]: rate from to CHF CHF 1.000000 MXN 19.673256 ZAR 0.000000 XAU 0.000775 THB 32.961405 When I did df.query('L0=="A1" &amp; L2=="C1"') Out[167]: colA colB L0 L1 L2 A1 B1 C1 1 2 B2 C1 5 6 Which give me back the expected out put . Then I want to apply the same function in df1 df1.query('ilevel_0=="CHF" &amp; ilevel_1=="MXN"') and df1.query('from=="CHF" &amp; to=="MXN"') Both failed What happened here ? Data Input : #df {'colA': {('A1', 'B1', 'C1'): 1, ('A1', 'B1', 'C2'): 3, ('A1', 'B2', 'C1'): 5, ('A1', 'B2', 'C2'): 7, ('A2', 'B3', 'C1'): 9, ('A2', 'B3', 'C2'): 11, ('A2', 'B4', 'C1'): 13, ('A2', 'B4', 'C2'): 15}, 'colB': {('A1', 'B1', 'C1'): 2, ('A1', 'B1', 'C2'): 4, ('A1', 'B2', 'C1'): 6, ('A1', 'B2', 'C2'): 8, ('A2', 'B3', 'C1'): 10, ('A2', 'B3', 'C2'): 12, ('A2', 'B4', 'C1'): 14, ('A2', 'B4', 'C2'): 16}} #df1 {'rate': {('CHF', 'CHF'): 1.0, ('CHF', 'MXN'): 19.673256, ('CHF', 'THB'): 32.961405, ('CHF', 'XAU'): 0.000775, ('CHF', 'ZAR'): 0.0}}
has comment: http://stackoverflow.com/comment/83297731
has comment: http://stackoverflow.com/comment/83297720

http://stackoverflow.com/comment/83147014
has text: If you just want to check if the x or y position of your sprite is past the point, do something like: `if mysprite.get_position()[0] > -100:`. You can't just [compare some tuples](https://stackoverflow.com/q/5292303/6220679).
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48085001

http://stackoverflow.com/a/48086059
upvote count: 2
answers question: http://stackoverflow.com/q/48085980
type: Answer
score: 2
downvote count: 0
has body: That is just a non-well-formed HTML which BeautifulSoup is still capable of parsing. It's just that attribute4="Domestic Total" is never true since it's not the space that is between Domestic and Total but rather a newline character. One way is to workaround with the find() method, using a function for the attribute4 attribute value, split and re-join which would effectively remove all newlines and replace them with spaces: In [19]: soup.find("m1_attribute_group2", attribute4=lambda x: x and " ".join(x.split()) == "Domestic Total") Out[19]: &lt;m1_attribute_group2 attribute4="Domestic Total"&gt; &lt;cell cell_value4="314.35"&gt;&lt;/cell&gt; &lt;/m1_attribute_group2&gt; You can then generalize it as: def filter_attribute(attr_value): def f(attr): return attr and " ".join(attr.split()) == attr_value return f And use: In [23]: soup.find("m1_attribute_group2", attribute4=filter_attribute("Domestic Total")) Out[23]: &lt;m1_attribute_group2 attribute4="Domestic Total"&gt; &lt;cell cell_value4="314.35"&gt;&lt;/cell&gt; &lt;/m1_attribute_group2&gt; Another approach would be to use a regular expression and \s+ as a delimiter between the words, where \s+ means "one or more space characters including newline": In [24]: soup.find("m1_attribute_group2", attribute4=re.compile(r"Domestic\s+Total")) Out[24]: &lt;m1_attribute_group2 attribute4="Domestic Total"&gt; &lt;cell cell_value4="314.35"&gt;&lt;/cell&gt; &lt;/m1_attribute_group2&gt;
has comment: http://stackoverflow.com/comment/83150175

http://stackoverflow.com/a/48014836
score: 6
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/48014637
downvote count: 0
has comment: http://stackoverflow.com/comment/82999209
has body: Another way you can do this to use melt and groupby: df_out = df.melt().groupby(['variable','value']).size().to_frame(name='n') df_out['proportion'] = df_out['n'].div(df_out.n.sum(level=0),level=0) print(df_out) Output: n proportion variable value grade A 2 0.4 B 2 0.4 C 1 0.2 year 2012 2 0.4 2013 3 0.6 And, if you really want to get crazy and do it in a one-liner: (df.melt().groupby(['variable','value']).size().to_frame(name='n') .pipe(lambda x: x.assign(proportion = x'n'/x.groupby(level=0).transform('sum')))) Upgraded solution using @Wen pct calculation: (df.melt().groupby(['variable','value']).size().to_frame(name='n') .pipe(lambda x: x.assign(proportion = x['n'].div(x.n.sum(level=0),level=0))))
has comment: http://stackoverflow.com/comment/82999816
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82999836
accepted answer of: http://stackoverflow.com/q/48014637

python-2.7
tags question: http://stackoverflow.com/q/48047865
tags question: http://stackoverflow.com/q/48074419
tags question: http://stackoverflow.com/q/48038968
tags question: http://stackoverflow.com/q/48143929
tags question: http://stackoverflow.com/q/48127720
tags question: http://stackoverflow.com/q/48165129
tags question: http://stackoverflow.com/q/48059815
tags question: http://stackoverflow.com/q/48168073
tags question: http://stackoverflow.com/q/48082264
tags question: http://stackoverflow.com/q/48122161
tags question: http://stackoverflow.com/q/48066606
tags question: http://stackoverflow.com/q/48103065
tags question: http://stackoverflow.com/q/48156951
tags question: http://stackoverflow.com/q/48069940
tags question: http://stackoverflow.com/q/48156392
tags question: http://stackoverflow.com/q/48135013
tags question: http://stackoverflow.com/q/48136359
tags question: http://stackoverflow.com/q/48107235
tags question: http://stackoverflow.com/q/48054932
tags question: http://stackoverflow.com/q/48051027
tags question: http://stackoverflow.com/q/48069875
tags question: http://stackoverflow.com/q/48078445
tags question: http://stackoverflow.com/q/48105436
tags question: http://stackoverflow.com/q/48108800
tags question: http://stackoverflow.com/q/48152513
tags question: http://stackoverflow.com/q/48126003
tags question: http://stackoverflow.com/q/48068739
tags question: http://stackoverflow.com/q/48166183
tags question: http://stackoverflow.com/q/48136052
tags question: http://stackoverflow.com/q/48128203
tags question: http://stackoverflow.com/q/48135571
tags question: http://stackoverflow.com/q/48125882
tags question: http://stackoverflow.com/q/48054334
tags question: http://stackoverflow.com/q/48106575
tags question: http://stackoverflow.com/q/48035367
tags question: http://stackoverflow.com/q/48047250
tags question: http://stackoverflow.com/q/48159254
tags question: http://stackoverflow.com/q/48152403
tags question: http://stackoverflow.com/q/48084891
tags question: http://stackoverflow.com/q/48125239
tags question: http://stackoverflow.com/q/48047307
tags question: http://stackoverflow.com/q/48135506
tags question: http://stackoverflow.com/q/48115983
tags question: http://stackoverflow.com/q/48067735
tags question: http://stackoverflow.com/q/48062858
tags question: http://stackoverflow.com/q/48078170
tags question: http://stackoverflow.com/q/48146580
tags question: http://stackoverflow.com/q/48147522
tags question: http://stackoverflow.com/q/48159459
tags question: http://stackoverflow.com/q/48169582
tags question: http://stackoverflow.com/q/48032299
tags question: http://stackoverflow.com/q/48120895
tags question: http://stackoverflow.com/q/48055372
tags question: http://stackoverflow.com/q/48045752
tags question: http://stackoverflow.com/q/48065517
tags question: http://stackoverflow.com/q/48014819
tags question: http://stackoverflow.com/q/48087569
tags question: http://stackoverflow.com/q/48146748
tags question: http://stackoverflow.com/q/48127684
tags question: http://stackoverflow.com/q/48114970
tags question: http://stackoverflow.com/q/48023743
tags question: http://stackoverflow.com/q/48127401
tags question: http://stackoverflow.com/q/48134584
tags question: http://stackoverflow.com/q/48039971
tags question: http://stackoverflow.com/q/48086812
tags question: http://stackoverflow.com/q/48082426
tags question: http://stackoverflow.com/q/48072862
tags question: http://stackoverflow.com/q/48173141
tags question: http://stackoverflow.com/q/48152899
tags question: http://stackoverflow.com/q/48143955
tags question: http://stackoverflow.com/q/48163333
tags question: http://stackoverflow.com/q/48050391
tags question: http://stackoverflow.com/q/48166440
tags question: http://stackoverflow.com/q/48017454
tags question: http://stackoverflow.com/q/48090648
tags question: http://stackoverflow.com/q/48066466
tags question: http://stackoverflow.com/q/48025283
tags question: http://stackoverflow.com/q/48110614
tags question: http://stackoverflow.com/q/48102450
tags question: http://stackoverflow.com/q/48017236

http://stackoverflow.com/comment/83174991
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48099928
has text: Can you share your `models.py`?

http://stackoverflow.com/comment/83118602
type: AnswerComment
type: Comment
score: 1
has text: @DebanjanB we don’t gave to and nth-of-type or other similar selectors is definitely an option as well. Thanks.
comment on: http://stackoverflow.com/a/48040615

http://stackoverflow.com/comment/83247902
type: Comment
comment on: http://stackoverflow.com/a/48134756
has text: One more question, does the images needs to be on jpeg file in order to create a tfrecord file? My dataset is composed of bmp, jpg, and png. I've ran the script for creating a tfrecord from a csv file and there were no errors so I assumed that everything was okay.
type: AnswerComment
score: 0

http://stackoverflow.com/q/48044241
has answer: http://stackoverflow.com/a/48044265
favorite count: 0
has title: What does words[count] = stars mean
has comment: http://stackoverflow.com/comment/83059691
type: UnansweredQuestion
downvote count: 8
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83060191
has answer: http://stackoverflow.com/a/48044345
has comment: http://stackoverflow.com/comment/83059423
has comment: http://stackoverflow.com/comment/83059475
has body: I'm a beginner and I did an exercise on Codecademy and the solution was this: def censor(text, word): words = text.split() result = '' stars = '*' * len(word) count = 0 for i in words: if i == word: words[count] = stars count += 1 result =' '.join(words) return result So my questions is what does words[count] = stars in line 8 mean?
has comment: http://stackoverflow.com/comment/83059422
type: Question
answer count: 2
score: -7

http://stackoverflow.com/a/48032331
type: Answer
has body: That is because you initialize the self.message in the init, and when you did s1.name = student2, you only changed the self.name, while the self.message was already initialized. If you want to get the self.message, you want to update its values somehow. what will work: class stud(): def __init__(self,a,b): self.name=a self.mark=b def the_message(self): self.message = self.name + ' ' + str(self.mark) return self.message s1 = stud('student1',40) print s1.the_message() s1.name='student2' print s1.the_message() output: student1 40 student2 40
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/83034863
has comment: http://stackoverflow.com/comment/83034817
downvote count: 0
answers question: http://stackoverflow.com/q/48032262
has comment: http://stackoverflow.com/comment/83034866
has comment: http://stackoverflow.com/comment/83034839

http://stackoverflow.com/comment/83122692
has text: @timgeb the next for 6 is 1
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48074511

http://stackoverflow.com/comment/83268290
score: 1
has text: `sudo apt-get install python-opencv` try this.
comment on: http://stackoverflow.com/q/48144883
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83269236
type: Comment
comment on: http://stackoverflow.com/a/48130014
has text: Cool. Update here , incase you figure out a better solution. All the best !
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83013526
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48022243
has text: I can not reproduce this error. Are you sure it is nowhre else in the code?
score: 0

http://stackoverflow.com/a/48065062
answers question: http://stackoverflow.com/q/48064965
upvote count: 3
has body: Just chain with dropna. Like so: df.groupby("cats").mean().dropna() values cats a 1.0 b 2.0 c 4.0
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83103296
has comment: http://stackoverflow.com/comment/132599710

http://stackoverflow.com/comment/83259798
comment on: http://stackoverflow.com/q/48104071
has text: @drew010 Sorry, It doesn't work..... I get the error : Unable to determine SOCKS version from socks5h://127.0.0.1:9050
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/48035464
score: 1
upvote count: 1
has body: I think problem is that float can't keep every value and we have situation that 0.1 + 0.2 != 0.3 And it can makes difference between expected result and obtained result. You can use only integer values to change position for all tiles ie. tile.rect.x = int(xmove) tile.rect.y = int(ymove) This way you can loose only small value (smaller then one pixel) but if you cumulate many small values then you can get few pixels. So you can try to cumulate differences between float and integer values. I can't check if this works correctly but I would do something like this def moveTiles(self): # add moves to already cumulated differences betweeen floats and integers self.xcululated += self.parent.dt * self.panning[0] * self.panning_speed self.ycululated += self.parent.dt * self.panning[1] * self.panning_speed # get only integer values xmove = int(self.xcululated) ymove = int(self.ycululated) # remove integers from floats self.xcululated += xmove self.ycululated += ymove for tile in self.game_map: # use the same integer values for all tiles tile.rect.x += xmove tile.rect.y += tmove
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83046360
answers question: http://stackoverflow.com/q/48034044

http://stackoverflow.com/a/56636858
score: 1
downvote count: 0
has body: I encountered same problem and took 2 hours to figure it out. pip install xlrd (latest) pip install pandas (latest) Go to C:\Python27\Lib\site-packages and check for xlrd folder (if there are 2 of them) delete the old version open a new terminal and use pandas to read excel. It should work.
answers question: http://stackoverflow.com/q/48066517
type: Answer
upvote count: 1

http://stackoverflow.com/q/48099832
possible better answer: http://stackoverflow.com/a/48099973
downvote count: 2
has answer: http://stackoverflow.com/a/48099973
type: Question
has answer: http://stackoverflow.com/a/48100192
answer count: 2
upvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48100192
tagged with: python
tagged with: dictionary
score: -2
has body: I would like to set up an empty dictionary ind_dict at the beginning, and then when I get a pair of (key, val). If the key already exists in the ind_dict, I will just add up the val(float type), otherwise I will add the new (key, val) pair.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83174926
has title: Adding/Updating key, val in a dictionary

http://stackoverflow.com/comment/83050890
comment on: http://stackoverflow.com/a/48039398
has text: Once again, "Tanto di cappello" as I say in Italian (I can not honestly say it in English XD) Joking aside, I thank you once again for your precious help.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83074372
has text: I was under the impression I needed to set it myself. Seems to be working as you described. Much appreciated!
comment on: http://stackoverflow.com/q/48043853
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51099586
answers question: http://stackoverflow.com/q/48070378
score: 0
has body: Found answer by myself. Should make use of the Model functionality to create a usable graph. outputs = [] outputs.append(tf.get_default_graph().get_tensor_by_name('activation_25/Relu:0')) outputs.append(tf.get_default_graph().get_tensor_by_name('activation_31/Relu:0')) inputs = resnet.input sub_resnet = tf.contrib.keras.models.Model(inputs, outputs) low_branch, high_branch = sub_resnet.apply(input_maps)
type: Answer

http://stackoverflow.com/a/48115477
has body: The method randrange does not return a range, but a randomly selected element instead as can be read in the doc. random.randrange(start, stop[, step]) Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object. That is why you get a TypeError, you are indeed trying to loop over an int. I would not recommend looping in a random order over your lists, but if it turns out to be necessary, I would use shuffle. from random import shuffle # shuffle mutates your list so we need to do the following rows, cols = range(len(lattice)), range(len(lattice)) shuffle(rows) shuffle(cols) for R1 in rows: for R2 in cols: # ... Note that in Python3, you would need to cast your range to a list first.
answers question: http://stackoverflow.com/q/48115384
score: 0
type: Answer

http://stackoverflow.com/comment/83184315
type: Comment
has text: you might be missing a period in "df_wantedreset_index()" but otherwise this looks great! Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/48102262
score: 0

http://stackoverflow.com/a/48105767
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48104401
score: 1
has body: I would suggest to use something like this approach, which is linear in the number of the elements of the matrix (consider that you cannot pay less than scanning at least once all the matrix's elements). Essentially, I group into a set the list of adjacent numbers, then on top of this I compute the neighbors entries. import numpy as np import collections def adj_to_neighbor_dict(adj): assert hasattr(adj, "__iter__") neighbor_dict = collections.defaultdict(lambda: set()) for i,j in adj: if i == j: continue neighbor_dict[i].add(j) neighbor_dict[j].add(i) return neighbor_dict def get_neighbors_2d(npmatrix): assert len(npmatrix.shape) == 2 I, J = range(npmatrix.shape[0]-1), range(npmatrix.shape[1]-1) adj_set = set( (npmatrix[i,j], npmatrix[i+1,j]) for i in I for j in J ) | set( (npmatrix[i,j], npmatrix[i,j+1]) for i in I for j in J ) return adj_to_neighbor_dict(adj_set) I tested it on a random matrix of 1M elements with 10 different numbers (np.random.randint(0,10,(1000,1000))) and it took 1.61 seconds. UPDATE: The same approach can be used for 3D arrays. The code to do it is the following: def get_neighbors_3d(npmatrix): assert len(npmatrix.shape) == 3 I, J, K = range(npmatrix.shape[0]-1), range(npmatrix.shape[1]-1), range(npmatrix.shape[2]-1) adj_set = set( (npmatrix[i,j,k], npmatrix[i+1,j,k]) for i in I for j in J for k in K ) | set( (npmatrix[i,j,k], npmatrix[i,j+1,k]) for i in I for j in J for k in K ) | set( (npmatrix[i,j,k], npmatrix[i,j,k+1]) for i in I for j in J for k in K ) return adj_to_neighbor_dict(adj_set) I tested also this function on a random matrix of 1M elements with 10 different numbers (np.random.randint(0,10,(100,100,100))) and it took 2.60 seconds. I would propose also a general purpose solution which is not based on the shape of the np.array: def npmatrix_shape_iter(shape): num_dimensions = len(shape) last_dimension = num_dimensions-1 coord = [0] * num_dimensions while True: yield tuple(coord) coord[last_dimension] += 1 for i in xrange(last_dime…
has comment: http://stackoverflow.com/comment/83212640
downvote count: 0
has comment: http://stackoverflow.com/comment/83188262

http://stackoverflow.com/comment/83141060
has text: @NickT. You are absolutely right. I did not read carefully.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48083114

http://stackoverflow.com/comment/83079169
has text: By the way, in python 2.7, may be you will need [unicodecsv](https://github.com/jdunck/python-unicodecsv)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48053388

http://stackoverflow.com/q/48054546
tagged with: google-cloud-datastore
linked to: http://stackoverflow.com/q/40689781
score: 0
has answer: http://stackoverflow.com/a/48056475
has body: I've read the documentation on how to do this but it is not working. I am trying to get my query to sort by date newest first, but this is not working: wrQuery = WorkRequest.query() wrQuery.order('-date') wrResult = wrQuery.fetch() I have also tried ('-WorkRequest.date') but both results in similar errors: TypeError: order() expects a Property or query Order; received '-date'
type: UnansweredQuestion
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/48058321
tagged with: python
has title: Datastore query sort order by newest date
type: Question
answer count: 2

http://stackoverflow.com/q/48131072
score: 2
downvote count: 0
tagged with: python-dateutil
has answer: http://stackoverflow.com/a/48131167
has title: Does anyone know why python dateutil parser is telling me it contains invalid syntax? It worked last night, will not work anymore
type: Question
upvote count: 2
has body: from dateutil import parser as _date_parser File "C:\Program Files (x86)\Python36-32\lib\site-packages\dateutil\parser.py", line 158 l.append("%s=%s" % (attr, `value`)) ^ SyntaxError: invalid syntax My code was no different last night when I ran it. Had no problems then, but now I'm getting this SyntaxError from the dateutil parser. Here's the code from the parser itself: def _repr(self, classname): l = [] for attr in self.__slots__: value = getattr(self, attr) if value is not None: l.append("%s=%s" % (attr, `value`)) return "%s(%s)" % (classname, ", ".join(l))
answer count: 1
tagged with: parsing
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83239074
tagged with: python

http://stackoverflow.com/comment/83098823
comment on: http://stackoverflow.com/q/48050639
has text: @MadPhysicist It takes right on 3 minutes on my desktop Mac with the `awk` I suggested.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48066306
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/48066449
upvote count: 3
tagged with: import
type: AnsweredQuestion
has title: Is it possible to use string elements as input in sklearn?
downvote count: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/83106098
favorite count: 0
type: Question
has body: I am trying to analyze my data using sklearn and see if there is some correlation between elements. My data set is a short protein motif which is quite diverse in sequence. My input looks like this: 1p 2p 3p 4p 5p genus 0 T V H F K Enterobacteriaceae 1 T V M F M Escherichia 2 E I H V K Enterobacteriaceae 3 K L M F K Enterobacteriaceae There are 20 different letter possibilities at positions 1-5. I wanted to use similar approach as it was shown in the sklearn Iris set to check dependencies between amino acids in different positions and bacterial genus. In the other words, I want to see if sequence of letters is genus specific and if letter at single position is somehow related to letters in other positions. Problem is, as far as I know, only numbers can be used as an input for sklearn. I tried to subsitute letters with numbers: from 1e-10 to 1e10 for each individual letter, but I had problems with data visualization later. I hope there is other, way more efficient way of using this kind of input data. I would be very grateful for some hints. Thanks!
tagged with: data-visualization
score: 3
has answer: http://stackoverflow.com/a/48066449
tagged with: bioinformatics

http://stackoverflow.com/comment/83185069
score: 0
has text: The general rule of thumb is to look for the bright yellow, flagging lines that require Python function calls (that includes `numpy` code). If Cython can replace those with pure C code, you usually get greater speed. It does't explain anything; it just identifies possible bottlenecks.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48103343

http://stackoverflow.com/comment/83138451
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48081877
type: Comment
has text: Okay, I got it working now. Thanks for your help. If you update your answer I'll select it as the correct one. I guess the input wasn't the problem after all... just programmer error :( Thanks again.

http://stackoverflow.com/comment/83077047
type: AnswerComment
has text: Yep, I installed MS Office Suite for Mac Home Business (free trial for a month) and the `wb = xw.Book()` line worked this time.
type: Comment
comment on: http://stackoverflow.com/a/48052370
score: 0

http://stackoverflow.com/q/48138209
tagged with: varchar
tagged with: matching
tagged with: mysql
has comment: http://stackoverflow.com/comment/83255493
type: Question
has comment: http://stackoverflow.com/comment/83255476
answer count: 1
tagged with: string
score: 0
has answer: http://stackoverflow.com/a/48138399
tagged with: python
has title: Check if any element of raw data is present in a srt file in python
linked to: http://stackoverflow.com/q/4940032
has comment: http://stackoverflow.com/comment/83255611
has comment: http://stackoverflow.com/comment/83254725
has comment: http://stackoverflow.com/comment/83255008
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83254923
has comment: http://stackoverflow.com/comment/83253963
has body: i have a variable data which have a value of [('01:02,02:52,03:30,03:31',)], and a srt file with some of its content be like: 23 00:00:59,025 --> 00:01:06,042 can read and display documents that 24 00:01:02,016 --> 00:01:08,225 contain HTML so Firefox Google Internet 25 00:01:06,042 --> 00:01:09,851 Explorer they all do the same thing 26 00:01:08,369 --> 00:01:12,630 they're going to take that document and now i want to check if any element of my data eg: 01:02 or 03:30 or any other separately is present in the srt file or not. For eg: 01:02 is present below 24 numbered 00:01:02,016 --> 00:01:08,225 here is python file but no outcome: import mysql.connector import numpy as np conn= mysql.connector.connect (user="root",password="",host="localhost",database="videojs") # prepare a cursor object using cursor() method cursor = conn.cursor() def read_from_db(): cursor.execute("select time_arr from info where id ='52'") data=cursor.fetchall() print(data) #Open the file fobj = open("one.srt") text = fobj.read().strip().split() #Conditions while True: s = input("Enter a string: ") #Takes input of a string from user if s == "": #if no value is entered for the string continue if s in text: #string in present in the text file print("Matched") break else: #string is absent in the text file print("No such string found,try again") continue fobj.close() read_from_db() please help me out....
has comment: http://stackoverflow.com/comment/83255434

http://stackoverflow.com/q/48166461
downvote count: 2
tagged with: plot
type: Question
score: -2
tagged with: matplotlib
has title: getting error with plot with panda DataFrame
tagged with: dataframe
tagged with: pandas
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83314716
tagged with: python
has body: i am trying to creat plot from that data Word count 17 in 2 15 on 2 33 the 2 8 you 2 0 valar 1 29 all 1 24 + 1 25 hotel 1 26 are 1 with this code : %matplotlib inline words_df[words_df['count'] &gt; 10000].plot(x='Word',kind='bar') but i got this message error : TypeError: Empty 'DataFrame': no numeric data to plot can you give me an idea where is the problem ???
has comment: http://stackoverflow.com/comment/83312053
has answer: http://stackoverflow.com/a/48166533
type: UnansweredQuestion

http://stackoverflow.com/comment/83187013
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48105262
has text: @cricket_007 but I can access this php file from other platforms like Matlab and Simulink

http://stackoverflow.com/comment/83292289
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48123538
has text: what do you mean by "taking too long"? `timeout` argument of `urlopen` is not for overall request time.

http://stackoverflow.com/comment/83323270
comment on: http://stackoverflow.com/a/48171125
type: Comment
type: AnswerComment
has text: @DanielSeidl `os.walk()` returns a tuple of 3 items. The docs describes what it does and provides an example. Should have everything you need. When you get it working or have more questions, come back and ask or select as answer.
score: 0

http://stackoverflow.com/q/48099570
linked to: http://stackoverflow.com/q/40871864
tagged with: find
downvote count: 0
linked to: http://stackoverflow.com/q/22897209
favorite count: 0
has comment: http://stackoverflow.com/comment/83208051
type: UnansweredQuestion
tagged with: path
tagged with: python
has comment: http://stackoverflow.com/comment/83174627
has body: Do someone want to explain me (in pseudocode too) how the pathfinding/a* algorithm can be implemented in Python? I searched all over the internet but I am not able to understand how to calculate H-cost or G-cost. I found some source code, but it is too difficult for me (I am still a newbie). Let's think I have a map like this: ''' S0000000000000000000000000100000000000 00000000000000000000100000001000000000 10000111110101000001100000001000000000 01111100010001000010100000010000000000 00000100001111100100100001110000110000 00001100000001011000000100000001000000 00000100000000101000000000011110000001 00000010000000000111111111100000000011 00000001000000000000000001100000111100 00000000110000000000000000010011000000 00000000010000000001100000001000000000 00000000010000000000110000000111111000 00000000010000000000010000000000000000 00000000011000111111111111111111111111 000000000100000110000010000000000000E0 00000000001100000100001000000000000000 00000000000100000011000000000000000000 00000000000010000000000000000000000000 ''' Where 1s are obstacles, 'S' is the starting point and 'E' is the end. How can I implement that algorithm? It would be great also if you can link an internet page who explain it in a easy way.
answer count: 0
tagged with: a-star
score: 1
upvote count: 1
has title: Explanation of pathfinding/a* algorithm?
type: Question
has comment: http://stackoverflow.com/comment/83175011
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83174537

http://stackoverflow.com/q/48104460
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48104498
accepted answer: http://stackoverflow.com/a/48104498
tagged with: selenium
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83184653
tagged with: javascript
score: -1
has comment: http://stackoverflow.com/comment/83191783
has title: How to execute a specific js request without loading the whole web page?
has comment: http://stackoverflow.com/comment/83184857
has body: I'm trying to get a single element from the webpage - a number of views (2128 digit on the upper left side near the eye image right now). The number is a result of some javascript function so it absents in the source page code, and I cannot get it with http request. I wouldn't like to download the whole page with Selenium webdriver either. Is there any way to run a single javascript code from the page without downloading it?
upvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/83135963
score: 0
type: Comment
has text: @PauloScardine Good catch, Cheers for the feedback :-). I'll update my answer.
comment on: http://stackoverflow.com/a/48080515
type: AnswerComment

http://stackoverflow.com/comment/83266967
score: 0
type: AnswerComment
type: Comment
has text: >>> spell('happyyyyyyyyyyy') 'happyyyyyyyyyyy' >>> spell('haaaaappyyyyyyyyyyy') 'haaaaappyyyyyyyyyyy'
comment on: http://stackoverflow.com/a/48144366

http://stackoverflow.com/comment/83117166
type: Comment
comment on: http://stackoverflow.com/q/48070972
type: QuestionComment
has text: i use python 3.6.2
score: 0

http://stackoverflow.com/a/48074653
has comment: http://stackoverflow.com/comment/83122800
has comment: http://stackoverflow.com/comment/83122907
has comment: http://stackoverflow.com/comment/83122805
has comment: http://stackoverflow.com/comment/83122851
has comment: http://stackoverflow.com/comment/83123450
has body: If you are working with "days" encoded 1-6, use the following: &gt;&gt;&gt; def prev_next_day(day): ... day -= 1 ... prev = ((day - 1) % 6) + 1 ... next_ = ((day + 1) % 6) + 1 ... return [prev, next_] ... &gt;&gt;&gt; prev_next_day(2) [1, 3] &gt;&gt;&gt; prev_next_day(5) [4, 6] &gt;&gt;&gt; prev_next_day(1) [6, 2] &gt;&gt;&gt; prev_next_day(6) [5, 1]
answers question: http://stackoverflow.com/q/48074511
type: Answer
has comment: http://stackoverflow.com/comment/83122984
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/83123282
downvote count: 0
has comment: http://stackoverflow.com/comment/83123006

http://stackoverflow.com/a/48164343
upvote count: 1
has comment: http://stackoverflow.com/comment/83371948
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48158110
has comment: http://stackoverflow.com/comment/83373187
has comment: http://stackoverflow.com/comment/83327427
has body: Why not use address returned by recvfrom() directly? ... The return value is a pair (bytes, address) where bytes is a bytes object representing the data received and address is the address of the socket sending the data. received, addr = getSocket.recvfrom(getSIZE) print(addr) yields: ('202.149.20.224', 51050)
type: Answer
has comment: http://stackoverflow.com/comment/83373293
downvote count: 0
has comment: http://stackoverflow.com/comment/83373608
has comment: http://stackoverflow.com/comment/83371602
has comment: http://stackoverflow.com/comment/83317165
has comment: http://stackoverflow.com/comment/83373242
has comment: http://stackoverflow.com/comment/83327486
has comment: http://stackoverflow.com/comment/83327344
has comment: http://stackoverflow.com/comment/83372538
has comment: http://stackoverflow.com/comment/83372032
has comment: http://stackoverflow.com/comment/83327386
score: 1
has comment: http://stackoverflow.com/comment/83371500
has comment: http://stackoverflow.com/comment/83372095
has comment: http://stackoverflow.com/comment/83371542
accepted answer of: http://stackoverflow.com/q/48158110

http://stackoverflow.com/comment/83034357
has text: Hi, can you post your data frame code? Thanks.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48031979
type: QuestionComment

http://stackoverflow.com/a/48106422
downvote count: 0
has body: You can test the value of the Fiscal quarter column and use it to select the values to replace like: Code: df['Fiscal quarter'][df['Fiscal quarter'].str.startswith('FYn')] = '' Test Code: import pandas as pd df = pd.DataFrame([ ('A', 'FY18 Q3'), ('A', 'FY18 Q4'), ('A', 'FYn Q3'), ], columns=['Type', 'Fiscal quarter']) print(df) df['Fiscal quarter'][df['Fiscal quarter'].str.startswith('FYn')] = '' print(df) Results: Type Fiscal quarter 0 A FY18 Q3 1 A FY18 Q4 2 A FYn Q3 Type Fiscal quarter 0 A FY18 Q3 1 A FY18 Q4 2 A
type: Answer
answers question: http://stackoverflow.com/q/48106341
upvote count: 1
score: 1

http://stackoverflow.com/comment/83172778
comment on: http://stackoverflow.com/q/48098785
type: Comment
score: 0
type: QuestionComment
has text: One question per question, please. [ask]

http://stackoverflow.com/q/48170089
tagged with: list
has body: I´m looking to merge 2 lists of lists. In the first piece of code I can merge 2 lists of strings without the repeated elements! That is what I´m looking for but with 2 lists of lists (of strings): list1 = ['a', 'b', 'c', 'd'] list2 = ['c', 'd', 'e', 'f'] # List merge without dupe list1.extend([element for element in list2 if element not in list1]) print list1 &gt;&gt;&gt; ['a', 'b', 'c', 'd', 'e', 'f'] What I´m looking for: list1=[["artur","1/1/2018","0.5"], ["paco","1/1/2018","2.11"], ["pepe","1/1/2018","11.2"], ["artur","2/1/2018","0.5"], ["paco","2/1/2018","2.11"], ["pepe","2/1/2018","11.2"]] list2=[["artur","1/1/2018","Estable"], ["paco","1/1/2018","Critico"], ["pepe","1/1/2018","Critico"], ["artur","2/1/2018","Estable"], ["paco","2/1/2018","Critico"], ["pepe","2/1/2018","Critico"]] #desired output: &gt;&gt;&gt;list1 [["artur","1/1/2018","0.5","Estable"], ["paco","1/1/2018","2.11","Critico"], ["pepe","1/1/2018","11.2","Critico"], ["artur","2/1/2018","0.5","Estable"], ["paco","2/1/2018","2.11","Critico"], ["pepe","2/1/2018","11.2","Critico"]] EDITION: if my list will be: list1=[["artur,1/1/2018,0.5"], ["paco,1/1/2018,2.11"], ["pepe,1/1/2018,11.2"], ["artur,2/1/2018,0.5"], ["paco,2/1/2018,2.11"], ["pepe,2/1/2018,11.2"]] list2=[["artur,1/1/2018,Estable"], ["paco,1/1/2018,Critico"], ["pepe,1/1/2018,Critico"], ["artur,2/1/2018,Estable"], ["paco,2/1/2018,Critico"], ["pepe,2/1/2018,Critico"]] I had to convert a csv to list but I have this kind of list and not what I´m asked in the fist lines of the question!
accepted answer: http://stackoverflow.com/a/48170219
score: 0
answer count: 3
upvote count: 1
downvote count: 1
has title: Merge 2 lists of lists
possible better answer: http://stackoverflow.com/a/48170325
has answer: http://stackoverflow.com/a/48170325
tagged with: python-2.7
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48170219
favorite count: 0
has comment: http://stackoverflow.com/comment/83319777
type: Question
has answer: http://stackoverflow.com/a/48172064
tagged with: python

http://stackoverflow.com/comment/133271370
score: 1
type: AnswerComment
has text: For calculating TN, you could also subtract TP, FP, and FN from the total `TN = np.repeat(np.sum(cm), 3) - TP - FP - FN`
comment on: http://stackoverflow.com/a/48101802
type: Comment

http://stackoverflow.com/a/48170918
has body: You can use Index.intersection + DataFrame.loc: idx = df1.index.intersection(df2.index) print (idx) Index(['28/11/2000', '29/11/2000', '30/11/2000'], dtype='object') Alternative solution with numpy.intersect1d: idx = np.intersect1d(df1.index, df2.index) print (idx) ['28/11/2000' '29/11/2000' '30/11/2000'] df1 = df1.loc[idx] print (df1) values 1 28/11/2000 -0.055276 29/11/2000 0.027427 30/11/2000 0.066009 df2 = df2.loc[idx]
has comment: http://stackoverflow.com/comment/98341316
has comment: http://stackoverflow.com/comment/101860485
downvote count: 0
score: 38
upvote count: 38
type: Answer
answers question: http://stackoverflow.com/q/48170867

http://stackoverflow.com/a/48051288
accepted answer of: http://stackoverflow.com/q/48050769
type: Answer
has body: Per pandas docs, to_json renders a json string which you can confirm with type(jsonfiles). Though the print output looks like a json object, single quotes will wrap at beginning and end. To resolve, simply import the built-in json module (part of Python standard library) and parse the to_json string into a json object with loads method: import json ... jsonfiles = json.loads(df.to_json(orient='records')) return render_template('index.html', ctrsuccess=jsonfiles)
score: 21
upvote count: 21
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48050769

http://stackoverflow.com/q/48060126
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I got an error, TemplateDoesNotExist at /app/detail/3/ app/post_detail.html. I wrote the following: def top(request): content = POST.objects.order_by('-created_at')[:5] page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,"page":page}) class DetailView(generic.DetailView): model = POST def detail(request, pk): content = POST.objects.get(id=pk) return render(request, 'detail.html',{'content': content}) in top.html {% for content in page %} {{ content.title }} SHOW DETAIL {% endfor %} in detail.html {{ content.title }} {{ content.text }} When I access top.html, ordinary web site is shown, so it is ok. But when I put SHOW DETAIL links the error happens. I did not write post_detail.html anywhere in my code, so I really cannot understand why post_detail.html causes the mistake. As a test,I made post_detail.html in same directory with top.html and detail.html, but the same error happens. I want to make a system when I put SHOW DETAIL links, the content's detail is shown. How should I fix this? What is wrong in my code? After reading answer,I rewrote DetailView of views.py class DetailView(generic.DetailView): model = POST template_name = 'detail.html' but when I put SHOW DETAIL links, nothing is shown there.I wrote in detail.html {{ post.title }} {{ post.text }} Am I wrong to write the way of detail.html or views.py?How can I show detail's content?
downvote count: 0
score: 1
tagged with: django
type: Question
has title: TemplateDoesNotExist at /app/detail/3/
has answer: http://stackoverflow.com/a/48060214

http://stackoverflow.com/comment/83298778
has text: If live you'd need to either do it in a migration or run it in the shell. You should not run into the issue once in place and new user creation auto creates the profile with user creation.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48159476
type: Comment

http://stackoverflow.com/a/48017323
answers question: http://stackoverflow.com/q/48017281
type: Answer
upvote count: 7
has body: An easy way is to use dict.pop() instead: data = { 'key1': { 'a': 'key1', 'b': 'val1', 'c': 'val2' }, 'key2': { 'a': 'key2', 'b': 'val3', 'c': 'val4' }, 'key3': { 'a': 'key3', 'b': 'val5', 'c': 'val6' } } for key in data: data[key].pop('a', None) print(data) Which Outputs: {'key1': {'b': 'val1', 'c': 'val2'}, 'key2': {'b': 'val3', 'c': 'val4'}, 'key3': {'b': 'val5', 'c': 'val6'}} The way dict.pop() works is that first checks if the key is in the dictionary, in this case "a", and it removes it and returns its value. Otherwise, return a default value, in this case None, which protects against a KeyError.
score: 7
downvote count: 0

http://stackoverflow.com/comment/83082508
type: Comment
has text: The `\n` is the newline character, you might want to clean it in `dft.colums` in order to avoid problems in the future. I’m glad it works now.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48054584

http://stackoverflow.com/comment/83263685
comment on: http://stackoverflow.com/q/48141087
type: Comment
type: QuestionComment
score: 0
has text: Just give this one a shot: `Socket s = new Socket("(name of global host)", 80);` And use the the InputStream and OutputStream directly

vertica
tag name: vertica
tags question: http://stackoverflow.com/q/48056394
type: Tag

http://stackoverflow.com/comment/83193264
type: QuestionComment
has text: like i said, PyQt5.
comment on: http://stackoverflow.com/q/48097176
score: 0
type: Comment

http
tags question: http://stackoverflow.com/q/48122260
tags question: http://stackoverflow.com/q/48092184
tags question: http://stackoverflow.com/q/48171159
tag name: http
tags question: http://stackoverflow.com/q/48158851
tags question: http://stackoverflow.com/q/48038369
tags question: http://stackoverflow.com/q/48023860
tags question: http://stackoverflow.com/q/48159415
type: Tag
tags question: http://stackoverflow.com/q/48068900
tags question: http://stackoverflow.com/q/48096390

http://stackoverflow.com/comment/83234141
comment on: http://stackoverflow.com/q/48125184
has text: Here are the output screens on both devices - https://imgur.com/a/NgzsC
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84756919
type: AnswerComment
has text: @Marcel Thanks for accepting. You can also upvote answers if you liked them :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48089266

waveform
tag name: waveform
type: Tag
tags question: http://stackoverflow.com/q/48043004

http://stackoverflow.com/comment/83157963
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48080357
has text: Yes, averaging the token-vectors is one way but I've got 30% loss with 85% accuracy in sentiment analysis with this in a convolutional neural network setup. Also, when I try to predict with obviously polar sentiments, it gives me wrong predictions. I figure this is because I'm not modelling sequential relationships between the words, so this is why I'm trying to get word vectors inputted separately to a LSTM.
score: 0

http://stackoverflow.com/q/48053300
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/48053456
answer count: 3
has comment: http://stackoverflow.com/comment/83078879
tagged with: global-variables
downvote count: 1
has title: Permutation program issue, has something to do with global variables (Python)
has comment: http://stackoverflow.com/comment/83078998
has comment: http://stackoverflow.com/comment/83079072
type: UnansweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/2612802
has answer: http://stackoverflow.com/a/48053532
tagged with: permutation
favorite count: 0
has answer: http://stackoverflow.com/a/48053322
type: Question
has body: this is an algorithm that is meant to write down some of the permutations of the list P and it does it well, but... def p(): global P P = ['a', 'b', 'c', 'd'] perm(4) per = [] def perm(k): global P if k==1: print(P) per.append(P) else: for i in range(k): P[i], P[k-1] = P[k-1], P[i] perm(k-1) P[i], P[k-1] = P[k-1], P[i] when i want it to add the permutations to a global list (necessary for the rest of the program) there is a problem. It still prints all the permutations ['b', 'c', 'd', 'a'] ['b', 'c', 'd', 'a'] ['d', 'b', 'c', 'a'] ['d', 'b', 'c', 'a'] ['b', 'd', 'c', 'a'] ['b', 'd', 'c', 'a'] ['a', 'c', 'b', 'd'] ['a', 'c', 'b', 'd'] ['b', 'a', 'c', 'd'] ['b', 'a', 'c', 'd'] ['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd'] ['b', 'd', 'a', 'c'] ['b', 'd', 'a', 'c'] ['a', 'b', 'd', 'c'] ['a', 'b', 'd', 'c'] ['b', 'a', 'd', 'c'] ['b', 'a', 'd', 'c'] ['a', 'd', 'b', 'c'] ['a', 'd', 'b', 'c'] ['b', 'a', 'd', 'c'] ['b', 'a', 'd', 'c'] ['a', 'b', 'd', 'c'] ['a', 'b', 'd', 'c'] but when i check the list it's filled with the default set [['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c']] could you please help me at least with what's the actual issue?

http://stackoverflow.com/comment/83144200
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48084630
type: Comment
has text: Use a OneToOneField in `B`, follow it and use the reverse relationship to `C` from there.

http://stackoverflow.com/a/48157217
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48153448
answers question: http://stackoverflow.com/q/48153448
has body: It isn't working because you are mounting the application at a sub URL in Apache, but your route in Flask also has the mount point in it. This means the URL you use would need to be /sysinfo/sysinfo/restart_now. You either need to use in the Flask route just /restart_now, or change the Apache configuration to use: WSGIScriptAlias /sysinfo /var/www/sysinfo/sysinfo.wsgi/sysinfo The addition of the trailing /sysinfo on last argument fiddles things so that the Flask application still sees the mount point as part of PATH_INFO, which is what Flask routes off. BTW, you don't need WSGIScriptReloading On as that is the default anyway.
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83294071
score: 2

http://stackoverflow.com/a/48143342
type: Answer
accepted answer of: http://stackoverflow.com/q/48139078
has body: Please refer to the snippet of code as below ， it works for me. from datetime import datetime, timedelta from azure.storage.blob import ( BlockBlobService, ContainerPermissions, ) accountName = "***" accountKey = "***" containerName = "***" blobService = BlockBlobService(account_name=accountName, account_key=accountKey) sas_token = blobService.generate_container_shared_access_signature(containerName,ContainerPermissions.READ, datetime.utcnow() + timedelta(hours=1)) print sas_token blobService = BlockBlobService(account_name=accountName, account_key=None, sas_token=sas_token) blobService.get_blob_to_path(containerName, "1.png", "E://testLocal.png") Hope it helps you.
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/95094514
answers question: http://stackoverflow.com/q/48139078

http://stackoverflow.com/q/48052710
tagged with: parameters
has answer: http://stackoverflow.com/a/48052809
score: 1
upvote count: 1
has title: how to use def with parameters in python
type: Question
tagged with: function
has answer: http://stackoverflow.com/a/48052811
answer count: 2
has body: why does it print 0 and not 5? i cant find the error in my logic? score = 0 def pass_score(test_string, aScore): if re.match(a, test_string): increase_score(5, score) print (aScore) def increase_score (aValue, aScore): aScore += aValue
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48161549
has body: NN- gurus! I am new both in Tensorflow and the Deep Learning stuff, and i created a small tutorial of full connected NN. Having input as 2 values, represending x and y of some points in range of 0...1, i want distinquish... just if points are in the middle. Simple, huh? Literaly, my inputs and expected data are : inputs = [[0,0], [0,0.3], [0.3,0], [0.3,0.5], [0.5,0.3], [0.7,0.5], [0.5,0.6], [0.7,0], [0,0.6], [0.5,1], [0,1], [1,1], [1, 0.5]] expected = [[0,1], [0,1], [0,1], [1,0], [1,0], [1,0], [1,0], [0,1], [0,1], [0,1], [0,1], [0,1], [0,1]] So i expect output[0,1] from those what "is at the border" and [1,0] from the middle. Howewer, taking this as a dataset after 100000 iterations (!) seems to work bad: points at the edge are recognized good, but those from the middle producing output near [0.5,0.5], and points what were not in the training set produce even worse result. I d like to know what causes this error. Is it wrong task setting, network build, parameters, etc? Or there is wrong usage on TensorFlow itself? So again here is a complete .py file: ''' Created on Jan 9, 2018 @author: noob ''' import tensorflow as tf import matplotlib.pyplot as plt # trying to recognice points in the middle as 1,0 print("hello from python") inputs = [[0,0], [0,0.3], [0.3,0], [0.3,0.5], [0.5,0.3], [0.7,0.5], [0.5,0.6], [0.7,0], [0,0.6], [0.5,1], [0,1], [1,1], [1, 0.5]] expected = [[0,1], [0,1], [0,1], [1,0], [1,0], [1,0], [1,0], [0,1], [0,1], [0,1], [0,1], [0,1], [0,1]] test_inputs = [[0.4,0.1], [0.5,0.5], [0.9,0.2], [0.4,0.6]] test_expected = [[0,1], [1,0], [0,1], [1,0]] # ---------- Define Layers --------------------- in_layer = tf.placeholder(tf.float32,[1,2]) in_to_middle = tf.Variable(tf.zeros([2,10])) middle_layer = tf.Variable(tf.zeros([10])) middle_to_out = tf.Variable(tf.zeros([10,2])) out_layer = tf.Variable(tf.zeros([2])) out_expected = tf.placeholder(tf.float32,[1,2]) middle_layer = tf.nn.sigmoid(tf.matmul(in_layer,in_to_middle)) out_layer = tf.nn.sigmoid(tf.matmul(mid…
type: UnansweredQuestion
tagged with: python
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/48173760
score: 0
tagged with: deep-learning
has title: Small Neuronal Network does not train : wrong Dataset or coding error?
answer count: 1

http://stackoverflow.com/a/48024184
score: 0
has body: Here is an alternative approach Since this is an interesting problem, I decided to have a go myself. Here is an efficient way of writing your first function with O(1) set lookup: def translate_english_robber(s): consonants = 'bcdfghjklmnpqrstvwxz' # using a set instead is more efficient lookup = set(consonants + consonants.upper()) result = "" for char in s: if char in lookup: # anonymous function for converting the case of the letter "o" convert_case = lambda x: "o" if x.islower() else "O" # add it to the result result += char + convert_case(char) + char else: result += char return result Then for the reverse translation, all you need to do is find a consonant, and append it to the list, then somehow remove the next 2 characters, and continue the next iteration after the last removed character. Otherwise, if the current character is not a constant, add it normally. For example, If my Robbers language was "hohey", I would first find "h", add it, and remove "o" and "h" after that, then start iterating from "e". In the end, we would have "hey" as the English translation. Using an iterator would be useful here. You can also read up on iterators here, they are quite useful for problems like this. Here is my attempt: def translate_robber_english(s): consonants = 'bcdfghjklmnpqrstvwxz' lookup = set(consonants + consonants.upper()) # create the iterator it = iter(list(s)) result = "" # loop till we reach the end while True: try: # get the current letter current = next(it) # add it regardless result += current # if consonant, skip the next to letters if current in lookup: next(it) next(it) # If this exception occurs, break out of the loop except StopIteration: break return result And now you can get the reverse translations with both the above functions: &gt;&gt;&gt; robber = translate_english_robber("black") &gt;&gt;&gt; print(robber) boblolacockok &gt;&gt;&gt; english = translate_robber_english(robber) &gt;&gt;&gt; print(english) black
type: Answer
answers question: http://stackoverflow.com/q/48022472

http://stackoverflow.com/comment/83087756
comment on: http://stackoverflow.com/q/48057669
has text: Well, you can see that the method is called. Now figure out what the value 3 means to you...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83102142
type: Comment
has text: your solution is fitting well for my problem. Thank you really!!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48064154

http://stackoverflow.com/q/48163539
linked to: http://stackoverflow.com/q/3431434
has answer: http://stackoverflow.com/a/48165615
accepted answer: http://stackoverflow.com/a/48165615
has comment: http://stackoverflow.com/comment/83306338
linked to: http://stackoverflow.com/q/7391945
has title: How to read gif from url using opencv (python)
answer count: 1
downvote count: 0
favorite count: 0
has body: I can read jpg file using cv2 as import cv2 import numpy as np import urllib url = r'http://www.mywebsite.com/abc.jpg' req = urllib.request.urlopen(url) arr = np.asarray(bytearray(req.read()), dtype=np.uint8) img = cv2.imdecode(arr,-1) cv2.imshow('abc',img) However, when I do it with gif file, it returns an error: error: (-215) size.width&gt;0 &amp;&amp; size.height&gt;0 in function cv::imshow How to solve this problem?
has comment: http://stackoverflow.com/comment/83308294
linked to: http://stackoverflow.com/q/14134892
tagged with: python
type: AnsweredQuestion
upvote count: 14
type: Question
score: 14
tagged with: opencv

16-bit
tags question: http://stackoverflow.com/q/48032876
tag name: 16-bit
type: Tag

http://stackoverflow.com/q/48078932
type: Question
has body: I'm trying to understand how Django uses python's metaclasses for it's database models (options) and came up with the following stripped down code snippet that should roughly mimic Django's logic. class DatabaseOptions(object): def __init__(self, opts): if opts: for key, val in opts.__dict__.items(): if not key.startswith('__') and not callable(val): setattr(self, key, val) class MetaModel(type): def __new__(cls, name, bases, classdict): result = super().__new__(cls, name, bases, dict(classdict)) opts = classdict.pop('DbMeta', None) if opts: setattr(result, '_db_meta', DatabaseOptions(opts)) return result class Model(object, metaclass=MetaModel): class DbMeta: database = 'default' migrate = True class User(Model): class DbMeta(Model.DbMeta): database = 'user' class GroupUser(User): class DbMeta(User.DbMeta): database = 'group_user' Using the above code, I would expect the following output: print(Model._db_meta.database) # default print(Model._db_meta.migrate) # True print(User._db_meta.database) # user print(User._db_meta.migrate) # True print(GroupUser._db_meta.database) # group_user print(GroupUser._db_meta.migrate) # True Instead I get the following exception &gt;&gt;&gt; python3 test.py default True user Traceback (most recent call last): File "test.py", line 48, in &lt;module&gt; print(User._db_meta.migrate) # True AttributeError: 'DatabaseOptions' object has no attribute 'migrate' My question would be why User.DbMeta does not inherit the migrate attribute from Model.DbMeta? Is there any solution for this kind of problem? Edit: According to Daniel's answer I came up with the following that worked for me: class DatabaseOptions(object): def __init__(self, opts): if opts: for key in dir(opts): if not key.startswith('__'): val = getattr(opts, key, None) if not callable(val): setattr(self, key, val)
tagged with: django-models
score: 4
has title: Inner classes - Inheritance and overriding their attributes
accepted answer: http://stackoverflow.com/a/48080069
upvote count: 4
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48080069
favorite count: 0
tagged with: python-3.x
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48096935
has body: This code: print u'S\xe9parateur' str(u'S\xe9parateur') throws the error: Séparateur UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128) I used the function str because I want to convert the unicode string u'S\xe9parateur' to the corresponding ascii string, i.e u'S\xe9parateur' --> 'S\xc3\xa9parateur'
tagged with: ascii
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48096985
tagged with: encoding
downvote count: 0
answer count: 1
tagged with: unicode
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48096985
upvote count: 1
type: Question
has title: How to convert a unicode string to the corresponding ascii string?

http://stackoverflow.com/q/48063082
has body: I have learnt from PEP 3131 that non-ASCII identifiers were supported in Python, though it's not considered best practice. However, I get this strange behaviour, where my identifier (U+1D70F) seems to be automatically converted to τ (U+03C4). class Base(object): def __init__(self): self. = 5 # defined with U+1D70F a = Base() print(a.) # 5 # (U+1D70F) print(a.τ) # 5 as well # (U+03C4) ? another way to access it? d = a.__dict__ # {'τ': 5} # (U+03C4) ? seems converted print(d['τ']) # 5 # (U+03C4) ? consistent with the conversion print(d['']) # KeyError: '' # (U+1D70F) ?! unexpected! Is that expected behaviour? Why does this silent conversion occur? Does it have anything to see with NFKC normalization? I thought this was only for canonically ordering Unicode character sequences...
has comment: http://stackoverflow.com/comment/83100170
tagged with: unicode
linked to: http://stackoverflow.com/q/34097193
has comment: http://stackoverflow.com/comment/83099177
answer count: 1
accepted answer: http://stackoverflow.com/a/48063328
tagged with: python
favorite count: 0
score: 8
duplicate of: http://stackoverflow.com/q/34097193
tagged with: identifier
has title: Non-ASCII Python identifiers and reflectivity
downvote count: 1
has comment: http://stackoverflow.com/comment/83099542
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83099275
upvote count: 9
tagged with: reflection
tagged with: variable-names
has answer: http://stackoverflow.com/a/48063328
type: Question
has comment: http://stackoverflow.com/comment/83099496

http://stackoverflow.com/comment/83071639
has text: thanks for support !
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48042254
type: Comment

http://stackoverflow.com/a/48061532
answers question: http://stackoverflow.com/q/48061496
score: 2
has body: Add a \ to escape the other \ char: string = """ Hello\\nWorld 123 HelloWorld """ or have a "raw" string: string = r""" Hello\nWorld 123 HelloWorld """
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48061496

http://stackoverflow.com/comment/83209251
has text: (And don't use `is` for comparing strings.)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48116533
score: 4

vlc
tags question: http://stackoverflow.com/q/48086279
tags question: http://stackoverflow.com/q/48081704
tag name: vlc
type: Tag

http://stackoverflow.com/q/48156741
has body: So i have an application with an embedded Python interpreter. We start with Py_Initialize, and when the script is run we spawn a new Interpreter with Py_NewInterpreter. We execute the script below to use some 3rd party API's and it works great importing our Keysight.DigitalTestApps.Framework.Remote.dll that is provided. clr.AddReference("Keysight.DigitalTestApps.Framework.Remote") from Keysight.DigitalTestApps.Framework.Remote import * We can use the API and everything works. Without killing the interpreter or anything, the second time we run the script we get an error "ImportError: No module named Keysight.DigitalTestApps.Framework.Remote" I'm at a bit of a loss why every other python library and external library we use does not have this problem, but as soon as we include this library it has this issue. If i remove the use of that dll i can run our script as many times as i want with no issues.
type: Question
tagged with: .net
tagged with: python.net
tagged with: pythonnet
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: clr
has title: Embedded Python Interpreter+CLR: Fails to find module on second run?
tagged with: python
has comment: http://stackoverflow.com/comment/83382700
answer count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/48174228
answers question: http://stackoverflow.com/q/48172928
has comment: http://stackoverflow.com/comment/83328703
type: Answer
accepted answer of: http://stackoverflow.com/q/48172928
downvote count: 0
has comment: http://stackoverflow.com/comment/83331037
has comment: http://stackoverflow.com/comment/101553363
upvote count: 39
has comment: http://stackoverflow.com/comment/83331821
has body: Using Circles An easy option is to replace the scatter by a PatchCollection consisting of Circles of radius 0.5. circles = [plt.Circle((xi,yi), radius=0.5, linewidth=0) for xi,yi in zip(x,y)] c = matplotlib.collections.PatchCollection(circles) ax.add_collection(c) Using scatter with markers of size in data units The alternative, if a scatter plot is desired, would be to update the markersize to be in data units. The easy solution here would be to first draw the figure once, then take the axes size and calculate the markersize in points from it. import matplotlib.pyplot as plt import numpy as np vmin = 1 vmax = 11 x = np.random.randint(vmin, vmax, 5) y = np.random.randint(vmin, vmax, 5) fig, ax = plt.subplots(dpi=141) for v in np.arange(vmin, vmax): ax.axvline(v - 0.5) ax.axvline(v + 0.5) ax.axhline(v - 0.5) ax.axhline(v + 0.5) ax.set_xlim(vmin - 0.5, vmax + 0.5) ax.set_ylim(vmin - 0.5, vmax + 0.5) ax.set_aspect(1) fig.canvas.draw() s = ((ax.get_window_extent().width / (vmax-vmin+1.) * 72./fig.dpi) ** 2) ax.scatter(x, y, s = s, linewidth=0) plt.show() For some background on how markersize of scatters is used, see e.g. this answer. The drawback of the above solution is that is fixes the marker size to the size and state of the plot. In case the axes limits would change or the plot is zoomed, the scatter plot would again have the wrong sizing. Hence the following solution would be more generic. This is a little involved and would work similarly as Plotting a line with width in data units. import matplotlib.pyplot as plt import numpy as np vmin = 1 vmax = 32 x = np.random.randint(vmin, vmax, 5) y = np.random.randint(vmin, vmax, 5) fig, ax = plt.subplots() for v in np.arange(vmin, vmax): ax.axvline(v - 0.5) ax.axvline(v + 0.5) ax.axhline(v - 0.5) ax.axhline(v + 0.5) ax.set_xlim(vmin - 0.5, vmax + 0.5) ax.set_ylim(vmin - 0.5, vmax + 0.5) class scatter(): def __init__(self,x,y,ax,size=1,**kwargs): self.n = len(x) self.ax = ax self.ax.figure.canvas.draw() self.size_data=siz…
type: AcceptedAnswer
score: 39

http://stackoverflow.com/q/48034696
has answer: http://stackoverflow.com/a/62544331
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83039624
linked to: http://stackoverflow.com/q/39517522
tagged with: blob
upvote count: 12
has comment: http://stackoverflow.com/comment/83040552
has comment: http://stackoverflow.com/comment/83046151
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/48173742
has title: Python: How to download a blob url video?
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/70415302
has body: I'd like to download a video from a website with Python script, however, the video is served by a blob URL as below.
tagged with: python
score: 11
tagged with: python-requests
answer count: 4
tagged with: video
has comment: http://stackoverflow.com/comment/83039351
has answer: http://stackoverflow.com/a/48035491

docker-machine
tags question: http://stackoverflow.com/q/48036153
type: Tag
tag name: docker-machine

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/48133520
tags question: http://stackoverflow.com/q/48039728
tags question: http://stackoverflow.com/q/48078820
tags question: http://stackoverflow.com/q/48090839
tags question: http://stackoverflow.com/q/48125698
tags question: http://stackoverflow.com/q/48062300
tags question: http://stackoverflow.com/q/48046985
tag name: kivy-language
tags question: http://stackoverflow.com/q/48108800
tags question: http://stackoverflow.com/q/48140520
tags question: http://stackoverflow.com/q/48132151
tags question: http://stackoverflow.com/q/48021882

http://stackoverflow.com/q/48082090
favorite count: 0
has answer: http://stackoverflow.com/a/48085643
has answer: http://stackoverflow.com/a/48085618
has comment: http://stackoverflow.com/comment/83138735
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83146006
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83141350
has comment: http://stackoverflow.com/comment/83138634
type: Question
tagged with: numpy
has title: Python: How to pass subarrays of array into array function
has comment: http://stackoverflow.com/comment/83139420
has comment: http://stackoverflow.com/comment/83145176
has comment: http://stackoverflow.com/comment/83138682
tagged with: arrays
has comment: http://stackoverflow.com/comment/83141206
answer count: 2
upvote count: 1
has body: The ultimate goal of my question is that I want to generate a new array 'output' by passing the subarrays of an array into a function, where the return of the function for each subarray generates a new element into 'output'. My input array was generated as follows: aggregate_input = np.random.rand(100, 5) input = np.split(aggregate_predictors, 1, axis=1)[0] So now input appears as follows: print(input[0:2]) &gt;&gt;[[ 0.61521025 0.07407679 0.92888063 0.66066605 0.95023826] &gt;&gt; [ 0.0666379 0.20007622 0.84123138 0.94585421 0.81627862]] Next, I want to pass each element of input (so the array of 5 floats) through my function 'condition' and I want the return of each function call to fill in a new array 'output'. Basically, I want 'output' to contain 100 values. def condition(array): return array[4] &lt; 0.5 How do I pass each element of input into condition without using any nasty loops? ======== Basically, I want to do this, but optimized: lister = [] for i in range(100): lister.append(condition(input[i])) output = np.array(lister)
has comment: http://stackoverflow.com/comment/83146147
has comment: http://stackoverflow.com/comment/83145951
has comment: http://stackoverflow.com/comment/83141281

http://stackoverflow.com/q/48109266
downvote count: 0
score: 1
tagged with: pandas
tagged with: python
favorite count: 0
type: UnansweredQuestion
has body: I have the following Dataframe : temp = pd.DataFrame({ 'long_entry':[False,True,False,False], 'long_exit':[False,False,False,True] }) long_entry long_exit 0 False False 1 True False 2 False False 3 False True I add 2 more columns with 0 that will receive conditional values : temp['open_long']=0 temp['close_long']=0 temp['long']=0 long_entry long_exit open_long close_long long 0 False False 0 0 0 1 True False 0 0 0 2 False False 0 0 0 3 False True 0 0 0 What i am trying to do is to fill open_long, close_long and long according to the following conditions : First row will be 0 for all 3 columns, then for the next ones: open_long: if previous row long_entry == 0 and same row long_entry == True then open_long = 1, else open_long = 0 close_long: if previous row long value equals 1 and same row long_exit == True, then close_long = -1, else close_long= 0 long: just equal to same row open_long + same row close_long + previous row long the resulting Dataframe is : long_entry long_exit open_long close_long long 0 False False 0 0 0 1 True False 1 0 1 2 False False 0 0 1 3 False True 0 -1 0 I was able to do it using loop but since I am working with 10 years of daily data it is taking a lot of time to complete. What is the optimal way to approach this problem in Python ?
upvote count: 1
has title: Conditionally filling values in Pandas Dataframe
tagged with: dataframe
has answer: http://stackoverflow.com/a/48110172
type: Question
answer count: 1

http://stackoverflow.com/comment/83235974
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48117508
score: 0
has text: Dupe of https://stackoverflow.com/questions/17388213/find-the-similarity-percent-between-two-strings too?

http://stackoverflow.com/a/48067054
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48054334
has comment: http://stackoverflow.com/comment/83157381
score: 1
answers question: http://stackoverflow.com/q/48054334
upvote count: 1
has comment: http://stackoverflow.com/comment/83147688
has comment: http://stackoverflow.com/comment/83145363
has body: An appropriate way would be to create a class that manages operations: class Operation: def __init__(self): self.params = [] def setParams(self, params): self.params = params def process(self): # processing u, v = self.params result = u*v return result def toString(self): return "{}x{}".format(*self.params) Then an object of that kind is created as an attribute of the widget and the logic is handled, as it is a property that can be accessed in the whole scope of the class. To change the color I use the QPalette of the widget as shown in the following code: class ExampleApp(QtGui.QMainWindow,new_design6.Ui_MainWindow): def __init__(self): super(self.__class__, self).__init__() self.setupUi(self) self.exit_app.clicked.connect(self.close) self.get_new_problem.clicked.connect(self.generate_new_problem) self.check_result.clicked.connect(self.check_problem_result) self.operation = Operation() self.show_problem.setReadOnly(True) def generate_new_problem(self): self.show_problem.clear() self.input_result.clear() self.show_result.clear() pal = self.show_result.palette() pal.setColor(QtGui.QPalette.Base, QtCore.Qt.white) self.show_result.setPalette(pal) u = int(np.random.randint(0,11,1)) v = int(np.random.randint(0,11,1)) params = u, v self.operation.setParams(params) self.show_problem.setPlainText(self.operation.toString()) def check_problem_result(self): input_result_number = self.input_result.toPlainText() result = int(input_result_number) pal = self.show_result.palette() if self.operation.process() == result: result_string="Correct! Result is: {}".format(result) pal.setColor(QtGui.QPalette.Base, QtCore.Qt.green) else: result_string="Wrong! Result is: {} Try another one".format(result) pal.setColor(QtGui.QPalette.Base, QtCore.Qt.red) self.show_result.setPlainText(result_string) self.show_result.setPalette(pal)
has comment: http://stackoverflow.com/comment/83148288
has comment: http://stackoverflow.com/comment/83145454
type: AcceptedAnswer

http://stackoverflow.com/a/48138972
has comment: http://stackoverflow.com/comment/120841396
accepted answer of: http://stackoverflow.com/q/48105646
answers question: http://stackoverflow.com/q/48105646
has comment: http://stackoverflow.com/comment/120845574
upvote count: 9
type: AcceptedAnswer
downvote count: 0
score: 9
type: Answer
has body: When you call the method Start() you are starting the event loop, which means that the following instructions will not be executed. Tipically you start the event loop after you completed the VTK pipeline, i.e, after you defined your actors, mappers, etc. Have you checked this example here? https://www.vtk.org/Wiki/VTK/Examples/Python/Widgets/EmbedPyQt It works fine, but assumes that you have PyQt4. In order to work with PyQt5, I made a few changes. Try this: import sys import vtk from PyQt5 import QtCore, QtGui from PyQt5 import Qt from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor class MainWindow(Qt.QMainWindow): def __init__(self, parent = None): Qt.QMainWindow.__init__(self, parent) self.frame = Qt.QFrame() self.vl = Qt.QVBoxLayout() self.vtkWidget = QVTKRenderWindowInteractor(self.frame) self.vl.addWidget(self.vtkWidget) self.ren = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create source source = vtk.vtkSphereSource() source.SetCenter(0, 0, 0) source.SetRadius(5.0) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(source.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self.frame.setLayout(self.vl) self.setCentralWidget(self.frame) self.show() self.iren.Initialize() self.iren.Start() if __name__ == "__main__": app = Qt.QApplication(sys.argv) window = MainWindow() sys.exit(app.exec_()) Important note: if your qt application becomes increasingly complex and you will be using multiple QVTKRenderWindowInteractor objects in it, do not call the interactor through the Start() method. Otherwise, as I mentioned before, you are creating another unnecessary event loop inside your qt application (app.exec() starts the qt loop). In this case, I think you should call app.exec() after you declared you necessary objects. More information can be found in thes…

http://stackoverflow.com/q/48171887
has comment: http://stackoverflow.com/comment/83323638
tagged with: python
has answer: http://stackoverflow.com/a/48172324
favorite count: 0
has body: If I use the following code I end up with an overcrowded x-axis. I would like to show only every 10th number on the x axis. Meaning [0,10,...]. Any idea how to do this? import pandas as pd import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt a = pd.DataFrame({'y':np.random.randn(100)}) a['time']=a.index ax = sns.pointplot(x='time', y="y", data=a) plt.show()
type: UnansweredQuestion
tagged with: seaborn
has comment: http://stackoverflow.com/comment/83323601
has comment: http://stackoverflow.com/comment/83323424
downvote count: 1
tagged with: plot
score: 2
upvote count: 3
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/83323831
answer count: 1
tagged with: pandas
has title: Only show round numbers on x-axis in point plot

http://stackoverflow.com/a/48060637
answers question: http://stackoverflow.com/q/48060582
has body: Here you are storing your data as set. Sets in Python are unordered in nature. {a, b} (note comma , here) is a syntax of a set. Probably you want to store it as dict (if you want it as key-value pair) which has the syntax {a: b} (note here the colon : instead of ,). OR, may be you can store it as a tuple too. For example: import re sourceDataList = [ '2017-12-20 08:59:17;Value01\r\n', '2017-12-20 08:59:18;Value02\r\n', '2017-12-20 08:59:20;Value03\r\n', '2017-12-20 08:59:21;Value04\r\n' ] # --- Using Dictionary --- dataList = [] for line in sourceDataList: dataList.append({'RESULT' : re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip())}) # --- Using tuple --- dataList = [] for line in sourceDataList: dataList.append(('RESULT', re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip()))) Here are one-liners to get the same result: # For Dictionary dataList = [{'RESULT' : re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip())} for line in sourceDataList] # For Dictionary dataList = [('RESULT', re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip())) for line in sourceDataList] Here are the sample of the result that you'll receive: # --- For Dictionary --- [{'RESULT': 'Value01'}, {'RESULT': 'Value02'}, {'RESULT': 'Value03'}, {'RESULT': 'Value04'}] # --- For tuple --- [('RESULT', 'Value01'), ('RESULT', 'Value02'), ('RESULT', 'Value03'), ('RESULT', 'Value04')]
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/q/48016766
tagged with: python-3.5
has answer: http://stackoverflow.com/a/48048177
answer count: 1
accepted answer: http://stackoverflow.com/a/48048177
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83002890
type: Question
score: 3
tagged with: type-hinting
has body: We have a method in our Python 3.5 application where one of the in-parameters (new_value in the example below) can be of any type, and we're wondering if there is a type hint that we can use for this case? def update(self, col_name: str, new_value) -&gt; None: (We would like the type hint for documentation purposes, to make the code easier to read) Grateful for help!
has title: Specifying "any" type using Python type hints
upvote count: 3

http://stackoverflow.com/q/48172983
tagged with: mandelbrot
type: Question
upvote count: 2
has body: The most pressing problem i have with my code is that when i change the X and Y dimensions to for example X = 501, Y = 500 the mandelbrot set tears completely (see pictures). The X and Y axis are also inverted. My goal is to achieve a similar result as this http://code.activestate.com/recipes/579048-python-mandelbrot-fractal-with-tkinter/ and from what i can gather i should create a coordinate mapping centralised around the origin? Any help would be greatly appreciated. from tkinter import * import numpy as np from numba import jit X = 500 Y = 500 maxIter = 500 minR = -3 minI = -2 maxR = 2 maxI = 2 @jit def mandelbrot_set(minR,maxR,minI,maxI,X,Y,maxIter): r1 = np.linspace(minR, maxR, X) r2 = np.linspace(minI, maxI, Y) return (r1,r2,[mandelbrot(complex(r, i),maxIter) for r in r1 for i in r2]) @jit def mandelbrot(c,max): z = c for n in range(max): if abs(z) &gt; 4: return n z = z*z + c return 255 set = mandelbrot_set(minR,maxR,minI,maxI,X,Y,maxIter) window = Tk() canvas = Canvas(window, width = X, height = Y, bg = "#FFFFFF", highlightthickness=0) canvas.pack() img = PhotoImage(width = X, height = Y) canvas.create_image((0, 0), image = img, state = "normal", anchor = NW) hexstring = "" counter = 0 for imaginary in set[1]: hexstring += "{ " for real in set[0]: if set[2][counter] == 0: hexstring += "#000000 " else: hexstring += "#" + "%02x" % set[2][counter] + "%02x" % set[2][counter] + "%02x" % set[2][counter] + " " counter += 1 hexstring += "} " img.put(hexstring) window.mainloop() Normal: Broken mandelbrot:
linked to: http://stackoverflow.com/q/44528552
answer count: 1
accepted answer: http://stackoverflow.com/a/48173519
has comment: http://stackoverflow.com/comment/83345894
has answer: http://stackoverflow.com/a/48173519
has title: Mandelbrot set 'tearing' at different X and Y values
tagged with: python
favorite count: 0
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83326042
tagged with: graphics
type: AnsweredQuestion

http://stackoverflow.com/comment/83046038
has text: The code here is mostly irrelevant, actually. (or perhaps I should say *likely* mostly irrelevant!)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48037857

http://stackoverflow.com/q/48098020
linked to: http://stackoverflow.com/q/14812342
tagged with: import
has answer: http://stackoverflow.com/a/48098125
answer count: 1
downvote count: 0
has body: using matplotlib.pyplot doesn't work unlike the flask.app despite the similarity in the arrangement of pyplot.py and app.py in their packages. Here is the explanation. The flask package contains the following modules. __init__.py app.py Note. These are not the only modules that flask contains. Whenever I want to use the app.py module i can do it in two ways. Here they are below. &gt;&gt;&gt; import flask &gt;&gt;&gt; flask.app &lt;module 'flask.app' from 'C:\\Python34\\lib\\site-packages\\flask\\app.py'&gt; &gt;&gt;&gt; from flask import app &gt;&gt;&gt; app &lt;module 'flask.app' from 'C:\\Python34\\lib\\site-packages\\flask\\app.py'&gt; &gt;&gt;&gt; Now let's take a look at the matplotlib package. The matplotlib package contains the following modules. __init__.py pyplot.py Note. These are not the only modules that matplotlib contains. Now I will use the same approach as I did for flask to use the pyplot.py module but this time the first approach doesn't work and I do not understand why. Here it is. &gt;&gt;&gt; import matplotlib &gt;&gt;&gt; matplotlib.pyplot Traceback (most recent call last): File "&lt;pyshell#20&gt;", line 1, in &lt;module&gt; matplotlib.pyplot AttributeError: 'module' object has no attribute 'pyplot' &gt;&gt;&gt; from matplotlib import pyplot &gt;&gt;&gt; pyplot &lt;module 'matplotlib.pyplot' from 'C:\\Python34\\lib\\site-packages\\matplotlib\\pyplot.py'&gt; &gt;&gt;&gt; Being self learner can't help you with problem like this. Any idea is appreciated.
score: 1
has title: How does import works in python?
favorite count: 0
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83171158
upvote count: 1
type: Question

http://stackoverflow.com/comment/83112021
type: QuestionComment
comment on: http://stackoverflow.com/q/48069068
score: 0
type: Comment
has text: Maybe consider amend this question with the actual code in question that uses whatever messenger bot API that you may be using.

http://stackoverflow.com/comment/83361951
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48169602
type: QuestionComment
has text: Check what? You are just repeating what's already in the question. Please provide complete (but minimal) Java code, including import statements.

http://stackoverflow.com/comment/83160171
comment on: http://stackoverflow.com/q/48081813
score: 0
type: Comment
type: QuestionComment
has text: The queryset you have posted looks fine. Perhaps you have not saved your changes or restarted your server after changing code, so you are not running the code you think your are. Or there might be an error in your urls/view (which you haven't shown), so that `archivos` is not the queryset you think it is.

http://stackoverflow.com/comment/83326978
comment on: http://stackoverflow.com/q/48173238
type: Comment
type: QuestionComment
has text: @langme, ok. What if to try `appium.find_element_by_id("title").send_keys(Keys.RIGHT)` between those lines?
score: 0

http://stackoverflow.com/q/48169885
has answer: http://stackoverflow.com/a/48169942
downvote count: 1
has title: Python counting next to one another
type: Question
duplicate of: http://stackoverflow.com/q/493386
score: -1
upvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
has body: I have this code but i would like the numbers to be printed next to one another but it doesn't do that it just prints down the screen instead of filling up the screen. import random count=2 while count&gt;0: print(random.randint(0,1))
tagged with: python

http://stackoverflow.com/q/48052705
tagged with: python-3.x
has body: I am a beginner in python and I wish coding a function having a variable number of parameters. This function must count the number of occurance of each character existing in all input strings. let's rename this function as carCompt. For example : carCompt("Sophia","Raphael","Alexandre") the result should be: {'A':5, 'D':1, 'E':3, 'H':2, 'L':1, 'N':1, 'O':1, 'P':2, 'R':2, 'S':1, 'X':1} thank you for help!!
tagged with: python
accepted answer: http://stackoverflow.com/a/48052741
downvote count: 6
type: AnsweredQuestion
score: -5
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/991350
has comment: http://stackoverflow.com/comment/83077655
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48052741
has title: Coding a function in python wihch count the number of occurances
has comment: http://stackoverflow.com/comment/83077811
has comment: http://stackoverflow.com/comment/83077668
answer count: 1
favorite count: 0

http://stackoverflow.com/a/52839149
has comment: http://stackoverflow.com/comment/131557619
type: AcceptedAnswer
upvote count: 23
has comment: http://stackoverflow.com/comment/127587290
answers question: http://stackoverflow.com/q/48030130
type: Answer
has body: You can change your code to something like below to have complexity O(N). def solution(A): s = sum(A) m = float('inf') left_sum = 0 for i in A[:-1]: left_sum += i m = min(abs(s - 2*left_sum), m) return m
accepted answer of: http://stackoverflow.com/q/48030130
downvote count: 0
score: 23
has comment: http://stackoverflow.com/comment/120725874

http://stackoverflow.com/q/48149491
type: UnansweredQuestion
has body: This is what I'm going for: Is there anything in, say, Matplotlib that can achieve this? I've looked at the Matplotlib gallery, but couldn't find anything that looks like it.
has answer: http://stackoverflow.com/a/67525872
tagged with: python
score: 1
has title: How to make a velocimeter-style plot in Python?
upvote count: 1
tagged with: plot
type: Question
tagged with: matplotlib
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83277594

http://stackoverflow.com/comment/83278544
comment on: http://stackoverflow.com/q/48150091
has text: @DeepSpace Updated my post.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48119632
downvote count: 0
score: 1
type: Question
tagged with: python-import
tagged with: ansible
upvote count: 1
has body: Introduction I want to run Python code (test.py) on a remote host with Ansible. This has not been a problem until I pulled out some functions into another module. When running a playbook with ansible-playbook test.yml (contents below, some details removed): - name: Perform tests hosts: ... vars_files: ... tasks: - name: run test script script: "{{ playbook_dir }}/scripts/test.py I get the following error: Traceback (most recent call last): File "/home/&lt;removed&gt;/.ansible/tmp/ansible-tmp-1515175369.61-59422518925475/test.py", line 11, in &lt;module&gt; import utils ImportError: No module named utils However, running python scripts/test.py on the target machine runs without a hitch. Details Here's my directory layout: + scripts/ - __init__.py - test.py - utils.py Inside test.py, I have this line: import utils Question How can I import the utils module from inside test.py?
answer count: 1
has title: How to remotely execute Python with more than one module through Ansible?
favorite count: 0
has answer: http://stackoverflow.com/a/48122955
accepted answer: http://stackoverflow.com/a/48122955
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83107028
comment on: http://stackoverflow.com/q/48066816
type: QuestionComment
score: 1
has text: The keyword you search for is intersection.
type: Comment

http://stackoverflow.com/comment/83026526
comment on: http://stackoverflow.com/q/48028234
type: Comment
type: QuestionComment
has text: what is your expected out put
score: 0

http://stackoverflow.com/comment/83260253
has text: Hey! Could you tell me what this mean "I say if the semantics of your code do not require that the bytes be a stream". When to use bytes as stream?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48134752
type: Comment

http://stackoverflow.com/comment/83418711
type: AnswerComment
score: 0
type: Comment
has text: @ShpielMeister can you give an example? I tried error handling yet it is not skipping the offending rows. How should I call out the corrupted rows?
comment on: http://stackoverflow.com/a/48134056

http://stackoverflow.com/q/48142859
tagged with: parallel-processing
type: AnsweredQuestion
has title: Distributing Python module - Spark vs Process Pools
linked to: http://stackoverflow.com/q/48148840
type: Question
tagged with: pyspark
score: 0
has answer: http://stackoverflow.com/a/48143216
tagged with: apache-spark
answer count: 1
tagged with: distribute
has body: I've made a Python module that extracts handwritten text from PDFs. The extraction can sometimes be quite slow (20-30 seconds per file). I have around 100,000 PDFs (some with lots of pages) and I want to run the text extraction on all of them. Essentially something like this: fileNameList = ['file1.pdf','file2.pdf',...,'file100000.pdf'] for pdf in fileList: text = myModule.extractText(pdf) # Distribute this function # Do stuff with text We used Spark once before (a coworker, not me) to distribute indexing a few million files from an SQL DB into Solr across a few servers, however when researching this it seems that Spark is more for parallelizing large data sets, not so much distributing a single task. For that it looks like Python's inbuilt 'Process Pools' module would be better, and I can just run that on a single server with like 4 CPU cores. I know SO is more for specific problems, but was just wanting some advice before I go down the entirely wrong road. For my use case should I stick to a single server with Process Pools, or split it across multiple servers with Spark?
tagged with: python
accepted answer: http://stackoverflow.com/a/48143216

http://stackoverflow.com/comment/83172801
score: 0
type: Comment
has text: Glad can help you!
comment on: http://stackoverflow.com/a/48074222
type: AnswerComment

http://stackoverflow.com/q/48127684
has comment: http://stackoverflow.com/comment/83234246
answer count: 1
tagged with: utf-8
has comment: http://stackoverflow.com/comment/83232137
has comment: http://stackoverflow.com/comment/83232395
type: UnansweredQuestion
tagged with: non-ascii-characters
tagged with: python
has body: I write codes that contain non-ASCII characters like this; print "Öüç" I know that Python's default encoding is ASCII. So I add this to my code. #-*- coding:utf-8 -*- When I launch my code, "Öüç" string appear like this; ├û├╝├ğ What should I do?
has answer: http://stackoverflow.com/a/48128258
has comment: http://stackoverflow.com/comment/83233104
has title: UTF-8 Character Printing Error Python 2.7
type: Question
has comment: http://stackoverflow.com/comment/83232301
tagged with: python-2.7
score: 0

http://stackoverflow.com/a/48143201
answers question: http://stackoverflow.com/q/48143126
score: 1
accepted answer of: http://stackoverflow.com/q/48143126
type: AcceptedAnswer
downvote count: 0
has body: First row has headers &lt;th&gt; instead of &lt;td&gt; so you get empty tds - and you have to check size for tds if len(tds) &gt; 0: print(tds[0].text) or shorter if tds: print(tds[0].text) Or you can skip first row using [1:] for tr in soup.find_all('tr')[1:]: tds = tr.find_all('td') print(tds[0].text)
type: Answer
has comment: http://stackoverflow.com/comment/83264606
upvote count: 1

pyqt5
tags question: http://stackoverflow.com/q/48028103
tags question: http://stackoverflow.com/q/48104077
type: Tag
tags question: http://stackoverflow.com/q/48099359
tags question: http://stackoverflow.com/q/48037355
tags question: http://stackoverflow.com/q/48121711
tags question: http://stackoverflow.com/q/48084565
tags question: http://stackoverflow.com/q/48041277
tags question: http://stackoverflow.com/q/48157811
tags question: http://stackoverflow.com/q/48022124
tags question: http://stackoverflow.com/q/48053484
tags question: http://stackoverflow.com/q/48039309
tags question: http://stackoverflow.com/q/48095573
tags question: http://stackoverflow.com/q/48046462
tags question: http://stackoverflow.com/q/48091332
tags question: http://stackoverflow.com/q/48155694
tags question: http://stackoverflow.com/q/48105246
tags question: http://stackoverflow.com/q/48077946
tags question: http://stackoverflow.com/q/48125641
tags question: http://stackoverflow.com/q/48053521
tags question: http://stackoverflow.com/q/48137040
tags question: http://stackoverflow.com/q/48049836
tags question: http://stackoverflow.com/q/48105646
tags question: http://stackoverflow.com/q/48077955
tags question: http://stackoverflow.com/q/48130524
tags question: http://stackoverflow.com/q/48150321
tags question: http://stackoverflow.com/q/48136977
tags question: http://stackoverflow.com/q/48022786
tags question: http://stackoverflow.com/q/48121393
tags question: http://stackoverflow.com/q/48057638
tags question: http://stackoverflow.com/q/48097207
tags question: http://stackoverflow.com/q/48140576
tags question: http://stackoverflow.com/q/48142341
tags question: http://stackoverflow.com/q/48070224
tags question: http://stackoverflow.com/q/48050477
tags question: http://stackoverflow.com/q/48073261
tag name: pyqt5
tags question: http://stackoverflow.com/q/48103685
tags question: http://stackoverflow.com/q/48053045
tags question: http://stackoverflow.com/q/48168432
tags question: http://stackoverflow.com/q/48132799
tags question: http://stackoverflow.com/q/48047866
tags question: http://stackoverflow.com/q/48139087
tags question: http://stackoverflow.com/q/48036742
tags question: http://stackoverflow.com/q/48080650
tags question: http://stackoverflow.com/q/48107167
tags question: http://stackoverflow.com/q/48123219
tags question: http://stackoverflow.com/q/48096085
tags question: http://stackoverflow.com/q/48151935
tags question: http://stackoverflow.com/q/48036069
tags question: http://stackoverflow.com/q/48128935

http://stackoverflow.com/q/48118647
has comment: http://stackoverflow.com/comment/83213975
has comment: http://stackoverflow.com/comment/83214084
tagged with: random
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48119026
has title: How to generate random numbers with if-statement in Python?
downvote count: 0
score: 1
favorite count: 0
has body: I would like to generate random numbers with a specific restriction using python. The code should do the following: If an entered number is: 0, then generate 0 random non-recurrent numbers &lt;1, then generate 1 random non-recurrent numbers &lt;9, then generate 2 random non-recurrent numbers &lt;15, then generate 3 random non-recurrent numbers &lt;26, then generate 5 random non-recurrent numbers &lt;51, then generate 8 random non-recurrent numbers &lt;91, then generate 13 random non-recurrent numbers &lt;151, then generate 20 random non-recurrent numbers &lt;281, then generate 32 random non-recurrent numbers The value of the random numbers should be limited by the value of the entered number. So if a 75 is entered, then the code should generate 13 random numbers with being 75 the highest value of the 13 numbers. 75 doesn't have to be the actual highest number, just in terms of max value. My guess was to use numpy. Here is what I got until now (with an users help). num_files=[0,1,9,...] num_nums=[0,1,2,3,5,...] for zipp in zip(num_files,num_nums) if len(docx_files)&lt;zipp[0]: list_of_rands=np.random.choice(len(docx_files)+1, zipp[1],replace=False) Any ideas or more starting points?
has comment: http://stackoverflow.com/comment/83214178
has comment: http://stackoverflow.com/comment/83213923
has answer: http://stackoverflow.com/a/48118890
type: Question
has answer: http://stackoverflow.com/a/48118960
has answer: http://stackoverflow.com/a/48118871
tagged with: python
possible better answer: http://stackoverflow.com/a/48118916
has comment: http://stackoverflow.com/comment/83214017
has answer: http://stackoverflow.com/a/48118916
has comment: http://stackoverflow.com/comment/83214223
has answer: http://stackoverflow.com/a/48119555
upvote count: 1
answer count: 7
has answer: http://stackoverflow.com/a/48118976
tagged with: numpy
has comment: http://stackoverflow.com/comment/83213708
has comment: http://stackoverflow.com/comment/83214006
has answer: http://stackoverflow.com/a/48119026
has comment: http://stackoverflow.com/comment/83213858
has comment: http://stackoverflow.com/comment/83213821

http://stackoverflow.com/comment/83213093
has text: Test_Scrape.py runs without error when I run it from the command line, all packages are installed properly so there shouldn't be an error when run
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48118152
type: QuestionComment

http://stackoverflow.com/q/48039167
has answer: http://stackoverflow.com/a/48039245
has answer: http://stackoverflow.com/a/48039422
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48039422
has body: I'm new to Python and haven't gotten into any optimization work yet. I'm attempting to take a bunch of files that themselves are already pretty large and combine them into one large file that will probably wind up being close to 50-100GB would be my guess. More memory than I have at any rate. I was given the code below and it works great for small files. When I try to run it over the actual files for my use case, it will totally lock up my computer. I understand that Pandas is fast. I'm guessing that data frames are stored in memory. If that is the case then that is probably what is wrecking stuff up here. Is there any kind or mechanism to spill to disk or possibly write to an existing file instead of trying to hold the whole thing in a dataframe before writing to disk? Or possibly another option that I didn't think of? import pandas as pd import os file_masks = ['fhv', 'green', 'yellow'] def combine_files(file_mask): csvfiles = [] for path, directories, files in os.walk('TaxiDriveData/'): csvfiles.extend([os.path.join(path, fn) for fn in files if fn.startswith(file_mask)]) df = pd.concat((pd.read_csv(fn) for fn in csvfiles)) df.to_csv(os.path.join('TaxiDriveCombinedData', file_mask + '_trip_data.csv'), index=False) for m in file_masks: combine_files(m)
type: Question
accepted answer: http://stackoverflow.com/a/48039245
tagged with: optimization
has comment: http://stackoverflow.com/comment/83048782
score: 0
answer count: 2
has title: What would make this code that combines some flat files run faster?
tagged with: python-3.x

http://stackoverflow.com/a/48086273
has comment: http://stackoverflow.com/comment/83235444
has comment: http://stackoverflow.com/comment/83186465
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83182210
has comment: http://stackoverflow.com/comment/83180722
has comment: http://stackoverflow.com/comment/83181067
score: 1
has comment: http://stackoverflow.com/comment/83182810
upvote count: 1
has body: To get the full product of the lists, you want: list(itertools.product(*tuple1)) which with your inputs will be 1.6M elements: ['1C5e1Dc9CP', '1C5e1Dc9CF', '1C5e1Dc9CC', '1C5e1Dc9OP', '1C5e1Dc9OF', '1C5e1Dc9OC', '1C5e1Dc9DP', '1C5e1Dc9DF', '1C5e1Dc9DC', '1C5e1Dc90P' ...] To chunk this, write a chunking function: def chunker(gen, size): while True: lst = [] for _ in range(size): lst.append(next(gen)) yield lst product_generator = itertools.product(*tuple1) chunks = chunker(product_generator, 50000) then you get each chunk via chunk = next(chunks) Below is the previous answer, which does not generate a complete product of the lists: This generates a list and works correctly with duplicates for arbitrary lists where you want to iterate a single element across the whole base. full = [] for piece_index in range(len(tuple1)): for inner_index in range(0 if piece_index == 0 else 1, len(tuple1[piece_index])): line = "" for index in range(len(tuple1)): line += tuple1[index][inner_index if piece_index == index else 0] full.append(line) This works by going list by list, element by element, and building a string around that element. It also skips the first element in every list except the first, as that is just a duplicate of the first element. piece_index keep track of which sublist we're currently working on. inner_index keeps track of which element in that sublist we're currently building a string about index is which character in that string built around tuple1[piece_index][inner_index] we're currently on. Result: ['1C5e1Dc9CP', 'xC5e1Dc9CP', 'tC5e1Dc9CP', 'fC5e1Dc9CP', 'TC5e1Dc9CP', '1D5e1Dc9CP', '165e1Dc9CP', '1C9e1Dc9CP', '1CJe1Dc9CP', '1CDe1Dc9CP', '1C5a1Dc9CP', '1C5o1Dc9CP', '1C5x1Dc9CP', '1C5f1Dc9CP', '1C5z1Dc9CP', '1C5exDc9CP', '1C5e7Dc9CP', '1C5efDc9CP', '1C5eTDc9CP', '1C5e1Oc9CP', '1C5e10c9CP', '1C5e1Bc9CP', '1C5e18c9CP', '1C5e1Qc9CP', '1C5e1qc9CP', '1C5e1Da9CP', '1C5e1DcJCP', '1C5e1Dc7CP', '1C5e1DcfCP', '1C5e1DcICP', '1C5e1DcJCP', '1C5e1Dc9OP', '1C5e1Dc9DP', '1C5e1…
has comment: http://stackoverflow.com/comment/83170409
answers question: http://stackoverflow.com/q/48085830
has comment: http://stackoverflow.com/comment/83178299
has comment: http://stackoverflow.com/comment/83181042
has comment: http://stackoverflow.com/comment/83181170
has comment: http://stackoverflow.com/comment/83180570
has comment: http://stackoverflow.com/comment/83180849
has comment: http://stackoverflow.com/comment/83186156
has comment: http://stackoverflow.com/comment/83180897

http://stackoverflow.com/comment/83190453
type: AnswerComment
has text: Made the edit however the error message remains the same. Thanks though
type: Comment
comment on: http://stackoverflow.com/a/48107476
score: 0

http://stackoverflow.com/q/48097297
upvote count: 1
has answer: http://stackoverflow.com/a/48097485
score: 1
type: Question
answer count: 2
has title: Upload an image blob from Ajax to Django
downvote count: 0
tagged with: javascript
tagged with: jquery
has body: I am trying to to upload an image to Django using Ajax. Ajax code: function sendImage() { console.log(blob); var fd = new FormData(); fd.append('image', blob); var tet = $.ajax({ url: '/login/photoverify/', type: 'POST', data: fd, async: false, contentType: false, processData: false, success: function (response) { console.log(response.driverBeacon); document.getElementById('username').setAttribute('value', response.username); }, error: function (error) { console.log(error); } }).responseText; } Django Code: def imageVerify(request): if request.method == 'POST': log.info('Inside imageVerify') myform = forms.Form(request.POST, request.FILES) log.info("Done loading form") if myform.is_valid(): log.info(myform.cleaned_data) file = myform.cleaned_data['image'] But myform.cleaned_data is empty. Can someone please help?
favorite count: 0
tagged with: ajax
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48144399
tagged with: django

http://stackoverflow.com/comment/83221016
type: QuestionComment
comment on: http://stackoverflow.com/q/48104071
score: 0
type: Comment
has text: @drew010 I don't really get it. So what am I supposed to do? Do the proxies, then what? Where do I put that?

http://stackoverflow.com/q/48091943
has answer: http://stackoverflow.com/a/48092040
tagged with: python
tagged with: dictionary
favorite count: 0
has comment: http://stackoverflow.com/comment/83158585
has comment: http://stackoverflow.com/comment/83159301
has comment: http://stackoverflow.com/comment/83158948
has comment: http://stackoverflow.com/comment/83158375
has body: suppose I have a dict like that: dict = {'people': [&lt;Bob&gt;], 'animals': [&lt;Frank&gt;]} Bob and Frank are two objects with attributes: Bob = MethodForCreateAPerson(){ Frank = MethodForCreateAnimals(){ name = 'Bob', name = 'Frank', age = 30, age = 6, sex = 'm' sex = 'w' } } The Question is: How can I access Bob's and Frank's attributes when they are values of a dict? In other words, I need to check the attributes of the objects returned from dict.values(). Thanks for help
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83159527
has comment: http://stackoverflow.com/comment/83158242
has title: Python Accessing attributes of an object as a dict value
has comment: http://stackoverflow.com/comment/83159367
type: Question
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48092040

testing
tags question: http://stackoverflow.com/q/48054392
tags question: http://stackoverflow.com/q/48111426
tags question: http://stackoverflow.com/q/48084891
tags question: http://stackoverflow.com/q/48061607
tag name: testing
tags question: http://stackoverflow.com/q/48111684
tags question: http://stackoverflow.com/q/48173238
tags question: http://stackoverflow.com/q/48069866
tags question: http://stackoverflow.com/q/48040994
tags question: http://stackoverflow.com/q/48102099
type: Tag
tags question: http://stackoverflow.com/q/48042132
tags question: http://stackoverflow.com/q/48126918

http://stackoverflow.com/q/48125961
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48152465
has body: I am building a simple app. I want some values in my CSV to be updated every 15 minutes. I want this part of my app to run in the background to prevent blocking the interface. I couldn't get it to work the way I want to. My code: # I'm using the pandas, sched and time imports here: #INTERFACE @app.route("/") def home(): s = sched.scheduler(time.time, time.sleep) s.enter(15, 1, timer) s.run() return render_template("index.html") #TIMER def timer(): timer = 0 csv_file='C:\Python27\Walmart\sheet.csv' print("UPDATING") data_df = pd.read_csv(csv_file) print("READ") for i, row in data_df.iterrows() : sku = data_df.iloc[i]['Walmart SKU'] print (sku) if sku is '': break else: update(sku) print("Item Updated") print("UPDATECOMPLETE") home() #UPDATE def update(sku): lookup=str(sku) lookup = lookup.replace('.0', '') product = wapy.product_lookup(lookup) ts = time.time() st = datetime.datetime.today().strftime('%Y-%m-%d %I:%M %p') print (product.name) if product.available_online is 'TRUE': instock = 'yes' else: instock ='no' quote_page = product.product_url page = urlopen(quote_page) soup = BeautifulSoup(page, 'html.parser') sold_box = soup.find('a', attrs={'class': 'font-bold prod-SoldShipByMsg'}) sold = sold_box.text.strip() left_box = soup.find('div', attrs={'class': 'prod-ProductOffer-urgencyMsg'}) left = left_box.text.strip() if left is '': stock=product.stock else: stock=left # fields=[lookup + ',' + '$'+str(product.sale_price) + ',' + instock + ',' + stock + ',' + str(sold) + ',' + st + ',' + '$'+str(product.msrp)] pathto_csv = 'C:\Python27\Walmart\sheet.csv' data_df = pd.read_csv(pathto_csv) print("CSV READ") data_df.set_value([lookup], ['Price'], '$'+str(product.sale_price)) data_df.set_value([lookup], ['In Stock'], instock ) data_df.set_value([lookup], ['Quantity'], stock) data_df.set_value([lookup], ['Last Update'], str(sold)) data_df.set_value([lookup], ['Min Price'], '$'+str(product.msrp)) data_df.to_csv(pathto_csv) with open(r'sheet.csv', 'a') as f: writer = csv.w…
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Pandas and CSV Libraries CSV Manipulation
score: 1
type: Question
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/48171985
has comment: http://stackoverflow.com/comment/83323735
tagged with: regex
possible better answer: http://stackoverflow.com/a/48172016
has comment: http://stackoverflow.com/comment/83323503
has answer: http://stackoverflow.com/a/48172016
has comment: http://stackoverflow.com/comment/83323858
has comment: http://stackoverflow.com/comment/83323427
upvote count: 1
has comment: http://stackoverflow.com/comment/83323671
downvote count: 1
has title: How to check if a string is word with regex?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/12382696
has comment: http://stackoverflow.com/comment/83323855
has answer: http://stackoverflow.com/a/48172029
type: Question
answer count: 2
has body: I want to check if a string (like 'hello') input by user only contains one word and nothing else. Like only true for those contains only [a-zA-Z] and no whitespace or dot or underscore or another word. For example: 'hello' true 'hello_' false 'hello world' false 'h.e.l.l.o' false I don't know how to write the regex. Need help.
accepted answer: http://stackoverflow.com/a/48172029
tagged with: string
has comment: http://stackoverflow.com/comment/83323478
has comment: http://stackoverflow.com/comment/83323562
favorite count: 0
has comment: http://stackoverflow.com/comment/83324238
linked to: http://stackoverflow.com/q/196345
score: 0
tagged with: python

http://stackoverflow.com/comment/83036884
type: Comment
has text: Actually, the caching behavior for modules can be explicitly overridden to import a module more than once. It's a terrible idea, but it can be done, you just delete the entry for the module in `sys.modules` then `import` it again, and you get a separate copy.
score: 1
comment on: http://stackoverflow.com/a/48033435
type: AnswerComment

http://stackoverflow.com/comment/83325597
comment on: http://stackoverflow.com/q/48172235
has text: I think part of your issue might be that `coordinates.x` and `coordinates.y` are collections of values rather than a single point. I think you just need to index those with the same index used on the dataframe.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48150512
has body: i am having a function that returns a json response in this format when printed in terminal [{"value": 17, "label": "PENDING_ENROUTE"}, {"value": 1, "label": "REJECTED_PREFIX_MISSING"}] but if i access the context variable holding the data in template it returns [{u&amp;#39;value&amp;#39;: 17, u&amp;#39;label&amp;#39;: u&amp;#39;PENDING_ENROUTE&amp;#39;}, {u&amp;#39;value&amp;#39;: 1, u&amp;#39;label&amp;#39;: u&amp;#39;REJECTED_PREFIX_MISSING&amp;#39;}] Anyone having an idea on how to resolve it, i have tried alot of ways but i couldn't find any solution. Somebody help.
has comment: http://stackoverflow.com/comment/83279684
has answer: http://stackoverflow.com/a/48150559
accepted answer: http://stackoverflow.com/a/48150559
tagged with: django
type: AnsweredQuestion
type: Question
answer count: 1
has title: Decoding Characters as printed in terminal
score: 0
tagged with: python

http://stackoverflow.com/comment/83263577
comment on: http://stackoverflow.com/q/48142682
type: Comment
type: QuestionComment
has text: there is also [some](https://stackoverflow.com/a/26230781/6689249) suggestion on how to download pdf. And can you provide example with embedded pdf (site link maybe)?
score: 0

http://stackoverflow.com/comment/83256536
comment on: http://stackoverflow.com/q/48138966
score: 0
has text: @VTT We'd love to prove Riemann hypothesis with C++ code :)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48168073
has body: I am wondering what's the best approach to turn a large number of images into a moving one in Python. A lot of examples I've found seem to deal with actual videos or video games, such as pygame, which seems over complicated for what I'm looking to do. I have created a loop, and would like the image to update every time the code runs through the loop. Is there a possibly a method in python to overplot each image and erase the previous image with each iteration? sweeps_no = 10 for t in range(sweeps_no): i = np.random.randint(N) j = np.random.randint(N) arr = nearestneighbours(lat, N, i, j) energy = delta_E(lat[i,j], arr, J) if energy &lt;= 0: matrix[i,j] *= matrix[i,j] elif np.exp(energy/T) &gt;= np.random.random(): matrix[i,j] *= -matrix[i,j] else: matrix[i,j] = matrix[i,j] t +=1 print t res.append(switch) image = plt.imshow(lat) plt.show() Also, I can't understand why the loop above doesn't result in 10 different images showing up when the image is contained in the loop.
linked to: http://stackoverflow.com/q/753190
has comment: http://stackoverflow.com/comment/83315478
has answer: http://stackoverflow.com/a/48169745
accepted answer: http://stackoverflow.com/a/48169745
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83315243
has comment: http://stackoverflow.com/comment/83315317
answer count: 1
has comment: http://stackoverflow.com/comment/83315460
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/83318457
tagged with: python
has title: Creating moving images in python

http://stackoverflow.com/comment/83168998
score: 2
comment on: http://stackoverflow.com/q/48096747
has text: The [getting started guide](https://docs.scipy.org/doc/numpy-dev/f2py/getting-started.html) indicates that it can be used for both C and Fortran. See [this also](https://scipy.github.io/old-wiki/pages/Cookbook/f2py_and_NumPy.html) (although somewhat dated).
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83089766
has text: Does [`unicodedata`](https://docs.python.org/3/library/unicodedata.html?#module-unicodedata) suffice? From the looks of it, it does not tell *everything* about each code point, but it's sure a lot.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48058402

http://stackoverflow.com/q/48135569
upvote count: 1
answer count: 1
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83249518
has title: Padding with Leading zeros for Pandas data frame column with data as numpy array
accepted answer: http://stackoverflow.com/a/48136273
tagged with: python
has comment: http://stackoverflow.com/comment/83249760
has comment: http://stackoverflow.com/comment/83249825
has comment: http://stackoverflow.com/comment/83248512
has answer: http://stackoverflow.com/a/48136273
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I have a pandas data frame df,I used following code to create the data frame import numpy as np import pandas as pd data = np.array([11234466, 77777777, 12345678, 23452345]) data1 = np.array([99999999, 66666666, 44332211, 56781234]) df=pd.DataFrame({'A' : [data.tolist()]}) df1=pd.DataFrame({'A' : [data1.tolist()]}) df=pd.concat([df,df1]) whose one column, Column A contains numpy array. with data type as object.The column A looks like A [11234466, 77777777, 12345678, 23452345] [99999999, 66666666, 44332211, 56781234] All the values are integer and mostly 8 digits number. I want to make it 10 digits string with leading zeros. Like this one A ['0011234466', '0077777777', '0012345678', '0023452345'] ['0099999999', '0066666666', '0044332211', '0056781234'] I thought to try below code df['A'] = df['A'].astype(str) df['A'] = df['A'].apply(lambda x: x.zfill(10)) However, this doesn't pad zeros but leave the column as it is. Can you suggest me how should I pad column A's value with leading zeros? Using Jazrel's suggestion, I'm getting this output A 0 [000000000[, 0000000001, 0000000001, 000000000... 0 [000000000[, 0000000009, 0000000009, 000000000... `
type: Question

http://stackoverflow.com/q/48136660
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
tagged with: html-parsing
type: Question
has title: Python BS4 Not Retrieving Results
has body: Using the below code, I am able to fetch "soup" without an issue. My goal is to ultimately fetch the title within the soup object, but I'm having trouble figuring out how to do it. In addition to below, I've also tried various iterations of soup['results'], soup.results, soup.get_text().results .. etc and not sure how to get to it. I can, of course, do soup.get_text() ... (some kind of search function for the string "title," but feel like there has to be a built-in method for this. 55)get_title() 54 ipdb.set_trace() ---&gt; 55 title = soup.html.head.title.string 56 title = re.sub(r'[^\x00-\x7F]+',' ', title) ipdb&gt; type(soup) &lt;class 'bs4.BeautifulSoup'&gt; ipdb&gt; soup.title ipdb&gt; print soup.title None ipdb&gt; soup {"status":"OK","copyright":"Copyright (c) 2018 The New York Times Company. All Rights Reserved.","section":"home","last_updated":"2018-01-07T06:19:00-05:00","num_results":42,"results":[{"section":"Briefing","subsection":"",**"title":"Trump, Palestinians, Golden Globes: Your Weekend Briefing"**, .... Code from __future__ import division import regex as re import string import urllib2 from bs4 import BeautifulSoup from cookielib import CookieJar import ipdb PARSER_TYPE = 'html.parser' def get_title(url): cj = CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) p = opener.open(url) soup = BeautifulSoup(p.read(), PARSER_TYPE) # This loads fine ipdb.set_trace() title = soup.html.head.title.string # This is sad title = re.sub(r'[^\x00-\x7F]+',' ', title) return title
upvote count: 1
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48136885
has comment: http://stackoverflow.com/comment/83250747

http://stackoverflow.com/comment/83069231
comment on: http://stackoverflow.com/a/48036575
type: Comment
has text: thank you for your input. i managed to use ```pyparsing``` module and ```pprint``` together with gvim (vi) to get what i want. (part auto and part manual). I will share my solution here after making improvements. sample pyparsing code: ```t1 = pp.nestedExpr(opener='{', closer='}').parseString(mytext); lst_t1 = t1.asList(); pprint.pprint(lst_t1, indent=4)``` then reverted to gvim for visualize the indents and search using indent pattern matching.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83246589
has text: You shouldn't use the variable name `list`, as it overwrites the built-in `list`. Also, doing `test=list` is pointless, as both variables point to the same list in memory and editing one will edit the other.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48134612
score: 0

http://stackoverflow.com/comment/83267416
has text: I found out that the problem is coming because of my data being not normalized and the variation of the numbers is very big. However if anyone can give me ideas how to make my model better always here and listening :)
comment on: http://stackoverflow.com/q/48143753
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83082143
type: Comment
has text: This needs to iterate over an Excel document of unknown length with unknown number of values to match against. I made a very simple sample of the data.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48054713

http://stackoverflow.com/comment/83075440
type: AnswerComment
has text: Also, the probability wouldn't be fixed at 10/180. The probability of choosing line `i`, given that `k` lines have already been chosen, will be `p = (10000 - k)/(180000 - i)`.
type: Comment
comment on: http://stackoverflow.com/a/48050896
score: 0

http://stackoverflow.com/q/48141626
tagged with: dynamic
linked to: http://stackoverflow.com/q/11376898
upvote count: 1
has answer: http://stackoverflow.com/a/48147473
downvote count: 1
type: Question
has body: what would be the best recommendation in order to move the 6 blue balls around the 3D field a) with a pygtk and threading matplot for the plot window? (menue in pygtk where the new position is given manually and the balls would move after a "Click Go") b) or something else? It seems that matplot is slow: 4s after starting the attached python script, the plot windows open and everything appear. Moving later manually the window (rotation) is very slow too (it is mandatory, I have access to that manual rotation function of the plot window in order to observe the position of the balls in the 3D field). Perhaps another library or programm should be used? For the reason 6 additional balls (light grey) must be added, it will become probably slow. The 3D rendering dont has to be good (just a bit non transparent 3D). Any recommendation is welcome before I go too far in that pygtk and matplotlib direction. The programm is for hobby sport and will help beginners to know where to have their position in a field and how to move (3D.. NOT 2D) from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import matplotlib.axes as axs import numpy as np import math from pylab import figure # parameter in m #swimminpool_width s_w = 10 #swimmingpool_length s_l = 18 #swimmingpool_depth s_d = 4 #exchange lane width el_w = 3 # ball radius b_r = 0.53 / (2 * math.pi) if __name__ == '__main__': # basket at the swimmingpool bottom in the middle x_basket1 = s_w / 2 y_basket1 = 0.24 # basket at the swimmingpool bottom in the middle x_basket2 = s_w / 2 y_basket2 = s_l - 0.24 # fig = plt.figure() ax1 = fig.add_subplot (111,projection='3d') # field xG = [0,10,10,0,0, 0,10,10,10,10,10, 0, 0,0, 0,10] yG = [0, 0, 0,0,0,18,18, 0, 0,18,18,18,18,0,18,18] zG = [0, 0, 4,4,0, 0, 0, 0, 4, 4, 0, 0, 4,4, 4, 4] ax1.plot_wireframe (xG,yG,zG,colors= (0,0,1,1)) # blue line game area # exchange area xW = [10,13,13,10,10,10,13,13,13,13,13,10,10,10,10,13] yW = [0, 0, 0, 0, 0,18,18, 0, 0,18,18,18,18, 0,18,…
has answer: http://stackoverflow.com/a/48215174
tagged with: matplotlib
score: 0
answer count: 2
tagged with: 3d
tagged with: pygtk
linked to: http://stackoverflow.com/q/8955869
has title: What is the best solution to move the 6 different blue balls with pyGTK?
favorite count: 0
linked to: http://stackoverflow.com/q/10374930
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/40890632

list
tags question: http://stackoverflow.com/q/48046565
tags question: http://stackoverflow.com/q/48063772
type: Tag
tags question: http://stackoverflow.com/q/48037575
tags question: http://stackoverflow.com/q/48054822
tags question: http://stackoverflow.com/q/48127586
tags question: http://stackoverflow.com/q/48159774
tags question: http://stackoverflow.com/q/48101278
tags question: http://stackoverflow.com/q/48045316
tags question: http://stackoverflow.com/q/48026448
tags question: http://stackoverflow.com/q/48057694
tags question: http://stackoverflow.com/q/48061280
tags question: http://stackoverflow.com/q/48169414
tags question: http://stackoverflow.com/q/48085512
tags question: http://stackoverflow.com/q/48065268
tags question: http://stackoverflow.com/q/48033318
tags question: http://stackoverflow.com/q/48062375
tags question: http://stackoverflow.com/q/48130038
tags question: http://stackoverflow.com/q/48068546
tags question: http://stackoverflow.com/q/48049947
tags question: http://stackoverflow.com/q/48063966
tags question: http://stackoverflow.com/q/48110003
tags question: http://stackoverflow.com/q/48159515
tags question: http://stackoverflow.com/q/48130932
tags question: http://stackoverflow.com/q/48018686
tags question: http://stackoverflow.com/q/48142074
tags question: http://stackoverflow.com/q/48110641
tags question: http://stackoverflow.com/q/48038883
tags question: http://stackoverflow.com/q/48158195
tags question: http://stackoverflow.com/q/48020089
tags question: http://stackoverflow.com/q/48128586
tags question: http://stackoverflow.com/q/48152273
tags question: http://stackoverflow.com/q/48086626
tags question: http://stackoverflow.com/q/48019561
tags question: http://stackoverflow.com/q/48046962
tags question: http://stackoverflow.com/q/48056160
tags question: http://stackoverflow.com/q/48070823
tags question: http://stackoverflow.com/q/48160343
tags question: http://stackoverflow.com/q/48170089
tags question: http://stackoverflow.com/q/48018999
tags question: http://stackoverflow.com/q/48142780
tags question: http://stackoverflow.com/q/48024154
tags question: http://stackoverflow.com/q/48088460
tags question: http://stackoverflow.com/q/48074511
tags question: http://stackoverflow.com/q/48142373
tags question: http://stackoverflow.com/q/48099095
tags question: http://stackoverflow.com/q/48156643
tag name: list
tags question: http://stackoverflow.com/q/48121163
tags question: http://stackoverflow.com/q/48070828
tags question: http://stackoverflow.com/q/48173305
tags question: http://stackoverflow.com/q/48050884
tags question: http://stackoverflow.com/q/48085830
tags question: http://stackoverflow.com/q/48120106
tags question: http://stackoverflow.com/q/48024167
tags question: http://stackoverflow.com/q/48044222
tags question: http://stackoverflow.com/q/48110712
tags question: http://stackoverflow.com/q/48054082
tags question: http://stackoverflow.com/q/48125304
tags question: http://stackoverflow.com/q/48026203
tags question: http://stackoverflow.com/q/48076780
tags question: http://stackoverflow.com/q/48084884
tags question: http://stackoverflow.com/q/48042805
tags question: http://stackoverflow.com/q/48136359
tags question: http://stackoverflow.com/q/48163846
tags question: http://stackoverflow.com/q/48164206
tags question: http://stackoverflow.com/q/48015231
tags question: http://stackoverflow.com/q/48160172
tags question: http://stackoverflow.com/q/48129418
tags question: http://stackoverflow.com/q/48019560
tags question: http://stackoverflow.com/q/48039229
tags question: http://stackoverflow.com/q/48143870
tags question: http://stackoverflow.com/q/48084224
tags question: http://stackoverflow.com/q/48062114
tags question: http://stackoverflow.com/q/48138978
tags question: http://stackoverflow.com/q/48140225
tags question: http://stackoverflow.com/q/48063310
tags question: http://stackoverflow.com/q/48144690
tags question: http://stackoverflow.com/q/48153804
tags question: http://stackoverflow.com/q/48082037

http://stackoverflow.com/comment/83082884
type: QuestionComment
comment on: http://stackoverflow.com/q/48055255
has text: The url is what I input in the address bar. And what do you mean by generate for me?
score: 0
type: Comment

http://stackoverflow.com/comment/83050403
comment on: http://stackoverflow.com/q/48039870
type: QuestionComment
type: Comment
has text: How did you install the wifi package? In what directory is it installed?
score: 0

http://stackoverflow.com/q/48096390
has comment: http://stackoverflow.com/comment/83167745
favorite count: 0
has comment: http://stackoverflow.com/comment/83167407
tagged with: python
possible better answer: http://stackoverflow.com/a/48096584
has answer: http://stackoverflow.com/a/48096589
has title: Starting a conversation with a chat bot hosted on Microsoft Azure through HTTP request in Python
has comment: http://stackoverflow.com/comment/83168179
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48096584
upvote count: 1
downvote count: 1
tagged with: http
type: Question
has body: A Microsoft tutorial shows that in order to set up a conversation with a bot I should issue the following HTTP request: POST https://directline.botframework.com/api/conversations Authorization: Bearer SECRET_OR_TOKEN My question is if I can achieve this with the following Python code: import requests r = requests.post('https://directline.botframework.com/api/conversations', params = {'Authorization':'Bearer ftmhNAqZ2tw.cwA.qIA.Xz2ZWfYJzxd8vJjcK9VmINWNLxlvKiM5jC8F_cbaf0s'}) If I print the response with print(r.content) it says: { "error": { "code": "BadArgument", "message": "Missing token or secret" } }
has comment: http://stackoverflow.com/comment/83167987
accepted answer: http://stackoverflow.com/a/48096589
has comment: http://stackoverflow.com/comment/83167793
score: 0
answer count: 2
tagged with: azure

http://stackoverflow.com/comment/83087487
has text: does this work `url_n=soup3.find('', class_ = 'next')['href']`? notice the underscore.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48057647
score: 2

http://stackoverflow.com/comment/83070510
score: 1
has text: You can not, since a function is procedural, you define the function when you a specific `func2()` when you call `func1()`. If you call `func1()` multiple times, you will define several `func2`s. Furthermore since it is procedural, it is possible that `func2` is never declared (in an `if` statement). Here you do not return the function, so unless with debugger-like hacking, that would be close to impossible.
comment on: http://stackoverflow.com/q/48049474
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48086708
has answer: http://stackoverflow.com/a/48086852
favorite count: 0
possible better answer: http://stackoverflow.com/a/48086804
type: Question
has answer: http://stackoverflow.com/a/48086804
tagged with: exception
tagged with: python
score: 10
has title: Python: statically detect unhandled exceptions
has comment: http://stackoverflow.com/comment/83148544
linked to: http://stackoverflow.com/q/27030716
has answer: http://stackoverflow.com/a/48088706
has body: I'm trying to write a highly-reliable piece of code in Python. The most common issue I run into is that after running for a while, some edge case will occur and raise an exception that I haven't handled. This most often happens when using external libraries - without reading the source code, I don't know of an easy way to get a list of all exceptions that might be raised when using a specific library function, so it's hard to know what to handle. I understand that it's bad practice to use catch-all handlers, so I haven't been doing that. Is there a good solution for this? It seems like it should be possible for a static analysis tool to check that all exceptions are handled, but I haven't found one. Does this exist? If not, why? (is it impossible? a bad idea? etc) I especially would like it to analyze imported code for the reason explained above.
answer count: 3
accepted answer: http://stackoverflow.com/a/48086852
upvote count: 10
has comment: http://stackoverflow.com/comment/83148499
has comment: http://stackoverflow.com/comment/83148482
has comment: http://stackoverflow.com/comment/83149059
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83148470
has comment: http://stackoverflow.com/comment/83148473
tagged with: static-analysis

http://stackoverflow.com/q/48152557
type: Question
tagged with: http://stackoverflow.com/tag/csv
has title: How to append the value of Radiobutton to a csv file
tagged with: python
possible better answer: http://stackoverflow.com/a/48152878
tagged with: tkinter
has answer: http://stackoverflow.com/a/48152878
score: 0
answer count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/48154359
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83287950
favorite count: 0
has answer: http://stackoverflow.com/a/48154359
has body: Am trying to append the value of radiobutton selected before printing the content in the entry field but am able to append the content in the entry widget to csv file. I would appreciate any help on how to go around achieve that. from tkinter import * import csv with open ("profile.csv", "w") as db: writer = csv.writer(db) writer.writerow(["NAME ", "GENDER"]) # create with heading def save_details(): global e1 # global variable to receive the data from entry data = e1.get() #Sex = R1.get # Sex = R2.get() totalinput = [ data] # Sex here to append to the csv file with open("profile.csv", "a") as savedb: w = csv.writer(savedb) w.writerow(totalinput) def validate(): value = option.get() # this for radiobutton now = new.get() # this for an entry widget if value != "male" and value != "female": print("An option must be selected") else: print(now) root = Tk() root.geometry("400x400") new = StringVar() e1 = Entry(root, textvariable=new) option = StringVar() R1 = Radiobutton(root, text="MALE", value="male", var=option, command=save_details, indicatoron=0) R2 = Radiobutton(root, text="FEMALE", value="female", var=option, command=save_details, indicatoron=0) button = Button(root, text="OK", command=validate) e1.pack() R1.pack() R2.pack() button.pack(side="bottom") root.mainloop()
has comment: http://stackoverflow.com/comment/83284317

http://stackoverflow.com/q/48027423
tagged with: python-3.x
linked to: http://stackoverflow.com/q/19686533
accepted answer: http://stackoverflow.com/a/48027443
has body: If I have two iterables of different lengths, how can I most cleanly pair them, re-using values from the shorter one until all values from the longer are consumed? For example, given two lists l1 = ['a', 'b', 'c'] l2 = ['x', 'y'] It would be desirable to have a function fn() resulting in pairs: &gt;&gt;&gt; fn(l1, l2) [('a', 'x'), ('b', 'y'), ('c', 'x')] I found I could write a function to perform this as such def fn(l1, l2): if len(l1) &gt; len(l2): return [(v, l2[i % len(l2)]) for i, v in enumerate(l1)] return [(l1[i % len(l1)], v) for i, v in enumerate(l2)] &gt;&gt;&gt; fn(l1, l2) [('a', 'x'), ('b', 'y'), ('c', 'x')] &gt;&gt;&gt; l2 = ['x', 'y', 'z', 'w'] &gt;&gt;&gt; fn(l1,l2) [('a', 'x'), ('b', 'y'), ('c', 'z'), ('a', 'w')] However, I'm greedy and was curious what other methods exist? so that I may select the most obvious and elegant and be wary of others. itertools.zip_longest as suggested in many similar questions is very close to my desired use case as it has a fillvalue argument which will pad the longer pairs. However, this only takes a single value, instead of wrapping back to the first value in the shorter list. As a note: in my use case one list will always be much shorter than the other and this may allow a short-cut, but a generic solution would be exciting too!
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/83027580
duplicate of: http://stackoverflow.com/q/19686533
type: AnsweredQuestion
downvote count: 2
upvote count: 1
type: Question
has title: Cleanest way to iterate over pair of iterables of different lengths, wrapping the shorter iterable?
has answer: http://stackoverflow.com/a/48027443
has answer: http://stackoverflow.com/a/48027454
answer count: 2
possible better answer: http://stackoverflow.com/a/48027454
favorite count: 0
tagged with: iterable

http://stackoverflow.com/a/48166659
answers question: http://stackoverflow.com/q/48079762
has comment: http://stackoverflow.com/comment/96768625
downvote count: 0
has comment: http://stackoverflow.com/comment/96765445
type: AcceptedAnswer
score: 10
upvote count: 10
has comment: http://stackoverflow.com/comment/83321336
type: Answer
has body: In general I see two possible solutions for your problem: Airflow has a PythonVirtualEnvOperator which allows a task to run in a virtualenv which gets created and destroyed automatically. You can pass a python_version and a list of requirements to the task to build the virtual env. Set up a docker registry and use a DockerOperator rather than a PythonOperator. This would allow teams to set up their own Docker images with specific requirements. This is how I think Heineken set up their airflow jobs as presented in their Airflow Meetup. I'm trying to see whether they posted their slides online but I can't seem to find them.
accepted answer of: http://stackoverflow.com/q/48079762

http://stackoverflow.com/comment/83210477
type: Comment
has text: `zip` is super useful. When you have a minute you should go over the documentation for it: https://docs.python.org/3/library/functions.html#zip
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48116944

http://stackoverflow.com/comment/83050254
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48039841
has text: I'm not sure if it'll help, but have you added `#/usr/bin/env python` at the top of your `Test_Cron.py` file (to let Linux know that it has to be run with Python) and given it execution permissions? (just for testing, do `chmod a+x /home/abc/anuj/TPA/Test_Cron.py` on a terminal... ) Either that, or change your `crontab` entry to `*/2 * * * * python /home/abc/anuj/TPA/Test_Cron.py` (see the `python`? In that entry, the "program" to run is `python` that will try to run `Test_Cron.py`)
type: Comment

http://stackoverflow.com/q/48101186
has title: json.dumps doesn't work for me
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48101225
upvote count: 2
tagged with: graphql
score: 2
type: AnsweredQuestion
has body: I wrote a small Python script to get a response from GitHub and its GraphQL API. Here is what I coded: import json def pp_json(json_thing, sort=True, indents=4): if type(json_thing) is str: print(json.dumps(json.loads(json_thing),sort_key=sort, indent=indents)) else: print(json.dumps(json_thing, sort_key=sort, indent=indents)) return None I start this function with the output of my request as you can see here: url = 'https://api.github.com/graphql' json = { "query" : """query { viewer { login name bio company location } }""" } api_token = "hiddencontent" headers = {'Authorization': 'token %s' % api_token} result_tokentest = requests.post(url=url, json=json, headers=headers) # just Response Code string_tokentest = result_tokentest.text print (result_tokentest) print (string_tokentest) pp_json(result_tokentest) I get following output: &lt;Response [200]&gt; {"data":{"viewer":{"login":"datasienceelmo","name":"E.Lmo","bio":"Rohdaten sind geil!!","company":"Hochschule Ulm","location":"Ulm"}}} --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-12-9c2eefbf15a2&gt; in &lt;module&gt;() 19 print (result_tokentest) 20 print (string_tokentest) ---&gt; 21 pp_json(result_tokentest) &lt;ipython-input-2-f2241ef62766&gt; in pp_json(json_thing, sort, indents) 4 print(json.dumps(json.loads(json_thing),sort_key=sort, indent=indents)) 5 else: ----&gt; 6 print(json.dumps(json_thing, sort_key=sort, indent=indents)) 7 return None AttributeError: 'dict' object has no attribute 'dumps' I am unable to understand what the problem with my Python interpreter is, because I imported JSON. And in the documentation I just read how to use it, and I did as they did.
type: Question
has answer: http://stackoverflow.com/a/48101225
answer count: 1
downvote count: 0
tagged with: github
favorite count: 0
tagged with: python

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/48053764
tags question: http://stackoverflow.com/q/48143571
tags question: http://stackoverflow.com/q/48077580
tag name: google-oauth

http://stackoverflow.com/a/48450068
has comment: http://stackoverflow.com/comment/88300700
has body: You would need to install pip3. On Linux, run first sudo apt update. Then the command would be: sudo apt install python3-pip On Mac, using brew, first brew install python3 Then brew postinstall python3 Try calling pip3 -V to see if it worked.
upvote count: 181
type: AcceptedAnswer
downvote count: 1
score: 180
has comment: http://stackoverflow.com/comment/94279606
has comment: http://stackoverflow.com/comment/107996535
has comment: http://stackoverflow.com/comment/100475970
has comment: http://stackoverflow.com/comment/107996641
type: Answer
has comment: http://stackoverflow.com/comment/88387282
accepted answer of: http://stackoverflow.com/q/48014769
has comment: http://stackoverflow.com/comment/114425248
answers question: http://stackoverflow.com/q/48014769
has comment: http://stackoverflow.com/comment/88495551

http://stackoverflow.com/comment/83067324
score: 0
type: AnswerComment
has text: Happy new year!
comment on: http://stackoverflow.com/a/48047864
type: Comment

http://stackoverflow.com/a/48141006
accepted answer of: http://stackoverflow.com/q/48138003
score: 1
answers question: http://stackoverflow.com/q/48138003
upvote count: 1
has body: This is a ISO 8601 compliant timestamp. There are various libraries which can help with these. But is your case, for a fixed format, you can use Python's dt.datetime.strptime and datetime.timedelta to calculate the seconds since epoch like: Code: def epoch_seconds_from_iso_8601_with_tz_offset(iso_8601): """ Convert ISO 8601 with a timezone offset to unix timestamp """ iso_8601_dt = dt.datetime.strptime(iso_8601[:-5], '%Y-%m-%dT%H:%M:%S') utc_at_epoch = dt.datetime(1970, 1, 1) epoch_without_tz_offset = (iso_8601_dt - utc_at_epoch).total_seconds() tz_offset = 60 * (60 * int(iso_8601[-4:-2]) + int(iso_8601[-2:])) if iso_8601[-5] == '-': tz_offset = -tz_offset return epoch_without_tz_offset - tz_offset Test Code: import datetime as dt t1 = epoch_seconds_from_iso_8601_with_tz_offset('2018-01-07T19:43:15+0000') t2 = epoch_seconds_from_iso_8601_with_tz_offset('2018-01-07T11:43:15-0800') epoch = 1515354195 assert epoch == t1 == t2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/70611664
type: Answer
has body: make sure everything in your app runs after apps.py. check to not importing any module in apps.py except AppConfig (or any django bult in module)
answers question: http://stackoverflow.com/q/48163641
score: 0

http://stackoverflow.com/comment/83022855
type: Comment
type: QuestionComment
has text: Ok, so this was a wild goose chase fo rme then! Thanks!
comment on: http://stackoverflow.com/q/48026452
score: 0

http://stackoverflow.com/a/48044246
score: 5
type: AcceptedAnswer
has body: Slicing is syntax, not a string. See the Slicings expressions reference documentation: The semantics for a slicing are as follows. The primary is indexed (using the same __getitem__() method as normal subscription) with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of a proper slice is a slice object (see section The standard type hierarchy) whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions. Bold emphasis mine. You can bypass this conversion (from slice syntax to slice() objects) by creating slice() objects directly; you can put them in tuples if need be. So numpy_array_to_slice[160:300,28:43] is equivalent to box = slice(160, 300), slice(28, 43) numpy_array_to_slice[box] I've omitted the step argument; it defaults to None when omitted. Extending this to your list would be: listofindexvalues = [ (slice(160, 300), slice(28, 43)), (slice(160, 300), slice(40, 55)), (slice(160, 300), slice(28, 43)) ] for box in listofindexvalues: sliced_array = numpy_array_to_slice[box]
upvote count: 5
has comment: http://stackoverflow.com/comment/83061028
accepted answer of: http://stackoverflow.com/q/48044222
type: Answer
answers question: http://stackoverflow.com/q/48044222
downvote count: 0

http://stackoverflow.com/q/48038409
duplicate of: http://stackoverflow.com/q/1690400
has comment: http://stackoverflow.com/comment/83047132
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/83047145
downvote count: 1
favorite count: 0
has body: This question is very simple, and I expect the answer will also be very simple. Is there a way that I can return the string corresponding to the name I have chosen to bind to an instance of an object? For example, if I have written the following line of code: tesla = Car(fuel='electric') I would like some function getname() that I can call roughly as follows: [In] tesla.*getname*() [Out] 'tesla' getname need not be called as a method of the object, I am also happy to call it as: [In] *getname*(tesla) [Out] 'tesla' I'm sure there must be some function that accomplishes this goal, but I have yet to find it. All I have found relating to the topic is the __name__ attribute of an object, but this seems to return the name of the class of the object (in this example, 'Car'), not the name bound to that object in the current environment.
type: UnansweredQuestion
has title: How can I return the name bound to an instance of an object?
tagged with: python
has comment: http://stackoverflow.com/comment/83047168
tagged with: object
tagged with: instance
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/83047138

http://stackoverflow.com/comment/84294430
has text: sorry to bother you again. When resampling to a given resolution and size and then back there are bound to be losses. With regular images I found these losses to be admissible but with labeled images I some time get losses of 20% of the segmented region (even when using nearest neighbour interpolation). Any suggestion on how to address this issue?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48065819

http://stackoverflow.com/comment/83150325
has text: you mean like this? from flask import app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' it says invalid syntax line 1
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48087659
type: AnswerComment

http://stackoverflow.com/q/48018162
has title: Unlock Computer Screen Using Python
has comment: http://stackoverflow.com/comment/83005421
upvote count: 1
has body: I had written some automation code for our site in which used sikuli for image automation. But sometimes I found that my computer screen locked in between, and that's why many of the test cases failed. So I want to write some python code to keep the screen unlocked. Here is the code patch which I wrote for locking the screen and now I am searching for how to unlock the screen: import os winpath = os.environ["windir"] os.system(winpath + r'\system32\rundll32 user32.dll, LockWorkStation') Note: I have already adjusted all the monitor settings which cause screen locking.
has comment: http://stackoverflow.com/comment/83006149
score: 1
has comment: http://stackoverflow.com/comment/83005399
has comment: http://stackoverflow.com/comment/83005799
type: Question
tagged with: robotframework
linked to: http://stackoverflow.com/q/26032706
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83006796
has comment: http://stackoverflow.com/comment/83005573
has comment: http://stackoverflow.com/comment/83160737
tagged with: sikuli
has comment: http://stackoverflow.com/comment/83005680
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83016869
has answer: http://stackoverflow.com/a/55742461
type: UnansweredQuestion

http://stackoverflow.com/comment/83137559
type: Comment
type: QuestionComment
has text: Running off Anaconda/python 3.6.3 with matplotlib 2.1.0
comment on: http://stackoverflow.com/q/48079364
score: 0

http://stackoverflow.com/q/48142357
answer count: 2
has comment: http://stackoverflow.com/comment/83298828
downvote count: 0
tagged with: laspy
favorite count: 0
has answer: http://stackoverflow.com/a/62428016
upvote count: 2
has comment: http://stackoverflow.com/comment/83273291
type: UnansweredQuestion
tagged with: python
score: 2
has title: TypeError: a bytes-like object is required, not 'str', laspy
has body: I am new to programming and wanted to convert Las file into grid file using laspy. It keeps giving error "TypeError: a bytes-like object is required, not 'str'". I know fmt gives a string, so I tried fmt = '%1.2f'.encode() to change in to binary, but got the same error. from laspy.file import File import numpy as np source = "/655-7878.las" target = "/lidar.asc" cell = 1.0 NODATA = 0 las = File(source, mode = "r") #xyz min and max min = las.header.min max = las.header.max #Get the x axis distance xdist = max[0] - min[0] #Get the y axis distance ydist = max[1] - min[1] #Number of columns for our grid cols = int((xdist)/cell) #Number of rows for our grid rows = int((ydist)/cell) cols += 1 rows += 1 #Track how many elevation #values we aggregate count = np.zeros((rows, cols)).astype(np.float32) #Aggregate elevation values zsum = np.zeros((rows, cols)).astype(np.float32) #Y resolution is negative ycell = -1 * cell #Project x,y values to grid projx =(las.x -min[0]) / cell projy = (las.y - min[1])/ ycell #Cas to integers and clip for use as index ix = projx.astype(np.int32) iy = projy.astype(np.int32) #Loop through x,y,z arrays, add to grid shape and aggregate values for averaging for x,y,z in np.nditer([ix, iy, las.z]): count[y, x] +=1 zsum[y, x]+=z # Change 0 values to 1 to avoid numpy warnings and NaN values in array nonzero = np.where(count&gt;0, count, 1) #Average our z values zavg = zsum/nonzero #Interpolate 0 values in array to avoid any holes in the grid mean = np.ones((rows, cols)) * np.mean(zavg) left = np.roll(zavg, -1,1) lavg = np.where(left&gt;0, left, mean) right = np.roll(zavg, 1, 1) ravg = np.where(right&gt;0, right, mean) interpolate = (lavg + ravg)/2 fill = np.where(zavg&gt;0, zavg, interpolate) #Create ASCII DEM header header = "ncols %s\n" % fill.shape[1] header += "nrows %s\n" % fill.shape[0] header += "xllcorner %s\n" % min[0] header += "yllcorner %s\n" % min[1] header += "cellsize %s\n" % cell header += "NODATA_value %s\n" % NODATA #Open the output …
has answer: http://stackoverflow.com/a/48165310
type: Question

http://stackoverflow.com/comment/83362068
type: Comment
comment on: http://stackoverflow.com/a/48141440
type: AnswerComment
has text: Right, but you might not have been aware of the python 3 port and thus your work might have gone to waste.
score: 0

http://stackoverflow.com/q/48171858
has comment: http://stackoverflow.com/comment/83340892
tagged with: python
type: AnsweredQuestion
score: 1
has body: How can I parse key-property definitions such as the following with pyparsing? some_key a b c d other_key /some/path /some/other/path.pl \ '$SOME_ENV_VAR$' \ '$OTHER_ENV_VAR$' Keys in this example are some_key and other_key. Values are the rests of the lines including [ \t] after whitespace that is following the key names, with an option for line continuation with \. I am relatively new to pyparsing and this exceeds my current capabilities.
upvote count: 1
type: Question
tagged with: pyparsing
has title: Parse key-value pairs with pyparsing where values may continue over multiple lines
has comment: http://stackoverflow.com/comment/83345821
accepted answer: http://stackoverflow.com/a/48183754
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48183754

http://stackoverflow.com/q/48142516
downvote count: 0
has answer: http://stackoverflow.com/a/48142551
has answer: http://stackoverflow.com/a/48142783
favorite count: 0
has answer: http://stackoverflow.com/a/48142564
linked to: http://stackoverflow.com/q/6130768
upvote count: 2
answer count: 5
has comment: http://stackoverflow.com/comment/83263168
possible better answer: http://stackoverflow.com/a/48142551
tagged with: python
tagged with: dictionary
duplicate of: http://stackoverflow.com/q/6130768
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48142650
has comment: http://stackoverflow.com/comment/83263323
duplicate of: http://stackoverflow.com/q/24814024
duplicate of: http://stackoverflow.com/q/42381821
type: Question
has title: Using a dict as a key when not all values exist
has body: I have a situation where some city names need to be renamed, so I am using a dict where the keys are the old city names and the values are the new ones. However, only some cities need to be renamed so not all possible cities are in the dict. The only way I know how to do it is to except a KeyError when the city doesn't need to be renamed, which works, but I'm not sure if this is bad practice, or if there are any downfalls to this. Is there something I am missing? # Set Venue venue_name = unidecode(cell[2].get_text()) try: # Correct venue names i.e. Cairns, QLD = Cairns venue_name = VENUE_NAMES_DICT[venue_name] except KeyError: pass
duplicate of: http://stackoverflow.com/q/42590901
has answer: http://stackoverflow.com/a/48142650
has answer: http://stackoverflow.com/a/48142544

http://stackoverflow.com/a/55910735
downvote count: 0
score: 18
type: Answer
accepted answer of: http://stackoverflow.com/q/48108582
answers question: http://stackoverflow.com/q/48108582
has body: I looked since hours for an answer to this question, and this can be found in the Scipy/Statsmodel code comments. In Scipy, comment at https://github.com/scipy/scipy/blob/abdab61d65dda1591f9d742230f0d1459fd7c0fa/scipy/stats/morestats.py#L523 says: probplot generates a probability plot, which should not be confused with a Q-Q or a P-P plot. Statsmodels has more extensive functionality of this type, see statsmodels.api.ProbPlot. So, now, let's look at Statsmodels, where comment at https://github.com/statsmodels/statsmodels/blob/66fc298c51dc323ce8ab8564b07b1b3797108dad/statsmodels/graphics/gofplots.py#L58 says: ppplot : Probability-Probability plot Compares the sample and theoretical probabilities (percentiles). qqplot : Quantile-Quantile plot Compares the sample and theoretical quantiles probplot : Probability plot Same as a Q-Q plot, however probabilities are shown in the scale of the theoretical distribution (x-axis) and the y-axis contains unscaled quantiles of the sample data. So, difference between QQ plot and Probability plot, in these modules, is related to the scales.
upvote count: 18
type: AcceptedAnswer

http://stackoverflow.com/a/48128849
type: Answer
has comment: http://stackoverflow.com/comment/83247443
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83236454
has comment: http://stackoverflow.com/comment/83234636
accepted answer of: http://stackoverflow.com/q/48128670
has body: You could use some trivial code such as: res = [] coords = [] xy = False with open('data.txt') as f: for line in f.readlines(): if 'layer' in line: arr = line.split() layer = int(arr[-1].strip()) elif 'xy' in line: arr = line.split() npoints = int(arr[1]) coords = arr[2:] xy = True elif 'endel' in line: res.append([layer, npoints, coords[0:npoints]]) xy = False coords = [] elif xy: coords.extend(line.split()) print(res) Then, you can convert the resulting list to numpy array, or whatever you like, but note that coords are still strings in the code above.
has comment: http://stackoverflow.com/comment/83234556
answers question: http://stackoverflow.com/q/48128670
has comment: http://stackoverflow.com/comment/83236104
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83234868
has comment: http://stackoverflow.com/comment/83234467

http://stackoverflow.com/q/48140693
has comment: http://stackoverflow.com/comment/83259305
has body: I am trying to retrieve the buy and sell values from the website: https://www.zebpay.com/#chart I tried the following code in python: import requests from bs4 import BeautifulSoup page = requests.get('https://www.zebpay.com/#chart') soup = BeautifulSoup(page.text, 'html.parser') for item in soup.find_all(id = 'topsell'): print(item) But I get only this result: Whereas I can clearly see the values when I do inspect elements: How can I solve this?
tagged with: beautifulsoup
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83259223
answer count: 0
type: UnansweredQuestion
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83259200
score: 0
has title: How to retrieve live values from a website?
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/83267381

http://stackoverflow.com/comment/83207946
comment on: http://stackoverflow.com/a/48104730
score: 0
type: AnswerComment
has text: solved it, i still had the `uper().__init__(parent)` in it. Now it works, thanks a ton!
type: Comment

http://stackoverflow.com/a/48086088
has body: You did not connect the nodes at all. See the code below. When a node is created, it is not connected to any other nodes. def insertbst(root, val): if root == None: root = Node(val) return You can connect two node by node_A.left = node_B # generates node_A / node_B node_A.right = node_B # generates node_A \ node_B
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48084192

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/48079105

http://stackoverflow.com/comment/83059932
type: Comment
has text: Please post a minimal example of an input (`a_list`) that should *evaluate* to `True` and one that *evaluates* to `False`. ... [mcve]
comment on: http://stackoverflow.com/q/48040762
score: 0
type: QuestionComment

http://stackoverflow.com/q/48114599
has title: What is the use of ,0 in this function
accepted answer: http://stackoverflow.com/a/48115210
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83205300
score: -3
has comment: http://stackoverflow.com/comment/83205403
has body: stock = {'football': 4, 'boardgame': 10, 'leggos': 100, 'doll': 5} def fillable(stock, merch, n): return stock.get(merch, 0) &gt;= n print(fillable(stock, 'leggos', 10)) The result in codewars: Traceback: in in fillable TypeError: unorderable types: NoneType() >= int()
tagged with: python
possible better answer: http://stackoverflow.com/a/48114769
has answer: http://stackoverflow.com/a/48115210
type: AnsweredQuestion
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/2068349
has answer: http://stackoverflow.com/a/48114769
has comment: http://stackoverflow.com/comment/83205072
downvote count: 4
upvote count: 1
has comment: http://stackoverflow.com/comment/83205297
has comment: http://stackoverflow.com/comment/83205025

http://stackoverflow.com/q/48107144
tagged with: python
has answer: http://stackoverflow.com/a/71954971
favorite count: 0
accepted answer: http://stackoverflow.com/a/48107183
has title: Combine pop() and setdefault() in python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48107183
score: 1
possible better answer: http://stackoverflow.com/a/71954971
type: Question
answer count: 2
upvote count: 1
has body: I'm trying to build a method where if an item is not in a dictionary then it uses the last member of a list and updates the dictionary accordingly. Sort of like a combination of the pop and setdefault method. What I tried was the following: dict1 = {1:2,3:4,5:6} b = 7 c = [8,9,10] e = dict1.setdefault(b, {}).update(pop(c)) So I would like the output to be where {7:10} gets updated to dict1, that is to say, if b is not in the keys of dict1 then the code updates dict1 with an item using b and the last item of c.

http://stackoverflow.com/comment/83079625
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162303/discussion-between-yohannes-libanos-and-shalakhin).
comment on: http://stackoverflow.com/a/48053312
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/55425435
has body: You might have used your Python file name as pickle.py. Python interpreter is confused and looking for dump function in you file pickle.py instead of the package you have imported. Change the name of your file to something else, it will work.
answers question: http://stackoverflow.com/q/48087036
score: 5
upvote count: 5
downvote count: 0
type: Answer

http://stackoverflow.com/q/48107313
has answer: http://stackoverflow.com/a/48107410
answer count: 3
downvote count: 3
has comment: http://stackoverflow.com/comment/83190418
tagged with: python
favorite count: 0
has title: Beginner: Index Error - What's wrong with this code?
has comment: http://stackoverflow.com/comment/83190450
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83190390
type: Question
tagged with: index-error
has answer: http://stackoverflow.com/a/48107476
has body: As mentioned, I am a beginner and am trying to do short exercises. Unfortunately my online tutor is not able to or unwilling to help me with this (keeps suggesting other ways of doing it). My task is to check if the first word for the line is 'From ' in which case I need to print the next word (the email address). For example the file has series of lines like the following From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Return-Path: &lt;postmaster@collab.sakaiproject.org&gt; Received: from murder (mail.umich.edu [141.211.14.90]) by frankenstein.mail.umich.edu (Cyrus v2.3.8) with LMTPA; From louis@media.berkeley.edu Fri Jan 4 18:10:48 2008 Return-Path: &lt;postmaster@collab.sakaiproject.org&gt; Received: from murder (mail.umich.edu [141.211.14.97]) The code should result with the following output: stephen.marquard@uct.ac.za louis@media.berkeley.edu I have written the following code to do this: fname = "mbox-short.txt" f = open(fname,'r') lines = f.readlines() i = 0 count = len(lines) while i &lt; count : test = lines[i].split() if test[0] == "From " : print(test[1]) i += 1 I keep getting the following error: Traceback (most recent call last): File "C:\Users\38775\Desktop\py4e\Project 2\email.py", line 10, in &lt;module&gt; if test[0] == "From " : IndexError: list index out of range I just want to understand why this is happening, and how I can correct this. Request you not to take time to share alternatives. Thanks
upvote count: 1
has comment: http://stackoverflow.com/comment/83190224
score: -2
has comment: http://stackoverflow.com/comment/83190466
has answer: http://stackoverflow.com/a/48110360

glyph
type: Tag
tag name: glyph
tags question: http://stackoverflow.com/q/48058402

http://stackoverflow.com/comment/83145427
has text: Hey kazemakase. Thank you very much for reading my post. I have added more info. I have put the code in a function put im not sure if its correct.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48077286
score: 0

http://stackoverflow.com/a/67139316
has comment: http://stackoverflow.com/comment/124984801
has comment: http://stackoverflow.com/comment/124979342
type: Answer
downvote count: 0
score: 3
has body: The accepted answer doesn't explain how to set the line-color, line-style and some more. So this is what I found and hope it will be useful to some else. You will need a working python-tk and install pygame and matplotlib with pip. The following code was tested with python3, pygame 2.0.1 and matplotlib 3.3.4 on a Ubuntu 18.04. Some links on how to customize the code: Cycler explained Linestyle explained Customizing with stylesheet and rcParams import matplotlib import matplotlib.pyplot as plt import matplotlib.backends.backend_agg as agg import pygame from pygame.locals import * import pylab matplotlib.use("Agg") plt.rcParams.update({ "lines.marker": "o", # available ('o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd', 'P', 'X') "lines.linewidth": "1.8", "axes.prop_cycle": plt.cycler('color', ['white']), # line color "text.color": "white", # no text in this example "axes.facecolor": "black", # background of the figure "axes.edgecolor": "lightgray", "axes.labelcolor": "white", # no labels in this example "axes.grid": "True", "grid.linestyle": "--", # {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} "xtick.color": "white", "ytick.color": "white", "grid.color": "lightgray", "figure.facecolor": "black", # color surrounding the plot "figure.edgecolor": "black", }) fig = pylab.figure(figsize=[4, 2], # Inches dpi=100) # 100 dots per inch, so the resulting buffer is 400x200 pixels fig.patch.set_alpha(0.1) # make the surrounding of the plot 90% transparent to show what it does ax = fig.gca() ax.plot([1, 2, 4]) canvas = agg.FigureCanvasAgg(fig) canvas.draw() renderer = canvas.get_renderer() raw_data = renderer.buffer_rgba() pygame.init() window = pygame.display.set_mode((600, 210), DOUBLEBUF) screen = pygame.display.get_surface() size = canvas.get_width_height() surf = pygame.image.frombuffer (raw_data, size, "RGBA") bg_color = (255, 0, 0) # fill red as background color screen.fill(bg_color) screen.blit(surf, (100, 5)) # x, y position on screen pygame.displa…
has comment: http://stackoverflow.com/comment/124483566
upvote count: 3
answers question: http://stackoverflow.com/q/48093361

http://stackoverflow.com/a/48092456
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48092411
score: 0
has comment: http://stackoverflow.com/comment/83163556
type: Answer
has body: You can use apply with list comprehension: df = pd.DataFrame({'member_info.vocabulary':[[], [{'post_iD':'3913', 'word':'Twisters'}, {'post_iD':'3911', 'word':'articulate'}]]}) df['words'] = df['member_info.vocabulary'].apply(lambda x: [y.get('word') for y in x]) print (df) member_info.vocabulary words 0 [] [] 1 [{'post_iD': '3913', 'word': 'Twisters'}, {'po... [Twisters, articulate] And if get one element lists only add str[0] for select first value of lists: df = pd.DataFrame({'member_info.vocabulary':[[], [{'post_iD':'3913', 'word':'Twisters'}]]}) df['words'] = df['member_info.vocabulary'].apply(lambda x: [y.get('word') for y in x]).str[0] print (df) member_info.vocabulary words 0 [] NaN 1 [{'post_iD': '3913', 'word': 'Twisters'}] Twisters
accepted answer of: http://stackoverflow.com/q/48092411

http://stackoverflow.com/q/48054636
downvote count: 4
has comment: http://stackoverflow.com/comment/83081763
linked to: http://stackoverflow.com/q/22937618
has comment: http://stackoverflow.com/comment/83081665
has answer: http://stackoverflow.com/a/48054693
accepted answer: http://stackoverflow.com/a/48054693
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83081644
has body: &gt;&gt;&gt; sentence = "Thomas Jefferson began building Monticello at the age of 26." &gt;&gt;&gt; tokens1 = re.split(r"([-\s.,;!?])+", sentence) &gt;&gt;&gt; tokens2 = re.split(r"[-\s.,;!?]+", sentence) &gt;&gt;&gt; tokens1 = ['Thomas', ' ', 'Jefferson', ' ', 'began', ' ', 'building', ' ', 'Monticello', ' ', 'at', ' ', 'the', ' ', 'age', ' ', 'of', ' ', '26', '.', ''] &gt;&gt;&gt; tokens2 = ['Thomas', 'Jefferson', 'began', 'building', 'Monticello', 'at', 'the', 'age', 'of', '26', ''] Can you explain the purpose of ( and )?
score: -1
type: Question
has comment: http://stackoverflow.com/comment/83081671
answer count: 2
has comment: http://stackoverflow.com/comment/83081819
has comment: http://stackoverflow.com/comment/83081720
has title: What's the difference between([])+ and []+?
possible better answer: http://stackoverflow.com/a/48054646
has comment: http://stackoverflow.com/comment/83081687
favorite count: 0
has comment: http://stackoverflow.com/comment/83081643
has answer: http://stackoverflow.com/a/48054646
upvote count: 3
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83081762

http://stackoverflow.com/q/48088128
has comment: http://stackoverflow.com/comment/83153845
tagged with: pandas
has answer: http://stackoverflow.com/a/48103837
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83152393
has comment: http://stackoverflow.com/comment/83152168
has title: Matplotlib bar chart show x-ticks only at non-zero bars
possible better answer: http://stackoverflow.com/a/48103837
upvote count: 2
has comment: http://stackoverflow.com/comment/83173261
tagged with: plot
type: Question
tagged with: matplotlib
tagged with: figure
answer count: 2
has answer: http://stackoverflow.com/a/48096601
has body: I have to make a (stacked) bar plot that has ~3000 positions on the x axis. However, many of these positions do not contain bars but are still labeled on the x-axis, making reading the plot difficult. Is there any way to only show x-ticks for existing (stacked) bars? The spaces between the bars based on the x-tick values are necessary. How would one tackle this in matplotlib? Is there a more fitting plot than a stacked bar chart? I'm constructing the plots from a pandas cross-table (pd.crosstab()). link to image of plot: https://i.sstatic.net/qk99z.png as an example of what my dataframe would look like (thanks gepcel): import pandas as pd import numpy as np N = 3200 df = pd.DataFrame(np.random.randint(1, 5, size=(N, 3))) df.loc[np.random.choice(df.index, size=3190, replace=False), :] = 0 df_select = df[df.sum(axis=1)&gt;0]
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48096601

http://stackoverflow.com/comment/83049058
score: 1
has text: You found some code on the internet and you don't know how it works? Did you spend any time reading through the Matplotlib docs? Have you ruled out any parts of the code? What do you suspect is the problem and what did you do to validate that?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48039312

http://stackoverflow.com/comment/83221961
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48122046
type: QuestionComment
has text: What? Your objective is to convert the month to a number, but your code with the `apply` does the opposite?

http://stackoverflow.com/q/48040529
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/83052921
favorite count: 0
has body: I have a Time Series Data-set that looks like the following: Dates Power 09-11-12 23:40 123 09-11-12 23:40 0 09-11-12 23:40 0 09-11-12 23:40 0 09-11-12 23:40 0 09-11-12 23:40 123 09-11-12 23:40 123 09-11-12 23:40 122 09-11-12 23:40 122 09-11-12 23:41 122 09-11-12 23:41 0 09-11-12 23:41 0 09-11-12 23:41 161 09-11-12 23:41 123 09-11-12 23:41 124 09-11-12 23:41 123 09-11-12 23:41 123 09-11-12 23:41 123 09-11-12 23:41 123 In the above data-set power consumed by an appliance in 6th sec of every minute is given.I want to convert the data-set to 1 hour time series with Power Unit=KW/h i.e. I want to convert it to power consumed in an hour without summing every 6th sec power consumption. I tired to sum them after multiplying 6th sec power consumption with 2.77778e-7 but I get the feeling i am doing it wrong. Is it the right way to do it? If not What is the right Way? I used the following code for summing them up. data = pd.read_csv( r'E:\ukdale\house_1\channel_6.dat', delimiter=' ', header=None, names=['Date', 'Power'], dtype={'Date': np.int64, 'Power': np.float64}, index_col='Date' ) data.index = pd.to_datetime((data.index.values), unit='s') ts = pd.Series(data=data['Power']) ts.multiply(0.000000277778) ts1=ts.resample('h').sum() ts1.dropna(inplace=True) My results: Dates Power(KW/h) 09-11-12 22:00 310 09-11-12 23:00 64948 10-11-12 0:00 279706 10-11-12 1:00 386517 10-11-12 2:00 0 10-11-12 3:00 125 10-11-12 4:00 0 10-11-12 5:00 0 10-11-12 6:00 0 10-11-12 7:00 0 10-11-12 8:00 95 10-11-12 9:00 582 10-11-12 10:00 594 10-11-12 11:00 585
type: UnansweredQuestion
has title: How to Convert 6s Power Consumption Time Series Data To 1 Hour Data?
tagged with: python
answer count: 0
downvote count: 0
score: 1
tagged with: energy
type: Question
tagged with: time-series
has comment: http://stackoverflow.com/comment/83057848

http://stackoverflow.com/a/48080210
type: Answer
answers question: http://stackoverflow.com/q/48077878
score: 0
has body: Using your sample data and if you only want the first supplier_code, then below will suffice. &gt;&gt;&gt; print(df.groupby('item_code').agg({'dollar_amount':sum, 'supplier_code': lambda curr: curr.iloc[0]}).sort_values('dollar_amount', ascending=False).reset_index()) item_code dollar_amount supplier_code 0 Item1 1802.25 Sup1 1 Item2 1400.00 Sup1 2 Item3 360.00 Sup2 reset_index() is optional. I just used it to return a DataFrame. But if you need to get the top supplier_code per item_code then I think you need to do a dual group_by. &gt;&gt;&gt; print(df.groupby(['item_code', 'supplier_code']).sum().sort_values('dollar_amount', ascending=False).reset_index().groupby('item_code').agg({'dollar_amount':sum, 'supplier_code': lambda curr: curr.iloc[0]}).reset_index()) item_code dollar_amount supplier_code 0 Item1 1802.25 Sup1 1 Item2 1400.00 Sup1 2 Item3 360.00 Sup2

http://stackoverflow.com/a/48107426
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48107325
has comment: http://stackoverflow.com/comment/83190472
has body: There is a thread-safe counter inside Lock instance, and lock.acquire means if counter bigger than 0, then pass, else block. lock.release means counter = counter + 1. So to sync two threads, you need to use lock inside both threads. If job1 doesn't lock.release, counter is 0 and the lock.acquire inside job2 will block until job1 call lock.release. That is how lock works basically. Update There isn't any lock inside job2 unless you do use a lock inside it. I know what you want, you want to block job2 until job1 call lock.release. But you need to explicitly tell job2 to block by calling lock.acquire. Or how could job2 know itself should be blocked? Going further, suppose you have two different lock instances a, b and two pairs of threads jobA1, jobA2, jobB1, jobB2. You can use a to synchronize jobA1 and jobA2 and use b to synchronize jobB1 and jobB2. But you need explicitly tell every thread which lock they should use.
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48107325
type: Answer

http://stackoverflow.com/a/48155874
upvote count: 4
answers question: http://stackoverflow.com/q/48155787
downvote count: 0
score: 4
has body: To fix your code df['Date']=pd.to_datetime(df.year*10000+df.month*100+df.day,format='%Y%m%d') df Out[57]: id lat lon year month day Date 0 381 53.3066 -0.54649 2004 1 2 2004-01-02 1 381 53.3066 -0.54649 2004 1 3 2004-01-03 2 381 53.3066 -0.54649 2004 1 4 2004-01-04
type: Answer

http://stackoverflow.com/q/48118345
has answer: http://stackoverflow.com/a/48121054
tagged with: python
has comment: http://stackoverflow.com/comment/83213123
has comment: http://stackoverflow.com/comment/83214511
downvote count: 2
has comment: http://stackoverflow.com/comment/83214985
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83214813
accepted answer: http://stackoverflow.com/a/48121054
has comment: http://stackoverflow.com/comment/83218384
score: -2
has body: I'm looking to model discrete growth rates for a biology application. I know the starting growth rate per hr (200%) and the ending growth rate per hr (2%). The growth rate should decrease linearly every hour. I also know that the total growth should be 200x. I'm trying to calculate the number of hours required and generate a vector array, sized to the number of hours, containing the growth rates (one value per hr)... something like [200%, 180%, 160% ... 4%, 2%]. But I need the total compounded growth to equal 200x. I've played with np.linspace and np.geomspace, but I'm not smart enough to know how to get the compounded growth to match in this case.
tagged with: math
has comment: http://stackoverflow.com/comment/83217270
has comment: http://stackoverflow.com/comment/83216968
tagged with: numpy
tagged with: vector
upvote count: 0
answer count: 1
tagged with: arrays
favorite count: 0
has title: Generate vector of linearly spaced growth rates, knowing beginning, end, and total compounded growth, with numpy or similar

http://stackoverflow.com/comment/83304976
type: QuestionComment
comment on: http://stackoverflow.com/q/48162795
score: 0
has text: Try doing `find_element` *then* `find_elements`. (note plural) There's one results list and multiple names. Also double check your xpath.
type: Comment

http://stackoverflow.com/a/48042053
has comment: http://stackoverflow.com/comment/83065883
has body: You will need to install the required packages. You should be able to do this with pip. Try the following command on the server: pip install --user tensorflow You can install pip using get-pip.py as described here: https://pip.pypa.io/en/stable/installing/ Quick recipe: #Gettin get-pip wget -P ~/.local/lib https://bootstrap.pypa.io/get-pip.py python ~/.local/lib/get-pip.py --user #Adds /.local/bin to the global path variable and adds it to bashrc file printf "\nPATH=~/.local/bin/:\$PATH" &gt;&gt; ~/.bashrc #run bashrc, almost same effect as restarting terminal source ~/.bashrc
type: Answer
has comment: http://stackoverflow.com/comment/83069381
score: 0
answers question: http://stackoverflow.com/q/48040808

http://stackoverflow.com/q/48038422
score: 2
has comment: http://stackoverflow.com/comment/83053410
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83054544
type: Question
has comment: http://stackoverflow.com/comment/83053519
has title: 3d plot of list of (hist, bin_edges) where histogram bar chart or lines are in the z-y plane
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48042170
accepted answer: http://stackoverflow.com/a/48042170
has comment: http://stackoverflow.com/comment/83050916
has comment: http://stackoverflow.com/comment/83054204
has comment: http://stackoverflow.com/comment/83054689
has body: EDIT - reworked question I need to print a 3D histogram of fitness data for 50 generations of computer programmes. This data is in calculated and stored in a logbook using the DEAP framework. The form of the plot needs to be with the fitness frequency on the z axis, generation on the x axis and bin_edges on the y axis. So the lines for the histogram are in the z-y plane, for each generation on the x-axis. The frequency data for each generation is contained in a numpy array of shape (#generations, #bin_edges), gained by running np.histogram() on each generation. histograms = [el[0] for el in logbook.chapters["fitness"].select("hist")] histograms.shape (51, 10) # (num gen, num bins) print (histograms) # excerpt only [[ 826. 145. 26. 2. 1. 0. 0. 0. 0. 0.] [ 389. 446. 145. 16. 4. 0. 0. 0. 0. 0.] [ 227. 320. 368. 73. 12. 0. 0. 0. 0. 0.] [ 199. 128. 369. 261. 43. 0. 0. 0. 0. 0.] [ 219. 92. 158. 393. 137. 1. 0. 0. 0. 0.] [ 252. 90. 91. 237. 323. 6. 1. 0. 0. 0.] [ 235. 89. 69. 96. 470. 36. 5. 0. 0. 0.] [ 242. 78. 61. 51. 438. 114. 16. 0. 0. 0.] [ 235. 82. 52. 52. 243. 279. 57. 0. 0. 0.]] bin_edges array([ 0., 9., 18., 27., 36., 45., 54., 63., 72., 81., 90.]) gen [0, 1, 2, 3, 4, 5, 6, 7, 8, ...] I've made several attempts, but can't seem to get the histogram data into the right format, or possibly shape for matplotlib axes.bar. ATTEMPT 2: busy reworking import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np xedges = list(gen) yedges = list(bin_edges) H = histograms.T fig=plt.figure() # error on this line: TypeError: list indices must be integers or slices, not list ax = fig.add_subplot(133, title='NonUniformImage: interpolated', aspect='equal', \ xlim=xedges[[0, -1]], ylim=yedges[[0, -1]]) im = mpl.image.NonUniformImage(ax, interpolation='bilinear') xcenters = (xedges[:-1] + xedges[1:]) / 2 ycenters = (yedges[:-1] + yedges[1:]) / 2 im.set_data(xcenters, ycenters, H) ax.images.append(im) plt.show() ATTEMPT 1: fig = plt.figure() ax = fig.add_subplot(111, p…
upvote count: 2
tagged with: numpy
linked to: http://stackoverflow.com/q/47899253
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83054901
has comment: http://stackoverflow.com/comment/83053298
has comment: http://stackoverflow.com/comment/83047195
tagged with: python
has comment: http://stackoverflow.com/comment/83053532
has comment: http://stackoverflow.com/comment/83047373

http://stackoverflow.com/comment/83057971
has text: Thanks that worked partially, the labels are flipped vertically. But I still don't have them in decreasing order since it is a count plot. It is counting how many times a particular word is appearing and finally plotting the results.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48043463

http://stackoverflow.com/a/48166669
score: 3
has comment: http://stackoverflow.com/comment/83313045
has comment: http://stackoverflow.com/comment/83312433
accepted answer of: http://stackoverflow.com/q/48166581
upvote count: 3
answers question: http://stackoverflow.com/q/48166581
has comment: http://stackoverflow.com/comment/83313358
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83313199
has comment: http://stackoverflow.com/comment/83313441
has comment: http://stackoverflow.com/comment/83312559
type: Answer
downvote count: 0
has body: If 'columns' are in index. In [217]: df.loc[(df.index.get_level_values('Site In') == 'Mid') | (df.index.get_level_values('Site Out') == 'Mid')] Out[217]: v Site In Site Out Transmission Commodity Mid North hvac Elec 1 South hvac Elec 1 North Mid hvac Elec 1 South Mid hvac Elec 1 If it's a flat dataframe, use In [168]: df.loc[(df['Site In'] == 'Mid') | (df['Site Out'] == 'Mid')] Out[168]: Site In Site Out Transmission Commodity 0 Mid North hvac Elec 1 Mid South hvac Elec 2 North Mid hvac Elec 4 South Mid hvac Elec Or In [169]: df.loc[df['Site In'].eq('Mid') | df['Site Out'].eq('Mid')] Out[169]: Site In Site Out Transmission Commodity 0 Mid North hvac Elec 1 Mid South hvac Elec 2 North Mid hvac Elec 4 South Mid hvac Elec
has comment: http://stackoverflow.com/comment/83312676

http://stackoverflow.com/a/48061272
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48061146
has body: Depending on what you're trying to do, your problem is probably that you are not specifying the type of your credentials. Try doing : import json import requests response = requests.get('https://api.samanage.com/incidents.json', headers={'X-Samanage-Authorization': 'Bearer ' + API_TOKEN}) print(response.status_code) Another case, your API_TOKEN is not the actual token if you have not made a mistake while typing your code back. You have a STRING API_TOKEN, but not the actual token.
accepted answer of: http://stackoverflow.com/q/48061146
has comment: http://stackoverflow.com/comment/83095103
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/83237522
has text: https://www.youtube.com/watch
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48015149

http://stackoverflow.com/comment/83276895
comment on: http://stackoverflow.com/q/48149135
score: 0
type: Comment
has text: You just need to read specific values from file and assign them to variables. Then you use those variables where you need to reference those values.
type: QuestionComment

http://stackoverflow.com/comment/83308672
score: 4
has text: Could you perhaps show a smaller example of what your trying to do? It's difficult for us to scan through all that code to see whats wrong.
type: QuestionComment
comment on: http://stackoverflow.com/q/48164698
type: Comment

http://stackoverflow.com/comment/83146125
has text: the error you get??
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48085578
type: Comment

http://stackoverflow.com/q/48043848
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83059697
favorite count: 0
has title: UnicodeDecodeError from python 2 to 3 with .decode() and sockets
has body: Hello i have been working on a Python code which will flash my Arduino over WiFi and i almost have it working im so close. The issue is it was created for Python 2 and i want it to run on the latest python 3. I added .encode and decode to places where socket sends or receives a string. and that works great up till the point where it stops reading strings and want to read a HEX string. I get this error Traceback (most recent call last): File "C:\Users\edwin\Desktop\FlashTesting\pythonFlash.py", line 258, in main() File "C:\Users\edwin\Desktop\FlashTesting\pythonFlash.py", line 250, in main if wait_for (cli, "\x00", MAX_TIMEOUT) [0]: File "C:\Users\edwin\Desktop\FlashTesting\pythonFlash.py", line 123, in wait_for received += cli.recv(1).decode() # .decode() is new TypeError: Can't convert 'bytes' object to str implicitly UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 0: unexpected end of data. Normally i would reduce all the code down to the parts required but seeing as the wait_for is used throughout the code i shall paste the entire code, functions are separated by a comment line to make it easy to read. Please any help is appreciated i have been working on this since xmas eve no stop. The error starts in the main function at the bottom of the code when it calls wait_for and wants to read "\x00" and then it will finally call the program_process function which i think will get the same error, as you can see i added .encode() to the HEX strings there, so can you also help with with one of those so i know how to resolve that when it happens. Thank you in advanced and have a nice new year :) main code that i am converting, note his indentation is shocking import sys import binascii import struct import select import socket import errno MAX_TIMEOUT = 500 SUCCESS = "success" FAILED = "failed" PORT = 50000 #------------------------------------------------------------------------------------------------- ''' Class containing the data from non-contiguou…
tagged with: python
has answer: http://stackoverflow.com/a/58914483
type: UnansweredQuestion
tagged with: sockets
upvote count: 1
has comment: http://stackoverflow.com/comment/83059583
score: 1
type: Question

http://stackoverflow.com/comment/83064781
has text: So, you want to turn a number into a date. But what is the number? Is it seconds?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48046647

http://stackoverflow.com/q/48072056
type: Question
tagged with: powershell
tagged with: azure-automation
has answer: http://stackoverflow.com/a/48348300
score: 0
answer count: 1
tagged with: azure
has comment: http://stackoverflow.com/comment/83145567
tagged with: python
has body: How can we pass parameters to child runbook written in python using Start-AzureRmAutomationRunbook. Start-AzureRmAutomationRunbook accepts -Parameter option for named parameters (works great with child runbooks written in PowerShell). But since python supports positional parameters (args), I am not able to use -Parameter option. By the way, my python runbook runs on a hybrid worker, so, I am not sure how can we use inline execution, because I need to pass RunOn option (Hybrid Runbook Worker Group).
has title: Azure automation : Pass parameters to child runbook in python
has comment: http://stackoverflow.com/comment/83375641
type: UnansweredQuestion

http://stackoverflow.com/q/48173147
type: Question
has title: Cannot insert NULL into column 'Type'
has comment: http://stackoverflow.com/comment/83326817
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83327020
tagged with: sql
tagged with: python
accepted answer: http://stackoverflow.com/a/48173645
upvote count: 1
tagged with: pyodbc
has answer: http://stackoverflow.com/a/48173645
has body: I'm attempting to add a row with two pieces of information to the Notes table. I'm executing the following INSERT statement with python. cursor.execute("insert into Notes(Notes, NumericKey) values (?, ?)",Tracking, OrderNumber) The error I'm getting it Traceback (most recent call last): File "&lt;interactive input&gt;", line 1, in &lt;module&gt; IntegrityError: ('23000', "[23000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot insert the value NULL into column 'Type', table 'beltoutlet.dbo.Notes'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [01000] [Microsoft][SQL Server Native Client 11.0][SQL Server]The statement has been terminated. (3621)") I'm seeing a lot of people with similar issues but all the attempted solutions haven't helped. I'm at my wits end since for Tracking and OrderNumber both have real values and I dont have a column "Type". Any assistance would be greatly appreciated.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83326729
score: 1
has comment: http://stackoverflow.com/comment/83325930
has comment: http://stackoverflow.com/comment/83325994

http://stackoverflow.com/a/62632480
has body: I resolved this problem by creating a new venv for my project and switch to it. Then, when I activate the venv and "pip list" into it, I list only venv packages. I think this problem happens when you rename project folder or venv folder or move those files maybe to reorganise your project structure.
upvote count: 6
answers question: http://stackoverflow.com/q/48159303
downvote count: 1
score: 5
type: Answer

http://stackoverflow.com/comment/83352388
has text: I have found a similar issue here: [BitBucket Issue #849](https://bitbucket.org/openpyxl/openpyxl/issues/849/849-type-error-when-loading-excel-with) but I don't know how to implement the sollution...
type: QuestionComment
comment on: http://stackoverflow.com/q/48168390
score: 0
type: Comment

http://stackoverflow.com/a/77952865
score: 5
has body: Obtain environment information using PyTorch via Terminal command python -m torch.utils.collect_env And if you can have True value for "Is CUDA available" in comand result like below, then your PyTorch is using GPU. Is CUDA available: True
downvote count: 0
answers question: http://stackoverflow.com/q/48152674
has comment: http://stackoverflow.com/comment/138218511
type: Answer
upvote count: 5

http://stackoverflow.com/a/48168779
has comment: http://stackoverflow.com/comment/83330443
score: 14
answers question: http://stackoverflow.com/q/48167835
downvote count: 0
type: Answer
has body: There are a few things wrong with your code. First, using the column in quotes in converters={'6': means that the conversion function will never be applied. Use column number without quotes: converters={6: convertDate}, Another problem is that you need to convert from string to integer, otherwise your datetime conversion will not work: convertDate = lambda x: datetime.datetime.utcfromtimestamp(int(x)) Finally, the datatype of your time field has to be numpy.datatype64 (and specify in micro seconds because that is what utcfromtimestamp returns). The proper way to assign the datatypes in your np.genfromtxt call is the following: data = np.genfromtxt('wx-log2.txt', delimiter=';', converters={6: convertDate}, usecols=(1,2,3,5,6), dtype=[('temp', 'f'), ('humidity', 'f'), ('press', 'f'), ('slp', 'f'), ('time', 'datetime64[us]')]) With the following above, you should how have the time in a format that plt.plot_date can understand. For the date format, you can have something similar to what you are trying to achieve by setting the minor tick mark labels to be HH:MM and the major to be day of year, but I don't know a way to have in addition unlabelled tick marks every 30 min. Here is a simple example that has a proper time array and plots in a similar format to what you want. For simplicity, only writing tick marks every 4 hours, but you can change it. import numpy as np import matplotlib.dates as dates import matplotlib.pyplot as plt fig, ax = plt.subplots() idx = pd.date_range('2018-01-07', '2018-01-09', freq='10min') # generate a time range series with 10 min intervals idx = np.arange('2018-01-07T00', '2018-01-09T02', 10, dtype='datetime64[m]') # some random data y = np.sin(np.arange(idx.shape[0]) / 0.01) ax.plot_date(idx, y, '-') ax.xaxis.set_minor_locator(dates.HourLocator(interval=4)) # every 4 hours ax.xaxis.set_minor_formatter(dates.DateFormatter('%H:%M')) # hours and minutes ax.xaxis.set_major_locator(dates.DayLocator(interval=1)) # every day ax.xaxis.set_major_form…
upvote count: 14

http://stackoverflow.com/a/48019678
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48019561
answers question: http://stackoverflow.com/q/48019561
has comment: http://stackoverflow.com/comment/83018105
type: Answer
has body: import pandas as pd dataframename['date'] = pd.to_datetime(dataframename['columnname'], unit='ms') See pandas.to_datetime docs for more examples
downvote count: 0
score: 1

http://stackoverflow.com/comment/83036904
comment on: http://stackoverflow.com/q/48033318
has text: @JonClements Thanks for the input what i am looking for is the indices of the original array elements before taking mod that have the same value after performing mod operation.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83284484
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48152139
type: Comment
has text: Updated for python2.7

http://stackoverflow.com/a/48077011
type: Answer
has body: You can convert string to datetime - using exact indexing: print (df.locpd.to_datetime("2015-10-01 02:00:00")) values 2015-10-01 02:00:00 2 Or convert Series to DataFrame and transpose: print (df.loc["2015-10-01 02:00:00"].to_frame().T) values 2015-10-01 02:00:00 2
upvote count: 1
answers question: http://stackoverflow.com/q/48076276
score: 1
downvote count: 0

geotagging
tag name: geotagging
tags question: http://stackoverflow.com/q/48019313
type: Tag

encoding
tags question: http://stackoverflow.com/q/48114158
tags question: http://stackoverflow.com/q/48116760
tags question: http://stackoverflow.com/q/48067514
tags question: http://stackoverflow.com/q/48068829
tags question: http://stackoverflow.com/q/48087091
tags question: http://stackoverflow.com/q/48105735
type: Tag
tags question: http://stackoverflow.com/q/48085319
tag name: encoding
tags question: http://stackoverflow.com/q/48056684
tags question: http://stackoverflow.com/q/48024964
tags question: http://stackoverflow.com/q/48096935
tags question: http://stackoverflow.com/q/48019249
tags question: http://stackoverflow.com/q/48151017

http://stackoverflow.com/comment/83268221
comment on: http://stackoverflow.com/a/48132854
type: Comment
type: AnswerComment
score: 0
has text: It will only work in console sessions. You have to put it in explicitly at the top of a saved program. Otherwise the program would fail when run outside of PyCharm.

http://stackoverflow.com/comment/83199380
has text: How would people modify your server's scripts? If your server allows unauthorized access to change code, you have a bigger problem than just this.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48111721

http://stackoverflow.com/comment/129274687
has text: In the django framework there is a way to pass multiple variables in Jinja2 but the syntax looks different. I'm not sure if I can help as things may be different in Webapp2.
comment on: http://stackoverflow.com/q/48015492
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83055984
type: Comment
has text: it works for me, with the csv sample you provided, maybe the real file is different?
type: AnswerComment
comment on: http://stackoverflow.com/a/48042585
score: 0

http://stackoverflow.com/a/48086397
has comment: http://stackoverflow.com/comment/83228060
has comment: http://stackoverflow.com/comment/83219195
answers question: http://stackoverflow.com/q/48086236
has comment: http://stackoverflow.com/comment/83224090
has comment: http://stackoverflow.com/comment/83188752
has comment: http://stackoverflow.com/comment/83187250
has body: See the execute function description in the sqlite documentation. Statement variables should be in a second argument to execute(...), a tuple containing all the parameters. Replace the %s in the statement string with ? as per the documentation specifications, for sanity. You need code like this: def Submit(): conn = sqlite3.connect('SSRB.db') conn.execute(''' INSERT INTO ssrb (date, time_in, time_out, company, plate, province, driver, pass1, pass2, pass3, deliver, contact, entry_by, pi_yes, pi_no, pi_violations, pi_done_by, vi_yes, vi_no, vi_violations, vi_done_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', (Date, TimeIn, TimeOut, Company, Plate, Province, Driver, Pass1, Pass2, Pass3, Delivery, Contact, EntryBy, PIYES, PINO, PIFound, PIDoneBy, VIYES, VINO, VIFound, VIDoneBy)) connect.commit() connect.close() Addendum 1: Variables in the parameters tuple should be primitives (integers, floats etc).
score: 0
has comment: http://stackoverflow.com/comment/83149140
type: Answer

http://stackoverflow.com/q/48065117
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/63120034
tagged with: simpleitk
tagged with: image-processing
type: Question
accepted answer: http://stackoverflow.com/a/48065819
answer count: 2
score: 5
upvote count: 5
downvote count: 0
tagged with: image
has body: I have a set o 3D volumes that I am reading with SimpleITK import SimpleITK as sitk for filename in filenames: image = sitk.ReadImage(filename) Each of the volumes has different size, spacing, origin and direction. This code yields different values for different images: print(image.GetSize()) print(image.GetOrigin()) print(image.GetSpacing()) print(image.GetDirection()) My question is: how do I transform the images to have the same size and spacing so that they all have the same resolution and size when converted to numpy arrays. Something like: import SimpleITK as sitk for filename in filenames: image = sitk.ReadImage(filename) image = transform(image, fixed_size, fixed_spacing) array = sitk.GetArrayFromImage(image)
favorite count: 0
has answer: http://stackoverflow.com/a/48065819
has answer: http://stackoverflow.com/a/63120034
has title: SimpleITK Resize images
tagged with: python
tagged with: computer-vision

http://stackoverflow.com/q/48042973
has answer: http://stackoverflow.com/a/48043050
type: Question
has comment: http://stackoverflow.com/comment/83061455
has comment: http://stackoverflow.com/comment/83056832
score: -1
accepted answer: http://stackoverflow.com/a/48043050
has title: HTML parsing forbidden error
has body: import re import urllib.request url='''https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=''' Stock = input('Enter the stock name: ').upper() url = url + Stock comp_info = urllib.request.urlopen(url).read() I am getting forbidden error, not able to understand the issue with the code. I am trying to input ITC.
answer count: 1
linked to: http://stackoverflow.com/q/16627227
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83056738
downvote count: 2
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48081927
has answer: http://stackoverflow.com/a/48081977
tagged with: pandas
tagged with: python
has title: Adding a new column based on values of another column in Pandas(python)
possible better answer: http://stackoverflow.com/a/48081988
upvote count: 1
has answer: http://stackoverflow.com/a/48082024
type: Question
type: AnsweredQuestion
score: 1
has body: Given a dataframe that looks something like Vote A Vote B 1 4 3 2 1 5 I want to add a new column named Winner that compares the value between two columns Vote A and Vote B and specify the winner. Winner B A B How can I do this in Pandas?
accepted answer: http://stackoverflow.com/a/48081977
answer count: 3
has answer: http://stackoverflow.com/a/48081988
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/83242709
has text: Sorry again, I must learn how to format this properly, have I done something wrong or misinterpreted your suggestion? Thanks
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48132007
type: AnswerComment

http://stackoverflow.com/q/48079316
has title: Python : error tuple index out of range when plotting pandas columns X Vs Y
has comment: http://stackoverflow.com/comment/83133416
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/101539256
tagged with: pandas
answer count: 1
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/57552414
tagged with: python
has comment: http://stackoverflow.com/comment/83132740
upvote count: 2
type: UnansweredQuestion
downvote count: 1
has body: Dears, happy new year 2018 from a french living in Shanghai I'm facing an issue when trying to plot a pandas dataframe into a canvas. The context is that I have an emmbedded graphic into a tkinter frame. So the matplotlib graphic should be in this frame (by creating a subplot) Regarding the data, this is an SQL extraction of 4.5M rows and 45 columns that I saved into a pickle. I'm applying some operations to reduce the size of the data in memory, then sorting and grouping, to finaly create a dataframe with the index and 3 columns DM_DESC, YEAR and SALES_W_VAT. Important to mention that DM_DESC is a category type because I want this column to be the X Axis of the graphic, ordered according to the list (listDM in the code below). Finally, when plotting the DM_DESC as X axis, and SALES_W_VAT as value, I got the famous error "tuple index out of range" I read a lot of docs on this error, but I really don't understand where the problem is.... Would appreciate your help [EDIT] : based on the first comments, I have created a small program with reproducible error. The problem comes for the line I tried to order the colum DM_DESC according to the list listDM DonneesBase["DM_DESC"]=pd.Categorical(DonneesBase["DM_DESC"],np.array(ListDM) ,ordered=True) If I comment this line, there is no error, plotting is fine, but the Xaxis is not ordered as expected Also what is interesting is that if I plot the dataframe directly with df.plot, I have no error, and the X-axis order is the expected one. So weird import matplotlib.pyplot as plt imp ort pandas as pd import numpy as np ListDM = [ 'Jan Big Low price',\ 'CNY 1',\ 'CNY 2'] f=plt.figure() a=f.add_subplot(111) DonneesBase = pd.DataFrame({"DM_DESC":["CNY 2","Jan Big Low price","CNY 1"],"YEAR":[2017,2017,2017], "SALES_W_VAT":[2.254691e+09, 2.509911e+09,1.8e+09]}) #ORDER COMMAND USING CATEGORICAL AND ARRAY DonneesBase["DM_DESC"]=pd.Categorical(DonneesBase["DM_DESC"],np.array(ListDM) ,ordered=True) sales = pd.DataFrame(DonneesBase[(Donnee…
tagged with: plot
type: Question

http://stackoverflow.com/comment/83326173
has text: Thank you for your hint. It is much better and easier to use List. Thank you!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48161671

timeit
tag name: timeit
type: Tag
tags question: http://stackoverflow.com/q/48096903

http://stackoverflow.com/q/48091504
upvote count: 1
has comment: http://stackoverflow.com/comment/83158080
favorite count: 0
tagged with: datetime
tagged with: python
linked to: http://stackoverflow.com/q/13685201
downvote count: 0
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/13685201
type: Question
has body: api_time = datetime.strptime( response_time, "%H:%M") Debugging has shown that api_time : 1900-01-01 06:30:00 All i want to do is to add 7 hours so the time is 13:30:00 how can i do it
has title: How can i add 7 hours into api_time?
score: 1
has comment: http://stackoverflow.com/comment/83157280
has comment: http://stackoverflow.com/comment/83157392

http://stackoverflow.com/comment/83109644
has text: @user2769952 are you required to use python 2? its mostly deprecated now
comment on: http://stackoverflow.com/a/48067935
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83345968
score: 1
type: AnswerComment
has text: Thank you very much. Your solution is nice! It works now. Thank you
type: Comment
comment on: http://stackoverflow.com/a/48181721

http://stackoverflow.com/a/48109729
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83195927
accepted answer of: http://stackoverflow.com/q/48109624
type: AcceptedAnswer
downvote count: 0
has body: Using diff is the right approach - just combine it with gt and cumsum and you have your groups. The idea is to use cumulative sum for differences bigger than your threshold. Difference larger than your threshold will become True. In contrast, differences equal or lower to your threshold will become False. Cumulatively summing over the boolean values will leave differences equal or lower to your threshold unchanged and hence they get the same group number. max_distance = 1 df["group_diff"] = df.sort_values("val")\ .groupby("group_number")["val"]\ .diff()\ .gt(max_distance)\ .cumsum() print(df) group_number val group_diff 0 1 5 0 1 1 8 1 2 1 12 2 3 1 13 2 4 1 22 5 5 1 26 6 6 1 31 8 7 2 7 0 8 2 16 3 9 2 17 3 10 2 19 4 11 2 29 7 12 2 33 9 13 2 62 10 You can now use groupby on group_number and group_diff and see the resulting groups with the following: grouped = df.groupby(["group_number", "group_diff"]) print(grouped.groups) {(1, 0): Int64Index([0], dtype='int64'), (1, 1): Int64Index([1], dtype='int64'), (1, 2): Int64Index([2, 3], dtype='int64'), (1, 5): Int64Index([4], dtype='int64'), (1, 6): Int64Index([5], dtype='int64'), (1, 8): Int64Index([6], dtype='int64'), (2, 0): Int64Index([7], dtype='int64'), (2, 3): Int64Index([8, 9], dtype='int64'), (2, 4): Int64Index([10], dtype='int64'), (2, 7): Int64Index([11], dtype='int64'), (2, 9): Int64Index([12], dtype='int64'), (2, 10): Int64Index([13], dtype='int64')} Thanks @jezrael for the hint of avoiding a new column to increase performance: group_diff = df.sort_values("val")\ .groupby("group_number")["val"]\ .diff()\ .gt(max_distance)\ .cumsum() grouped = df.groupby(["group_number", group_diff])
has comment: http://stackoverflow.com/comment/83195204
type: Answer
has comment: http://stackoverflow.com/comment/83196106
has comment: http://stackoverflow.com/comment/83196159
answers question: http://stackoverflow.com/q/48109624
has comment: http://stackoverflow.com/comment/83195986
has comment: http://stackoverflow.com/comment/83195368
has comment: http://stackoverflow.com/comment/83195175
has comment: http://stackoverflow.com/comment/83197592
has comment: http://stackoverflow.com/comment/83195263

http://stackoverflow.com/comment/83297306
type: AnswerComment
score: 1
has text: A list comprehension may be more readable than `filter`: `vowelCount = len([c for c in text if c.lower() in ['a','e','i','o','u']])`
comment on: http://stackoverflow.com/a/48158874
type: Comment

http://stackoverflow.com/a/48021809
score: 0
has body: It seems that I had to do an explicit wait after updating the iframe. import time time.sleep(2)
type: Answer
answers question: http://stackoverflow.com/q/48020641

javascript
tags question: http://stackoverflow.com/q/48098631
tags question: http://stackoverflow.com/q/48171159
tags question: http://stackoverflow.com/q/48020177
tags question: http://stackoverflow.com/q/48036365
tags question: http://stackoverflow.com/q/48026322
tags question: http://stackoverflow.com/q/48075495
tags question: http://stackoverflow.com/q/48032708
tags question: http://stackoverflow.com/q/48137081
tags question: http://stackoverflow.com/q/48030474
tags question: http://stackoverflow.com/q/48019321
tags question: http://stackoverflow.com/q/48016462
tags question: http://stackoverflow.com/q/48150328
tags question: http://stackoverflow.com/q/48042083
tags question: http://stackoverflow.com/q/48131317
tag name: javascript
tags question: http://stackoverflow.com/q/48160199
tags question: http://stackoverflow.com/q/48104693
tags question: http://stackoverflow.com/q/48064033
tags question: http://stackoverflow.com/q/48143233
tags question: http://stackoverflow.com/q/48118872
tags question: http://stackoverflow.com/q/48126313
tags question: http://stackoverflow.com/q/48136491
tags question: http://stackoverflow.com/q/48024578
tags question: http://stackoverflow.com/q/48097297
type: Tag
tags question: http://stackoverflow.com/q/48089903
tags question: http://stackoverflow.com/q/48152431
tags question: http://stackoverflow.com/q/48160147
tags question: http://stackoverflow.com/q/48018281
tags question: http://stackoverflow.com/q/48020309
tags question: http://stackoverflow.com/q/48138479
tags question: http://stackoverflow.com/q/48060738
tags question: http://stackoverflow.com/q/48015074
tags question: http://stackoverflow.com/q/48104460
tags question: http://stackoverflow.com/q/48069013
tags question: http://stackoverflow.com/q/48159567
tags question: http://stackoverflow.com/q/48103435
tags question: http://stackoverflow.com/q/48058581
tags question: http://stackoverflow.com/q/48125278
tags question: http://stackoverflow.com/q/48030864
tags question: http://stackoverflow.com/q/48053060
tags question: http://stackoverflow.com/q/48089942
tags question: http://stackoverflow.com/q/48040020
tags question: http://stackoverflow.com/q/48139864
tags question: http://stackoverflow.com/q/48106087
tags question: http://stackoverflow.com/q/48050870
tags question: http://stackoverflow.com/q/48085374
tags question: http://stackoverflow.com/q/48126969
tags question: http://stackoverflow.com/q/48032772
tags question: http://stackoverflow.com/q/48070250
tags question: http://stackoverflow.com/q/48054922
tags question: http://stackoverflow.com/q/48050595
tags question: http://stackoverflow.com/q/48173192
tags question: http://stackoverflow.com/q/48027558

http://stackoverflow.com/comment/83210085
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48116789
score: 0
has text: I'm sorry if there's some duplication, but what seems like the critical line of my code looks almost identical to that of the first solution, yet mine doesn't seem to work. (The grid will be small, so an O(n^2) algorithm is fine.)

http://stackoverflow.com/comment/83232238
type: QuestionComment
has text: Possible duplicate of [Python Hexadecimal](https://stackoverflow.com/questions/14678132/python-hexadecimal)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48127757

http://stackoverflow.com/comment/83282656
score: 0
type: QuestionComment
has text: Brilliant minds type almost equally fast? Or what's that old saying.
comment on: http://stackoverflow.com/q/48152069
type: Comment

http://stackoverflow.com/q/48050998
has answer: http://stackoverflow.com/a/48051846
tagged with: scikit-learn
tagged with: python-3.x
tagged with: python
has body: I am currently trying to convert the dataframe below: 0 Cat Chicken 1 Fish Chicken 2 Fish Cat 3 Cat Chicken 4 Dog Cat To Cat Fish Dog Chicken 0 1 0 0 1 1 0 1 0 1 2 1 1 0 0 3 1 0 0 1 4 1 0 1 0 So far I have only managed to successfully do Label Binarizer of singular columns. I can imagine doing this in a brute force manner where I loop through everything and check conditionally. However, that would cause the run time to be quite long. Therefore, is there a smarter way of doing this?
accepted answer: http://stackoverflow.com/a/48051846
score: 0
possible better answer: http://stackoverflow.com/a/48051086
has title: Label Binarizer: Multiple Columns
type: Question
has answer: http://stackoverflow.com/a/48051086
type: AnsweredQuestion
answer count: 2
tagged with: pandas

http://stackoverflow.com/q/48033065
has answer: http://stackoverflow.com/a/48033117
tagged with: python
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48033109
score: 1
has comment: http://stackoverflow.com/comment/83036261
upvote count: 1
has comment: http://stackoverflow.com/comment/83036263
has answer: http://stackoverflow.com/a/78168444
type: Question
has body: I'm trying to read multiple lines in a file and it doesn't seem to work when I assigned my readline() method to a variable. It keeps printing the first line. It only seems to work when I don't assign it to a variable. Any ideas? I'm using Python 3.6.2. Here is my code: # This is it not working ( I omitted the 'gradesfile_path' variable) gradesfile = open(gradesfile_path,'r') readgrades = gradesfile.readline() print(readgrades) print(readgrades) # This is working when I don't call the variable print(gradesfile.readline()) print(gradesfile.readline()) print(gradesfile.readline())
has answer: http://stackoverflow.com/a/48033221
has answer: http://stackoverflow.com/a/48033109
has comment: http://stackoverflow.com/comment/83036265
downvote count: 0
possible better answer: http://stackoverflow.com/a/48033117
favorite count: 0
has comment: http://stackoverflow.com/comment/83036400
has title: readline() only reading the first line

http://stackoverflow.com/comment/83084187
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48055472
type: Comment
has text: I wrote above: this is not how minimization works. You don't get to say "minimize so that the minimum is zero". The attempt to put "objective==0" as a constraint is never going to work.

http://stackoverflow.com/a/48168368
has body: There is ) at line 171 and line 175 without any ( which must be causing syntax error. many code lines are unreachable because you are coding return before them but those won't cause syntax error. You can watch the logs on Cloudwatch. The blueprint which you are using is very complex and not beginner friendly. You really should be using this blueprint for starting. That is my suggestion. Also, since you are using response_card so please be aware that the response cards won't be shown in the Lex Console window. It will work in Facebook and Slack though.
has comment: http://stackoverflow.com/comment/83318600
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83387312
has comment: http://stackoverflow.com/comment/83317795
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83387376
answers question: http://stackoverflow.com/q/48166178
type: Answer
accepted answer of: http://stackoverflow.com/q/48166178

http://stackoverflow.com/comment/83040552
type: Comment
score: 3
comment on: http://stackoverflow.com/q/48034696
type: QuestionComment
has text: put all information in question. You can also create minimal working example.

http://stackoverflow.com/a/48601819
has body: Suppose you want to use the same code to do your training and validation. You might like to use the same iterator, but initialized to point to different datasets; something like the following: def _make_batch_iterator(filenames): dataset = tf.data.TFRecordDataset(filenames) ... return dataset.make_initializable_iterator() filenames = tf.placeholder(tf.string, shape=[None]) iterator = _make_batch_iterator(filenames) with tf.Session() as sess: for epoch in range(num_epochs): # Initialize iterator with training data sess.run(iterator.initializer, feed_dict={filenames: ['training.tfrecord']}) _train_model(...) # Re-initialize iterator with validation data sess.run(iterator.initializer, feed_dict={filenames: ['validation.tfrecord']}) _validate_model(...) With a one-shot iterator, you can't re-initialize it like this.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91302096
answers question: http://stackoverflow.com/q/48091693
type: Answer
accepted answer of: http://stackoverflow.com/q/48091693
has comment: http://stackoverflow.com/comment/87219509
upvote count: 12
has comment: http://stackoverflow.com/comment/108445815
score: 12

http://stackoverflow.com/q/48157113
has answer: http://stackoverflow.com/a/48160750
upvote count: 0
answer count: 1
has title: I Can't Get Whiteboard To Draw After Setting IT At Toplevel - Tkinter
has comment: http://stackoverflow.com/comment/83293463
tagged with: python
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/83294254
score: -1
has comment: http://stackoverflow.com/comment/83301000
has body: When set as root the whiteboard functions correctly, now moved to a Toplevel popup, lines can only emanate from 0,0 outward, creating nice graphical lines from the top left corner. NOT THE INTENDED OBJECTIVE..mmm. I suspect it has something to do with my 'global' statements but I'm stuck never the less. Here is the code as it sits Toplevel within a shell canvas: # WHITEBOARD POPUP def whiteboardPanel(): whitePanel = Toplevel(root) whitePanel.transient(root) whitePanel.title("WHITEBOARD") whitePanel.minsize(550,600) whitePanel.maxsize(550,600) #whitePanel.focus_set() #whitePanel.grab_set() whitePanel.geometry("550x600+1800+215") lastX, lastY = 0, 0 colour = "black" erase = "white" thick = 5 # ========= FUNCTION DEF ========== def set_colour_red(event): global colour colour = "red" thick = 5 def set_colour_green(event): global colour colour = "green" thick = 5 def set_colour_black(event): global colour colour = "black" thick = 5 def set_colour_erase(event): global colour colour = "white" thick = 10 def store_position(event): lastX = event.x lastY = event.y def on_click(event): store_position(event) def on_drag(event): lastX, lastY = 0, 0 canvas.create_line(lastX, lastY, event.x, event.y, fill=colour, width=thick) store_position(event) canvas = Canvas(whitePanel, width=550, height=600, bg="white") canvas.pack() # fill='both', expand=True, padx=6, pady=6) canvas.bind("&lt;Button-1&gt;", on_click) canvas.bind("&lt;B1-Motion&gt;", on_drag) red_id = canvas.create_rectangle(10, 10, 30, 30, fill="red") green_id = canvas.create_rectangle(10, 35, 30, 55, fill="green") black_id = canvas.create_rectangle(10, 60, 30, 80, fill="black") erase_id = canvas.create_rectangle(10, 85, 30, 105, fill="white") canvas.tag_bind(red_id, "&lt;Button-1&gt;", set_colour_red) canvas.tag_bind(green_id, "&lt;Button-1&gt;", set_colour_green) canvas.tag_bind(black_id, "&lt;Button-1&gt;", set_colour_black) canvas.tag_bind(erase_id, "&lt;Button-1&gt;", set_colour_erase) ....somewhere down below ....root…
type: Question

http://stackoverflow.com/q/48038535
has comment: http://stackoverflow.com/comment/83047746
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48042582
linked to: http://stackoverflow.com/q/46135070
has body: Suppose we have a distance matrix as following: array([[ 0. , 0.2039889 , 0.25030506, 0.56118992], [ 0.2039889 , 0. , 0.39916797, 0.6909994 ], [ 0.25030506, 0.39916797, 0. , 0.63389566], [ 0.56118992, 0.6909994 , 0.63389566, 0. ]]) How can I get the values of the upper matrix with their indexes like : 1 0.2039889 1 2 2 0.25030506 1 3 3 0.56118992 1 4 4 0.39916797 2 3 5 0.6909994 2 4 6 0.63389566 3 4
tagged with: numpy
answer count: 2
tagged with: arrays
has title: Get the values of the upper triangle of a matrix with their indexes
score: 0
tagged with: matrix
possible better answer: http://stackoverflow.com/a/48042582
tagged with: python
has answer: http://stackoverflow.com/a/48039268
accepted answer: http://stackoverflow.com/a/48039268

http://stackoverflow.com/q/48122975
has title: Exec(file.py) with arguments not working
has comment: http://stackoverflow.com/comment/83223169
has answer: http://stackoverflow.com/a/48122988
score: 0
tagged with: http://stackoverflow.com/tag/html
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/83222799
has body: i have to create a website to compare two pictures given by the user. I've created the pyhton file to compare this two files ( using sys.argv in python ) but i don't know how can I put arguments for my python prog. I've tried with &amp;argv1 and &amp;argv2 and put it row in: [...] &amp;argv1 = "image.jpg" &amp;argv2 = "image2.jpg" $command = escapeshellcmd('Diff1.py'); $output = shell_exec($command); exec ('Diff1.py' &amp;argv1 &amp;argv2); echo '&lt;p&gt;&lt;img src="resultat.jpg" alt="icon"/&gt;&lt;/p&gt;'; //The Python prog return a file named resultat.jpg and i have to show it but it didn't works. So how could I do ? Thank you in advance!
type: Question

http://stackoverflow.com/comment/83234514
type: Comment
comment on: http://stackoverflow.com/a/48123430
has text: Wow, that was perfect. Thank you!
type: AnswerComment
score: 1

http://stackoverflow.com/q/48160798
tagged with: pip
tagged with: django
tagged with: python
tagged with: installation
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48160861
has title: ImportError after successful pip install
answer count: 1
has body: I install some lib in docker pip3.4 install after installation I received the message Successfully installed &lt;lib&gt; I checked install by pip3.4 list and was in list I write code in setting MIDDLEWARE_CLASSES += (&lt;lib&gt;,) INSTALLED_APPS += (&lt;lib&gt;,) Runserver in Pycharm and I got MSG Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7f1b69b9b400&gt; Traceback (most recent call last): File "/usr/local/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.4/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.4/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.4/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.4/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 2254, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 2237, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 2224, in _find_and_load_unlocked ImportError: No module named 'silk'
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/83262957
has text: @COLDSPEED Awesome! The non-greedy matcher was the key then!! Thanks. P.S- I ended up using the extract for this one! Thanks for a lot!!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48142189

http://stackoverflow.com/a/48137073
has body: As already stated in comments, a=smf should be a=smf(). But why do you get that error? In Python, instance.method(args...) is kind of syntactic sugar for class.method(instance, args...), which explains why the first argument of methods is the instance itself, usually called self. And by doing a=smf, a is another reference to the class itself, so you are actually calling the method in the class.method(instance, args...) kind of way missing the self instance.
type: Answer
accepted answer of: http://stackoverflow.com/q/48134162
answers question: http://stackoverflow.com/q/48134162
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48017874
has body: I am a newbie in django social auth. I am using social-auth-app-django to authenticate Microsoft Azure AD user. Authentication process works well and user object is created inside the database. But request.user is returing null inside view. Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', # 'social.apps.django_app.default', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', 'social.apps.django_app.context_processors.backends', 'social.apps.django_app.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social.backends.azuread.AzureADOAuth2', ) #settings.py SOCIAL_AUTH_PIPELINE = { 'pipeline.new_users_handler' } View def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) context = { 'title':'Home Page', 'year':datetime.now().year, 'request': request, 'user': request.user, } context_instance = RequestContext(request,context) return render( request, 'index.html',context) The request.user works fine when I login as admin or any other user created using admin. The issue is when authenticated via social aut…
score: 0
has title: request.user returns None Django social-auth-app-django
has comment: http://stackoverflow.com/comment/114556158
answer count: 1
type: UnansweredQuestion
tagged with: azure
tagged with: python
has answer: http://stackoverflow.com/a/48018217
tagged with: django
type: Question
tagged with: django-socialauth

http://stackoverflow.com/q/48086081
tagged with: defaultdict
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48086115
has title: Error Changing Dictionary Keys
possible better answer: http://stackoverflow.com/a/48086751
has answer: http://stackoverflow.com/a/48086751
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48086115
type: Question
has body: I've two defaultdicts I eventually want to merge, but first I need to make their keys match. According to some threads I've seen here, I can use pop() to replace keys in a dictionary. But that only updates the existing dictionary, whereas I want to create a new dictionary with the new keys. So something like: existing_dict_one -> new_dict_one This is what I've so far: def split_tabs(x): """ Function to split tab-separated strings, used to break up the keys that are separated by tabs. """ return x.split('\t') def create_dict(old_dict): """ Function to create a new defaultdict from an existing defaultdict, just with different keys. """ new_dict = old_dict.copy() # Create a copy of old_dict to house the new keys, but with the same values. for key, value in new_dict.iteritems(): umi = split_tabs(key)[0] # Change key to be UMI, which is the 0th index of the tab-delimited key. # new_key = key.replace(key, umi) new_dict[umi] = new_dict.pop(key) return new_dict However, I'm getting the following error RuntimeError: dictionary changed size during iteration and I don't know how to fix it. Does anyone know how to correct it? I'd like to use the variable "umi" as the new key. I'd like to post the variable "key" and dictionary "old_dict" I'm using for testing this code, but it's messy and takes up a lot of space. So here's a pastebin link that contains them instead. Note that "umi" comes from variable "key" which is separated by tabs. So I split "key" and get the first object as "umi".
score: 0
answer count: 2
tagged with: key

http://stackoverflow.com/a/54973781
downvote count: 0
has body: ds = pd.read_csv('/Dataset/test.csv', encoding='windows-1252') Works fine for me, thanks.
answers question: http://stackoverflow.com/q/48067514
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/a/48083131
answers question: http://stackoverflow.com/q/48082893
has body: You need to add a super call to Base1 so that Base2's __init__ will get called after Base1's. You can also add a super call to Base2. It's not necessary, but it won't hurt. class Base1(object): def __init__(self): super(Base1, self).__init__() self.base1var = "this is base1" class Base2(object): def __init__(self): #super(Base2, self).__init__() self.base2var = "this is base2" class MainClass(Base1, Base2): def __init__(self): super(MainClass, self).__init__() if __name__ == "__main__": a = MainClass() print a.base1var print a.base2var output this is base1 this is base2 BTW, you really should be using Python 3. super is much nicer in modern Python. :)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48082893
score: 8
has comment: http://stackoverflow.com/comment/83140989
type: Answer
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/83140930

http://stackoverflow.com/q/48103536
type: Question
score: 4
linked to: http://stackoverflow.com/q/29550414
upvote count: 4
accepted answer: http://stackoverflow.com/a/48103583
possible better answer: http://stackoverflow.com/a/48130307
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48130307
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: Stripping proper nouns from text
has answer: http://stackoverflow.com/a/61171449
has body: I have a df with several thousand rows of text data. I'm using spaCy to do some NLP on a single column of that df and and am trying to remove proper nouns, stop words, and punctuation from my text data using the following: tokens = [] lemma = [] pos = [] for doc in nlp.pipe(df['TIP_all_txt'].astype('unicode').values, batch_size=9845, n_threads=3): if doc.is_parsed: tokens.append([n.text for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn]) lemma.append([n.lemma_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn]) pos.append([n.pos_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn]) else: tokens.append(None) lemma.append(None) pos.append(None) df['s_tokens_all_txt'] = tokens df['s_lemmas_all_txt'] = lemma df['s_pos_all_txt'] = pos df.head() But I get this error and I'm not sure why: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-34-73578fd46847&gt; in &lt;module&gt;() 6 n_threads=3): 7 if doc.is_parsed: ----&gt; 8 tokens.append([n.text for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn]) 9 lemma.append([n.lemma_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn]) 10 pos.append([n.pos_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn]) &lt;ipython-input-34-73578fd46847&gt; in &lt;listcomp&gt;(.0) 6 n_threads=3): 7 if doc.is_parsed: ----&gt; 8 tokens.append([n.text for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn]) 9 lemma.append([n.lemma_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn]) 10 pos.append([n.pos_ for n in doc if not n.is_punct and not n.is_stop and not n.is_space and not n.is_propn]) AttributeError: 'spacy.tokens.token.Token' object has no attribute 'is_propn' If I tak…
tagged with: python
type: AnsweredQuestion
tagged with: spacy
has answer: http://stackoverflow.com/a/48103583

http://stackoverflow.com/q/48046020
type: AnsweredQuestion
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/48046163
type: Question
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/74299987
has answer: http://stackoverflow.com/a/48046163
answer count: 4
possible better answer: http://stackoverflow.com/a/60739427
has answer: http://stackoverflow.com/a/60739427
has title: PassingCars in Codility using Python
upvote count: 2
has answer: http://stackoverflow.com/a/70721318
tagged with: python
has body: I have a coding challenge next week as the first round interview. The HR said they will use Codility as the coding challenge platform. I have been practicing using the Codility Lessons. My issue is that I often get a very high score on Correctness, but my Performance score, which measure time complexity, is horrible (I often get 0%). Here's the question: https://app.codility.com/programmers/lessons/5-prefix_sums/passing_cars/ My code is: def solution(A): N = len(A) my_list = [] count = 0 for i in range(N): if A[i] == 1: continue else: my_list = A[i + 1:] count = count + sum(my_list) print(count) return count It is supposed to be O(N) but mine is O(N**2). How can someone approach this question to solve it under the O(N) time complexity? In general, when you look at an algorithm question, how do you come up with an approach?
score: 2

http://stackoverflow.com/q/48101040
has title: Slice a 3D array in to multiple 2D arrays
has comment: http://stackoverflow.com/comment/83181860
accepted answer: http://stackoverflow.com/a/48101317
has body: I have a numpy array of shape(64,64,3). How can we get three arrays of dimension (64,64) each.
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48103207
has comment: http://stackoverflow.com/comment/83177654
has answer: http://stackoverflow.com/a/48103207
has comment: http://stackoverflow.com/comment/83177400
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48101317
has comment: http://stackoverflow.com/comment/83177522
score: 1
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/83177475

http://stackoverflow.com/q/48068829
has answer: http://stackoverflow.com/a/48070685
type: AnsweredQuestion
has title: Representing non-English characters with Unicode (UTF-8)
has answer: http://stackoverflow.com/a/57436479
type: Question
score: 0
answer count: 3
tagged with: encoding
has body: I am working with an HTML string in Python that contains non-English characters that is represented in the string by 16-bit unicode hex values. The string reads: "Skräddarevägen" The string when properly converted should read "Skräddarevägen". How do i ensure that the unicode hex value gets correctly encoded/decoded on output and reads with the correct accents? (Note, I'm using Requests and Pandas and the encoding in both is set to utf-8) Thanks in advance!
possible better answer: http://stackoverflow.com/a/57436479
tagged with: unicode
accepted answer: http://stackoverflow.com/a/48070685
has answer: http://stackoverflow.com/a/48069139
tagged with: decoding
tagged with: python
tagged with: utf-8

http://stackoverflow.com/comment/83033424
type: Comment
has text: i'm a bit confused, how do I call get the timer on to execute my method at the given time? I'm both new to python and to timer. I use Python 3
type: AnswerComment
comment on: http://stackoverflow.com/a/48031438
score: 0

http://stackoverflow.com/comment/83109240
type: Comment
has text: Now that you mention it I tried creating a file using the python interpreter and when I try to read it, it gives me a bunch of hexvalue.
comment on: http://stackoverflow.com/q/48067160
score: 0
type: QuestionComment

http://stackoverflow.com/q/48170954
upvote count: 0
tagged with: dataframe
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/17241004
has comment: http://stackoverflow.com/comment/83321404
tagged with: pandas
has comment: http://stackoverflow.com/comment/83321632
has comment: http://stackoverflow.com/comment/83321343
score: -1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83321254
tagged with: python
answer count: 1
has title: Return first column in DataFrame as a list of string values
has answer: http://stackoverflow.com/a/48171258
has comment: http://stackoverflow.com/comment/83321602
has body: how can I return a list of string values for first column (State) from below DataFrame? Population State County California Los Angeles County 9818605 Illinois Cook County 5194675 Texas Harris County 4092459
downvote count: 1
has comment: http://stackoverflow.com/comment/83321386

http://stackoverflow.com/a/58536235
has comment: http://stackoverflow.com/comment/120470227
has body: If you want to bypass your local disk and upload directly the data to the cloud, you may want to use pickle instead of using a .npy file: import boto3 import io import pickle s3_client = boto3.client('s3') my_array = numpy.random.randn(10) # upload without using disk my_array_data = io.BytesIO() pickle.dump(my_array, my_array_data) my_array_data.seek(0) s3_client.upload_fileobj(my_array_data, 'your-bucket', 'your-file.pkl') # download without using disk my_array_data2 = io.BytesIO() s3_client.download_fileobj('your-bucket', 'your-file.pkl', my_array_data2) my_array_data2.seek(0) my_array2 = pickle.load(my_array_data2) # check that everything is correct numpy.allclose(my_array, my_array2) Documentation: boto3 pickle BytesIO
has comment: http://stackoverflow.com/comment/105627772
has comment: http://stackoverflow.com/comment/123373789
downvote count: 0
type: Answer
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/123371853
answers question: http://stackoverflow.com/q/48049557

http://stackoverflow.com/q/48077737
favorite count: 0
has body: Probably a regex question (forgive my broken english). I need to identify a sub string that starts with a certain value. For example, take the following string: "Select 1 from user.table1 inner join user.table2..." I need to extract all the words that start with "user" and end with "blank space". So, after applying this "unkown" regex to the above string, it would produce the following result: table1 table2 I tried to use the "re.findall" function, but couldn't find a way to specify the start and end patterns. So, how can extract the substrings using a starting pattern?
tagged with: python
has answer: http://stackoverflow.com/a/48087914
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48077982
has comment: http://stackoverflow.com/comment/83129598
has comment: http://stackoverflow.com/comment/83129331
has title: Extract Substring values with key pattern
upvote count: 2
possible better answer: http://stackoverflow.com/a/48077982
score: 0
answer count: 2
downvote count: 2
accepted answer: http://stackoverflow.com/a/48087914

http://stackoverflow.com/comment/83300336
has text: if you know that every character in `changedword` is an `int` you could cast it as an `int` with `int()`. but this could cause bugs if you have non `int` characters
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48160373

http://stackoverflow.com/a/48197838
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48026805
type: Answer
has body: Probably is related to your CLASSPATH values. Jython needs to be related to the location of your JDBC drivers. In my case using Jython 2.7.0 in Linux, I review inside the interpeter, what are the CLASSPATH locations that Jython search by default: Type into the Jython interpeter: Jython 2.7.0 (default:9987c746f838, Apr 29 2015, 02:25:11) [Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_151 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/opt/jython/Lib', '__classpath__', '__pyclasspath__/', '/opt/jython/Lib/site-packages'] &gt;&gt;&gt; sys.path.append("/opt/jython/jdbc/derby.jar") &gt;&gt;&gt; sys.path.append("/opt/jython/jdbc/derbyclient.jar") &gt;&gt;&gt; sys.path ['', '/opt/jython/Lib', '__classpath__', '__pyclasspath__/', '/opt/jython/Lib/site-packages', '/opt/jython/jdbc/derby.jar', '/opt/jython/jdbc/derbyclient.jar'] &gt;&gt;&gt; The way that I found to resolve this problem, is call the driver's directory with the files, to the sys.path. Example: Jython 2.7.0 (default:9987c746f838, Apr 29 2015, 02:25:11) [Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_151 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', '/opt/jython/Lib', '__classpath__', '__pyclasspath__/', '/opt/jython/Lib/site-packages'] &gt;&gt;&gt; sys.path.append("/opt/jython/jdbc/derby.jar") &gt;&gt;&gt; sys.path.append("/opt/jython/jdbc/derbyclient.jar") &gt;&gt;&gt; sys.path ['', '/opt/jython/Lib', '__classpath__', '__pyclasspath__/', '/opt/jython/Lib/site-packages', '/opt/jython/jdbc/derby.jar', '/opt/jython/jdbc/derbyclient.jar'] &gt;&gt;&gt; from com.ziclix.python.sql import zxJDBC &gt;&gt;&gt; d, u, p, v = "jdbc:derby://localhost:1527//opt/apache-derby/derbydata/derbytutor/mundialito", "APP", "APP", "org.apache.derby.jdbc.ClientDriver" &gt;&gt;&gt; db = zxJDBC.connect(d, u, p, v) &gt;&gt;&gt; c = db.cursor() &g…
upvote count: 1

http://stackoverflow.com/comment/83124628
type: QuestionComment
has text: That's how this indicator works, it's calculation based on it's previous value
score: 0
comment on: http://stackoverflow.com/q/48062788
type: Comment

http://stackoverflow.com/comment/83108027
comment on: http://stackoverflow.com/q/48067228
has text: The requested URL was not found on this server
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48067886
has comment: http://stackoverflow.com/comment/83109560
linked to: http://stackoverflow.com/q/17101845
has comment: http://stackoverflow.com/comment/83109586
answer count: 1
has comment: http://stackoverflow.com/comment/83109397
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83154759
score: 6
has comment: http://stackoverflow.com/comment/83111673
has comment: http://stackoverflow.com/comment/83109442
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/76245451
has comment: http://stackoverflow.com/comment/83112034
has comment: http://stackoverflow.com/comment/102232621
upvote count: 7
downvote count: 1
has title: How can a type be incompatible with itself?
type: Question
has body: In my django application (Django 1.6.0, python 2.7.5 running on Red Hat), my database driver is seeing an error from ctypes: TypeError: incompatible types, LP_c_int instance instead of LP_c_int instance The code looks like this: is_null = value is None param.value.is_null = pointer(c_int(is_null)) &lt;-- error occurs on this line I'm not really familiar with ctypes (I inherited this code) but on the surface, this error message makes no sense. The code has been running for years but I'm now seeing this error all over the place. Am I doing something obviously wrong? Here is a minimal repro thanks to the comment from Ilja Everilä: from ctypes import * from ctypes import _reset_cache class DataValue(Structure): """Must match a_sqlany_data_value.""" _fields_ = [("buffer", POINTER(c_char)), ("buffer_size", c_size_t), ("length", POINTER(c_size_t)), ("type", c_int), ("is_null", POINTER(c_int))] d = DataValue() _reset_cache() is_null = False d.is_null = pointer( c_int( is_null ) )
tagged with: ctypes

http://stackoverflow.com/comment/83066367
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48040545
has text: Did you save the simplified polygons in a new field for caching? Did you try saving the geojson in a new field for can caching? Are you serving for usage in a js map?

http://stackoverflow.com/a/48086905
answers question: http://stackoverflow.com/q/48086841
upvote count: 1
type: Answer
has body: Your if should be a while if you want the result to be as you expected: while num &gt; 2: print(num) num -= 1 print(num) &gt; 5 &gt; 4 &gt; 3 &gt; 2
score: 1
downvote count: 0

http://stackoverflow.com/a/48169976
has comment: http://stackoverflow.com/comment/83323050
has body: General conditional syntax is like this: {% if some_variable == some_value %} {{ do_something }} {% endif %} Docs have some more examples.
has comment: http://stackoverflow.com/comment/83325128
downvote count: 0
type: Answer
upvote count: 59
has comment: http://stackoverflow.com/comment/84512199
score: 59
answers question: http://stackoverflow.com/q/48169611

http://stackoverflow.com/comment/83179480
has text: and the parse_dates arg in pd.read_csv seems to do the trick when reading in the data
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48101560

http://stackoverflow.com/a/48068317
has body: Consider MySQL's dialect-specific aggregate function group_concat: SELECT pd.prj_id, GROUP_CONCAT(pd.dl_id) AS grp_ids, GROUP_CONCAT(pd.name) AS grp_name, GROUP_CONCAT(pd.email) AS grp_email FROM projects_doc pd JOIN reminder rm ON pd.prj_id = rm.prj_id WHERE doc_typ = 'assignment' GROUP BY pd.prj_id ORDER BY pd.id ASC; However, it is not clear how you want to run update since more rows would be in original table than above aggregate query. Consider creating a new table from above query: CREATE TABLE new_table AS &lt;above SELECT query&gt; Or better yet keep your original long format which provides more efficient storage, scalability, query maintainability, and referential integrity as nested lists in columns are usually for reporting than table structure. And simply create a view from this query. Views are stored queries for use elsewhere even in application level like Python and can even be queried themselves. CREATE VIEW new_view AS &lt;above SELECT query&gt; SELECT * FROM new_view WHERE prj_id = 1;
score: 1
upvote count: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48065834
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48065834
type: Answer

http://stackoverflow.com/q/48136804
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48522650
score: 2
linked to: http://stackoverflow.com/q/58606438
tagged with: tensorflow
type: Question
has title: tf.Estimator.train throws as_list() is not defined on an unknown TensorShape
has comment: http://stackoverflow.com/comment/99371621
has body: I created a custom input_func and converted a keras model into tf.Estimator for training. However, it keeps throwing me error. Here is my model summary. I have attempted to set the Input layer with batch_shape=(16, 320, 320, 3) for testing but the problem still persits inputs = Input(batch_shape=(16, 320, 320, 3), name='input_images') outputs = yolov2.predict(intputs) model = Model(inputs, outputs) model.compile(optimizer= tf.keras.optimizers.Adam(lr=learning_rate), loss = compute_loss) I used tf.keras.estimator.model_to_estimator for conversion. I also create a input_fn for training: def input_fun(images, labels, batch_size, shuffle=True): dataset = create_tfdataset(images, labels) dataset = dataset.shuffle().batch(batch_size) iterator = dataset.make_one_shot_iterator() images, labels = iterator.next() return {'input_images': images}, labels estimator = tf.keras.estimator.model_to_estimator(keras_model=model) estimator.train(input_fn = lambda: input_fn(images, labels, 32), max_steps = 1000) And it throws me this error input_tensor = Input(tensor=x, name='input_wrapper_for_' + name) ... File "/home/dat/anaconda3/envs/webapp/lib/python2.7/site-packages/tensorflow/python/layers/base.py", line 1309, in __init__ self._batch_input_shape = tuple(input_tensor.get_shape().as_list()) "as_list() is not defined on an unknown TensorShape.") ValueError: as_list() is not defined on an unknown TensorShape.
upvote count: 2
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: keras

http://stackoverflow.com/a/48110317
has body: From Python in a Nutshell: L.acquire() When blocking is True, acquire locks L . If L is already locked, the calling thread suspends and waits until L is unlocked, then locks L . Even if the calling thread was the one that last locked L , it still suspends and waits until another thread releases L . When blocking is False and L is unlocked, acquire locks L and returns True. When blocking is False and L is locked, acquire does not affect L , and returns False. And a practical example using the following simple code: from multiprocessing import Process, Lock, current_process def blocking_testing(lock): if not lock.acquire(False): print('{} Couldn\'t get lock'.format(current_process().ident)) else: print('{} Got lock'.format(current_process().ident)) if __name__ == '__main__': lock = Lock() for i in range(3): procs = [] p = Process(target=blocking_testing, args=(lock,)) procs.append(p) p.start() for p in procs: p.join() With the above version (blocking=False) this outputs 12206 Got lock 12207 Couldn't get lock 12208 Couldn't get lock If I set blocking=True (or remove it, as it defaults to True) the main process will hang, as the Lock is not being released. Finally, if I set blocking=True and add a lock.release() at the end, my output will be 12616 Got lock 12617 Got lock 12618 Got lock I hope this was a clear enough explanation.
answers question: http://stackoverflow.com/q/48109259
accepted answer of: http://stackoverflow.com/q/48109259
score: 9
type: AcceptedAnswer
upvote count: 9
type: Answer
downvote count: 0

http://stackoverflow.com/q/48068306
has comment: http://stackoverflow.com/comment/83112154
has comment: http://stackoverflow.com/comment/83420461
score: 0
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/83110792
has comment: http://stackoverflow.com/comment/83147135
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: ubuntu-17.10
tagged with: matlab
has comment: http://stackoverflow.com/comment/83359919
has title: Segmentation Violation when running MATLAB r2017a with caffe (python script)
has comment: http://stackoverflow.com/comment/83112121
type: Question
has body: I get the following crash when running Matlab r2017a with caffe from python script (selective_search.py from https://github.com/sergeyk/selective_search_ijcv_with_python). I run it with user root on ubuntu 17.10 and CPU mode only!. I also tried to run *.m file with matlab and it works fine. you can see below more details. also you can see below the matlab script parameters (['matlab', '-softwareopengl' atc) root@desktop-home:/home/USERNAME/deepLearning/hed/python# python detect.py /home.USERNAME/Desktop/input.txt /home/USERNAME/Desktop/output.csv CPU mode !!!!!! WARNING: Logging before InitGoogleLogging() is written to STDERR I0102 22:59:10.099709 3052 net.cpp:50] Initializing net from parameters: name: "FCN" input: "data" input_dim: 1 input_dim: 3 ... ... ... I0102 22:59:10.636869 3052 upgrade_proto.cpp:620] Attempting to upgrade input file specified using deprecated V1LayerParameter: /home/USERNAME/deepLearning/hed/examples/hed/5stage-vgg.caffemodel I0102 22:59:10.847916 3052 upgrade_proto.cpp:628] Successfully upgraded file specified using deprecated V1LayerParameter Loading input... selective_search_rcnn({'/home/USERNAME/Desktop/camera_500_X_500.jpg'}, '/tmp/tmphzvr5w.mat') ['matlab', '-softwareopengl', '-nojvm', '-r', "try; selective_search_rcnn({'/home/USERNAME/Desktop/camera_500_X_500.jpg'}, '/tmp/tmphzvr5w.mat'); catch; exit; end; exit"] ['matlab', '-softwareopengl', '-nojvm', '-r', "try; selective_search_rcnn({'/home/USERNAME/Desktop/camera_500_X_500.jpg'}, '/tmp/tmphzvr5w.mat'); catch; exit; end; exit"] /home/USERNAME/deepLearning/hed/python/selective_search_ijcv_with_python No protocol specified ------------------------------------------------------------------------ Segmentation violation detected at Tue Jan 2 22:59:13 2018 ------------------------------------------------------------------------ Configuration: Crash Decoding : Disabled - No sandbox or build area path Crash Mode : continue (default) Current Graphics Driver: Unknown software Current Visual…
tagged with: caffe

xcode
tags question: http://stackoverflow.com/q/48153924
type: Tag
tag name: xcode

http://stackoverflow.com/comment/83024592
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48027341
has text: can you provide a [MCVE](https://stackoverflow.com/help/mcve)?

http://stackoverflow.com/q/48115731
score: 0
has body: In Python 3 and pandas I have a dataframe with full names. My default encoding is utf-8. The names are in the Portuguese language, therefore they have spelling accentuation perfis_deputados.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 513 entries, 0 to 512 Data columns (total 10 columns): data_nascimento 513 non-null object e_mail 513 non-null object link_api 513 non-null object link_foto 513 non-null object nome_completo 513 non-null object nome_eleitoral 513 non-null object partido 513 non-null object sexo 513 non-null object telefone 513 non-null object uf 513 non-null object dtypes: object(10) memory usage: 40.2+ KB The columns "nome_completo" and "nome_eleitoral" have cases like: AELTON JOSÉ DE FREITAS JOÃO ALBERTO FRAGA SILVA ALTINEU CÔRTES I need to compare this dataframe with another - compare the names. But this second dataframe has names without any spelling accent. So the names appear like this, for example AELTON JOSE DE FREITAS JOAO ALBERTO FRAGA SILVA ALTINEU CORTES Please, is there a way to compare ignoring orthographic accenting? Or remove the spelling accent in the column I'm analyzing?
tagged with: pandas
has comment: http://stackoverflow.com/comment/83207790
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/517923
has answer: http://stackoverflow.com/a/48115927
type: AnsweredQuestion
has title: How to compare names with and without orthographic accent in pandas?
tagged with: spelling
duplicate of: http://stackoverflow.com/q/37926248
accepted answer: http://stackoverflow.com/a/48115927
linked to: http://stackoverflow.com/q/37926248
type: Question

http://stackoverflow.com/q/48085644
downvote count: 1
has comment: http://stackoverflow.com/comment/83146317
has answer: http://stackoverflow.com/a/48085818
tagged with: file
type: Question
has answer: http://stackoverflow.com/a/48085822
answer count: 2
upvote count: 0
has title: Python- Reading back usernames and passwords into a program to authenticate
score: -1
tagged with: io
tagged with: simplify
has comment: http://stackoverflow.com/comment/83146293
favorite count: 0
has comment: http://stackoverflow.com/comment/83146351
has body: I am currently writing a program in Python that asks if you have a log in. If no, they proceed to create a username and password. If yes, they log in and their details are checked against a text file. The text file looks like this (Username then password): whitehallj27 EXpass%20 Username2 EXPASSWORD%%% james_27 password1234 I am trying to figure out a way of programming this as simply as possible. It seems to work, but isn't nearly as simple and doesn't really work how I thought it would. Here is the code snippet: logins={} usernames_passwords=open("UsernamesAndPasswords.txt","r") count=0 for line in usernames_passwords: count=count+1 count=count/2 usernames_passwords.close() usernames_passwords=open("UsernamesAndPasswords.txt","r") try: for x in range(count): username=usernames_passwords.readline() password=usernames_passwords.readline() logins[username]=password except TypeError: count=int(count+0.5) for x in range(count): username=usernames_passwords.readline() password=usernames_passwords.readline() logins[username]=password usernames_passwords.close() print(logins) Also, how would I go about authenticating the username and password to check it's correct. Many thanks, James Duxbury
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83146383
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/48097742
has comment: http://stackoverflow.com/comment/83175794
favorite count: 0
has title: geopandas point in polygon
tagged with: pandas
tagged with: geopandas
tagged with: python
has answer: http://stackoverflow.com/a/48105955
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48105955
score: 35
type: Question
tagged with: point-in-polygon
has body: I have a GeoDataFrame of polygons (~30) and a GeoDataFrame of Points (~10k) I'm looking to create 30 new columns (with appropriate polygon names) in my GeoDataFrame of Points with a simple boolean True/False if the point is present in the polygon. As an example, the GeoDataFrame of Polygons is this: id geometry foo POLYGON ((-0.18353,51.51022, -0.18421,51.50767, -0.18253,51.50744, -0.1794,51.50914)) bar POLYGON ((-0.17003,51.50739, -0.16904,51.50604, -0.16488,51.50615, -0.1613,51.5091)) The GeoDataFrame of Points is like this: counter points 1 ((-0.17987,51.50974)) 2 ((-0.16507,51.50925)) Expected output: counter points foo bar 1 ((-0.17987,51.50974)) False False 1 ((-0.16507,51.50925)) False False I can do this manually by: foo = df_poly.loc[df_poly.id=='foo'] df_points['foo'] = df_points['points'].map(lambda x: True if foo.contains(x).any()==True else False But given that I have 30 polygons, I was wondering if there is a better way. Appreciate any help!
upvote count: 35
has comment: http://stackoverflow.com/comment/83174905
downvote count: 0
answer count: 1

http://stackoverflow.com/q/48042281
has comment: http://stackoverflow.com/comment/83055259
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83055289
tagged with: web-scraping
tagged with: python
has comment: http://stackoverflow.com/comment/83055355
has title: Dealing with uneven data
has answer: http://stackoverflow.com/a/48042362
tagged with: selenium
type: Question
has body: How do I deal with page that are bugged so data is not scraped correctly similar to this Though I tried to implement something similar below with no luck as the page is not structured as simply. Any idea how I can cater for unequal data as data becomes uneven at random due to webpage. Desired Azam FC v Mwenge 1.8 https://www.bet365.com.au/#/AC/B1/C1/D13/E104/F16/S1/ Western Sydney Wanderers v Melbourne City 2.87 https://www.bet365.com.au/#/AC/B1/C1/D13/E101/F16/S1/ Sydney FC v Newcastle Jets 1.53 https://www.bet365.com.au/#/AC/B1/C1/D13/E101/F16/S1/ output looks like Azam FC v Mwenge 1.8 https://www.bet365.com.au/#/AC/B1/C1/D13/E104/F16/S1/ Western Sydney Wanderers v Melbourne City 1.53 https://www.bet365.com.au/#/AC/B1/C1/D13/E101/F16/S1/ The 1.53 should not be for Western Sydney but for Sydney FC Script.py import collections import csv import time from selenium import webdriver from selenium.common.exceptions import TimeoutException, NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui import WebDriverWait as wait driver = webdriver.Chrome() driver.set_window_size(1024, 600) driver.maximize_window() driver.get('https://www.bet365.com.au/#/AS/B1/') driver.get('https://www.bet365.com.au/#/AS/B1/') def page_counter(): for x in range(1000): yield x count = page_counter() clickMe = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, ('//div[div/div/text()="Main Lists"]//div[starts-with(@class, "sm-CouponLink_Label") and normalize-space()]')))) coupon_lables = [x.text for x in driver.find_elements_by_xpath('//div[div/div/text()="Main Lists"]//div[starts-with(@class, "sm-CouponLink_Label") and normalize-space()]')] links = dict((next(count) + 1, e) for e in coupon_lables) desc_links = collections.OrderedDict(sorted(links.items(), reverse=True)) for key, label in desc_links.items(): driv…
answer count: 1
linked to: http://stackoverflow.com/q/47922167
score: 0
has comment: http://stackoverflow.com/comment/83063217

http://stackoverflow.com/q/48127363
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83233894
has comment: http://stackoverflow.com/comment/83237209
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83231748
score: 2
answer count: 0
has body: I am using django 2.0. For users I am using the model django.contrib.auth.models.User. I have stored a user with username john in it. I have a Post model which uses a User model as ForeignKey. This is my models.py: from django.db import models from django.contrib.auth.models import User class Post(models.Model): post_content = models.CharField(max_length=140) post_date = models.DateTimeField('post date') post_user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.post_content ...In my views.py I am creating a post with: from django.contrib.models import User Post.objects.create(post_content=post_text, post_date=timezone.now(),post_user=User.objects.get(username='john')) ...In one part of the code. When I run I get this error: FOREIGN KEY constraint failed IntegrityError at / And it points to the line in which I create the user in views.py. Is there a proper way to ForeignKey a user model? Any guidance appreciated. Thank you :-). EDIT:It works after doing a reset to the database because I made an error with migrations. Run you migrations properly friends!
type: Question
has comment: http://stackoverflow.com/comment/83233819
has comment: http://stackoverflow.com/comment/107653054
upvote count: 2
has title: Django User model foreign key failed

http://stackoverflow.com/comment/83192141
type: Comment
type: QuestionComment
has text: @ Dark, this is the result which i was looking, it is working. jezrael i tried that method also, but is giving the same error. thanks for both of you.
comment on: http://stackoverflow.com/q/48108025
score: 0

http://stackoverflow.com/q/48037121
has answer: http://stackoverflow.com/a/48039742
type: Question
tagged with: python
tagged with: tweepy
has comment: http://stackoverflow.com/comment/83047075
score: 0
accepted answer: http://stackoverflow.com/a/48039742
answer count: 1
has comment: http://stackoverflow.com/comment/83045036
has comment: http://stackoverflow.com/comment/83044858
has comment: http://stackoverflow.com/comment/83044420
tagged with: twitter
tagged with: python-2.7
has title: Error with tweepy API posting text with update_status
has body: I am working on a Python based twitter bot using tweepy that uses speedtest-cli and subprocess to get my internet speed and tweet at my ISP every 45 minutes if it is underneath what we pay for, however, I am having a problem. For testing, I made 2 files, both identical in imports and both in Python 2.7 using Python 3 print function. One has a static, set speedtest result as to allow me to test the Tweepy aspect, while the other runs the speedtest and writes it to an identically named variable. The real version is while True: testresraw = subprocess.check_output('speedtest --no-upload', shell=True) #Test speed and get output testresnone,testressplit = testresraw.split('Download: ')#Remove text before the download speed testresint,testresnone = testressplit.split('Mbit/s')#Remove text after download speed float(testresint)#Make sure download speed is a number if testresint&lt;float(10.0): statustext= ('My download speed is currently %d MB/s, which is less than the 10 we pay @CenturyLink for' % (testresint)) api.update_status(status=statustext) time.sleep(2700) else: time.sleep(2700) And the testing version is testresint = 1 if testresint&lt;float(10.0): statustext = ('My download speed is currently %d MB/s, which is less than the 10 we pay @CenturyLink for' % (testresint)) api.update_status(status=statustext) time.sleep(2700) else: time.sleep(2700) Only the testing version works and I can't figure out why. EDIT: I placed some print functions to show me where it was messing up, and as it turns out, it is going to the else statement after judging that testresint is not less than 10, mistakenly. I removed the float before the 10.0 as advised. I still can't figure out what's gone wrong.
tagged with: automated-tests
type: AnsweredQuestion

http://stackoverflow.com/q/48081418
has answer: http://stackoverflow.com/a/48081922
has answer: http://stackoverflow.com/a/48081594
tagged with: matplotlib
type: Question
upvote count: 4
has title: Installing pip to import modules
downvote count: 0
accepted answer: http://stackoverflow.com/a/48081538
score: 4
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/83139209
answer count: 3
possible better answer: http://stackoverflow.com/a/48081922
has answer: http://stackoverflow.com/a/48081538
favorite count: 0
has comment: http://stackoverflow.com/comment/83137271
tagged with: pip
tagged with: python
has body: I am attempting to install matplotlib and scipy to python, and using pip to do so. However when I attempted to install scipy with pip install scipy --myuser I received the message: invalid requirement '--myuser' Previously I had installed numpy using pip with python get-pip.py —myuser and pip install numpy —myuser This worked fine, so I am unsure what the problem is here. This is frustrating as I would like to use python from the terminal rather than from my Windows desktop.
type: AnsweredQuestion

http://stackoverflow.com/comment/83108157
has text: its escaping the quotes found in `Katie_"Appleseed"`, why do you want to prevent this?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48067318

http://stackoverflow.com/comment/83143359
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48081912
has text: The `i` came from a silly mistake before. I changed it to reflect the more accurate code and test case scenario. I call the function later on with ```AdjacencyToASC(edges, 0, edges[0], triangles, "") print(triangles)``` where `triangles` is an empty list.
score: 0

http://stackoverflow.com/comment/83175959
score: 1
has text: What is wrong with `set(lst1) & set(lst2)`. Tat being said, do not answer questions that show zero effort...
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48100420

http://stackoverflow.com/comment/83065352
type: Comment
type: QuestionComment
has text: The original weighted_value function returns 3 values seed, a function and fill value. for simplicity of asking I made it as one value. My approach is a manual construction of data by for looping and when ready convert it to a data frame. 1st find the # of unique values 1st df.col call; then call the weighted function; use it to create a data string; store it in a dict with key as col name and data as the string. repeat for all cols. I have 100+ columns. It is nothing but a string manipulation. The other approach i was thinking was to use SQL procedure.
score: 0
comment on: http://stackoverflow.com/q/48046766

http://stackoverflow.com/q/48073635
has comment: http://stackoverflow.com/comment/88556017
type: AnsweredQuestion
score: 1
has body: I'm currently building a REST API using Flask-RESTful and using Flask-HTTPAuth to protect some of the put and get methods. I want to allow access to these methods based on pre-defined user permissions I have stored in a database. My question is, how can I modify or intercept the results of the function below, so that I can vary access depending on the endpoint/method? After basic authentication clears, I want to be able to check whether the user has the relevant permissions in my database. With Flask-Session this was easy, but here the API is stateless. @auth.verify_password def verify_password(user, password): query_set = models.User.objects(username=user) if query_set: return helpers.verify(password, query_set[0].password) else: return False Thank you very much.
has comment: http://stackoverflow.com/comment/83163161
tagged with: flask-restful
tagged with: flask-httpauth
accepted answer: http://stackoverflow.com/a/48101205
type: Question
has title: Flask-HTTPAuth user access levels
downvote count: 0
tagged with: flask
tagged with: rest
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48101205
upvote count: 1
tagged with: python

http://stackoverflow.com/q/48138479
tagged with: javascript
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/83254431
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/83254743
has comment: http://stackoverflow.com/comment/83254657
has comment: http://stackoverflow.com/comment/83254700
has title: recursively parse json in javascript to retrieve certain keys' values
has comment: http://stackoverflow.com/comment/83255148
answer count: 0
has body: I am new to javascript and every time i try learning it, I just end up in an immense amount of frustration and disgust ! No offense, but this is my opinion or perhaps I am too stupid to not understand how it works at all. I have a simple requirement. I have a pretty deeply nested dictionary (which is what it is called in many backend languages) at hand. To be more specific it is the raw text of a postman collection. The collection itself could have multiple nested directories. Now all I want to do is to be able to parse this dictionary and do something with it recursively. For example, if I had to do the same in python I would do it as simply as : def createRequests(self, dic): total_reqs = 0 headers = {} print type(dic) keys = dic.keys() if 'item' in keys: print "Folder Found. Checking for Indivisual request inside current folder . . \n" self.item_list = dic.get('item') for each_item in self.item_list: self.folder.append(self.createRequests(each_item)) else: print "Found Indivisual request. Appending. . . \n" temp_list = [] temp_list.append(dic) self.requestList.append(temp_list) return self.requestList where dic would be my dictionary that I want to parse. Is there any simple and straight forward way to do the same in Javascript? Let's just say all I want to do is that if I have a text file that has properly formed json data in it and whose contents have been read into dataReadFromFile and then it has been converted into a JSON as : var obj = JSON.parse(dataReadFromFile); is there any simple and easy way to convert this JSON to dictionary or the dataReadFromFile directly into a dictionary such that I can say something like dictioanry.keys() if I wanted a list of the keys in it. Note that the content of the file is not fixed. It may have multiple levels of nesting, which may not be known beforehand.
has comment: http://stackoverflow.com/comment/83254993
type: UnansweredQuestion
type: Question
tagged with: recursion
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/83254589
upvote count: 1
downvote count: 1

modelica
tag name: modelica
tags question: http://stackoverflow.com/q/48155084
type: Tag

http://stackoverflow.com/a/54941438
score: 10
upvote count: 10
downvote count: 0
answers question: http://stackoverflow.com/q/48140193
type: Answer
has body: I kept my flask application name as flask.py. Changing this to flaskfile.py or any other name but not flask alone worked for me Maybe flask is a keyword.
has comment: http://stackoverflow.com/comment/102978866

http://stackoverflow.com/q/48096655
score: 2
has comment: http://stackoverflow.com/comment/83170451
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/83176784
has body: I am running long simulations which involve integration of an ode. Due to the long running times, I decided to generate fallbacks which allow to continue the simulations from a checkpoint. For the ode integration, I decided to pickle the scipy ode solver instance. This approach works for the reentrant solvers 'dopri5' and 'dop853', but fails for 'vode' and 'lsoda'. For my particular problem the 'vode' algo seems the fastest, so I am interested, whether one could circumvent this problem. I would expect that this is possible, because in a restart also only one solver instance is required. Running the following two code snippets demonstrates my problem, check out this gist: initialize.py Starts an integration and persists the ode solver instance via pickling (using dill which can also pickle lambdas). import scipy.integrate import dill # Solve a simple ode up to some time t rhs= lambda t, y: -y ode_solver = scipy.integrate.ode(rhs).set_integrator('vode') ode_solver.set_initial_value(1) ode_solver.integrate(1) print ode_solver.t, ode_solver.y ## Stop solving and persist ode solver to a file file_name='ode_instance.pkl' with open(file_name, "w") as ode_file: dill.dump(ode_solver, ode_file) continue.py Tries to continue the above integration via loading the ode solver. import scipy.integrate import dill ## Restart the ode solver file_name='ode_instance.pkl' with open(file_name, "r") as ode_file: ode_solver = dill.load(ode_file) ode_solver.integrate(2) print ode_solver.t, ode_solver.y Throws Traceback (most recent call last): File "continue.py", line 9, in &lt;module&gt; ode_solver.integrate(2) File "~/Applications/miniconda2/envs/cooperativity/lib/python2.7/site-packages/scipy/integrate/_ode.py", line 408, in integrate self.f_params, self.jac_params) File "~/Applications/miniconda2/envs/cooperativity/lib/python2.7/site-packages/scipy/integrate/_ode.py", line 852, in run self.check_handle() File "~/Applications/miniconda2/envs/cooperativity/lib/python2.7/site-packages/scip…
has comment: http://stackoverflow.com/comment/83177472
has comment: http://stackoverflow.com/comment/83198036
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48141512
has title: Scipy: pickle an ode solver instance
upvote count: 2
type: UnansweredQuestion
tagged with: pickle
tagged with: python
tagged with: ode

http://stackoverflow.com/a/48113496
has body: Use subprocess.Popen instead of os.system. You'll get 3 Popen instances that you can wait on. For example: import subprocess procs = [subprocess.Popen(['python', 'node{}.py'.format(n)]) for n in range(1, 4)] retcodes = [p.wait() for p in procs] If you want separate console windows, like how CMD's start command works, then add the option creationflags=subprocess.CREATE_NEW_CONSOLE to the Popen call (Windows only). If you instead want separate consoles that don't create windows, use creationflags=CREATE_NO_WINDOW (0x08000000). In this case they still have console standard I/O; it's just not rendered to a window.
has comment: http://stackoverflow.com/comment/83203885
accepted answer of: http://stackoverflow.com/q/48112191
answers question: http://stackoverflow.com/q/48112191
has comment: http://stackoverflow.com/comment/83203191
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/102650903
type: AcceptedAnswer
type: Answer
upvote count: 6

http://stackoverflow.com/a/48114834
has body: You have to convert the elements to str, not the list itself. Otherwise you are iterating over individual chars in one long string. The following should do the trick for the initial list of integers: y = [int(x.startswith('1')) for x in map(str, list1)]
has comment: http://stackoverflow.com/comment/83205708
answers question: http://stackoverflow.com/q/48114669
type: Answer
score: 0

http://stackoverflow.com/comment/83251550
has text: No Problem .You solved it on your own :)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48136977

http://stackoverflow.com/a/48088266
accepted answer of: http://stackoverflow.com/q/48088196
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48088196
has body: You can use isin i.e array = np.array([-150,105,250,-520,-1024,-1050]) np.where( ~np.isin(array, np.arange(-1024,0)) , array, 0) array([ 0, 105, 250, 0, 0, -1050])
type: Answer
upvote count: 3
has comment: http://stackoverflow.com/comment/83179943
score: 3

http://stackoverflow.com/comment/83139677
type: Comment
type: QuestionComment
has text: The icon itself is checkable (like a flat button), so there's no need to add anything else.
score: 1
comment on: http://stackoverflow.com/q/48080650

http://stackoverflow.com/comment/83147587
score: 0
has text: Thanks for the comments! I've clarified the question somewhat. The involvement of a binding was for context and not relevant to the solution I am looking for.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48086214

http://stackoverflow.com/q/48049601
has title: error with python saying invalid syntax trying to create list of struct
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48049686
has comment: http://stackoverflow.com/comment/83071048
favorite count: 0
has comment: http://stackoverflow.com/comment/83070916
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/83070867
has comment: http://stackoverflow.com/comment/83071070
tagged with: python
tagged with: computer-vision
tagged with: camera-calibration
accepted answer: http://stackoverflow.com/a/48049686
has body: In key frames in Camera resectioning, I am trying to create a list of points that appears in a frame and then try to create a list containing the corresponding points in the following frames to keep tracking the points along the video to find the K matrix between them. I have the following class to store the points from each frame and to create a list of points for each frame and tracking them along all frames. class PointsCorrespondence: """ Stores the point of a specific index. """ # A point is represented as (coordinate X, coordinate Y) Point = (float, float) # A point with corresponding same point is represented as (coordinates, index of the corresponding point or -1 if there is no corresponding point). PointWithCorrespondence = (Point, int) # Contains the points represented as one list of notable points for each frame. _pointsPerFrame : PointWithCorrespondence def __init__(self, pointsPerFrame : PointWithCorrespondence): self._pointsPerFrame = pointsPerFrame when I try to run this code to store the points inside it, I got the following error: Traceback (most recent call last): File "main.py", line 4, in import pointTracking File "/home/k/Desktop/CV/project/insertc/project12345/pointTracking.py", line 17 _pointsPerFrame : PointWithCorrespondence ^ SyntaxError: invalid syntax actually I don't know why I got that error, and I tried many things to check the python syntax styles. I am using python 3.4
score: 0
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/42002596
downvote count: 1
tagged with: opencv
has comment: http://stackoverflow.com/comment/83070852
has comment: http://stackoverflow.com/comment/83070828

http://stackoverflow.com/comment/83270127
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48143903
has text: Possible duplicate of [Same output in different workers in multiprocessing](https://stackoverflow.com/questions/12915177/same-output-in-different-workers-in-multiprocessing)

http://stackoverflow.com/a/48086591
downvote count: 0
answers question: http://stackoverflow.com/q/48086182
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/83159326
has body: Ok, so this one was slightly more complex as I was using websockets. When a message is sent and persisted to the database we can also do the following within the relevant "consumer" method (really, consumers.py is the websocket equivalent of the views.py file so I should have known this!) The following lines of code worked: client = algoliasearch.Client(settings.ALGOLIA['APPLICATION_ID'], settings.ALGOLIA['API_KEY']) index = client.init_index('Room Index') res = index.partial_update_objects([{"last_activity": naturaltime(datetime.datetime.now()), "objectID": your_object_id]}]) The trick for anyone listening would be to designate the your_object_id from what value of the message is passed in from the client side to the consumer. Don't forget to add: import datetime from django.conf import settings from django.contrib.humanize.templatetags.humanize import naturaltime At the top of the consumers.py file! I also found the python specific incremental updates documentation from Algolia extremely useful: I https://www.algolia.com/doc/tutorials/indexing/synchronization/incremental-updates/ To render the updated time in "real time" - use which ever front-end tool floats your boat, I used jQuery but Vue.js or React.js would work equally well.

http://stackoverflow.com/q/48040685
has title: Calculate cost of variable length output at each timestep
tagged with: machine-learning
upvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48046922
type: Question
score: 1
tagged with: recurrent-neural-network
answer count: 1
tagged with: neural-network
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/35732281
has body: I'm trying to create a text generation neural network using a LSTM cell and Tensorflow. I'm training the network on sentences in time-major format [time_steps, batch_size, input_size] and I want each time step to predict the next word in a sequence. The sequence is padded with empty values up to the time steps and a separate placeholder contains the length of each sequence in the batch. There is a lot of information on the concept of back propagation through time, however I can't find anything regarding the actual implementation in tensorflow for variable length sequence cost calculation. Since the end of the sequence is padded, I'm assuming I don't want to calculate the cost on the padded parts. So I need a way to clip the outputs from the first output to the end of the sequence. Here's the code I currently have: outputs = [] states = [] cost = 0 for i in range(time_steps+1): output, state = cell(X[i], state) z1 = tf.matmul(output, dec_W1) + dec_b1 a1 = tf.nn.sigmoid(z1) z2 = tf.matmul(a1, dec_W2) + dec_b2 a2 = tf.nn.softmax(z2) outputs.append(a2) states.append(state) #== calculate cost cost = cost + tf.nn.softmax_cross_entropy_with_logits(logits=z2, labels=y[i]) optimizer = tf.train.AdamOptimizer(0.001).minimize(cost) This code works without variable length sequences. However if I have padded values added to the end, then it calculates the cost of the padded sections as well which doesn't make much sense. How can I only calculate the cost of the outputs before the sequence length cap?
tagged with: python
accepted answer: http://stackoverflow.com/a/48046922
type: AnsweredQuestion

http://stackoverflow.com/comment/83132151
has text: @Dark there:)!!
type: QuestionComment
comment on: http://stackoverflow.com/q/48079043
score: 0
type: Comment

mysql
tags question: http://stackoverflow.com/q/48146748
tags question: http://stackoverflow.com/q/48081103
tags question: http://stackoverflow.com/q/48149893
tags question: http://stackoverflow.com/q/48170847
tags question: http://stackoverflow.com/q/48091060
tags question: http://stackoverflow.com/q/48103470
tags question: http://stackoverflow.com/q/48131705
tags question: http://stackoverflow.com/q/48015668
tags question: http://stackoverflow.com/q/48065834
tags question: http://stackoverflow.com/q/48017719
tags question: http://stackoverflow.com/q/48054586
tag name: mysql
tags question: http://stackoverflow.com/q/48083587
tags question: http://stackoverflow.com/q/48112125
tags question: http://stackoverflow.com/q/48030970
tags question: http://stackoverflow.com/q/48151137
tags question: http://stackoverflow.com/q/48086283
tags question: http://stackoverflow.com/q/48153473
tags question: http://stackoverflow.com/q/48025907
tags question: http://stackoverflow.com/q/48078136
tags question: http://stackoverflow.com/q/48119528
tags question: http://stackoverflow.com/q/48038472
tags question: http://stackoverflow.com/q/48026265
tags question: http://stackoverflow.com/q/48089244
tags question: http://stackoverflow.com/q/48103402
tags question: http://stackoverflow.com/q/48143727
tags question: http://stackoverflow.com/q/48020008
tags question: http://stackoverflow.com/q/48145283
tags question: http://stackoverflow.com/q/48077287
tags question: http://stackoverflow.com/q/48076288
tags question: http://stackoverflow.com/q/48076096
tags question: http://stackoverflow.com/q/48122906
tags question: http://stackoverflow.com/q/48134780
tags question: http://stackoverflow.com/q/48126859
tags question: http://stackoverflow.com/q/48148354
tags question: http://stackoverflow.com/q/48140157
tags question: http://stackoverflow.com/q/48069745
tags question: http://stackoverflow.com/q/48043853
tags question: http://stackoverflow.com/q/48118224
tags question: http://stackoverflow.com/q/48092750
tags question: http://stackoverflow.com/q/48062763
tags question: http://stackoverflow.com/q/48019765
type: Tag
tags question: http://stackoverflow.com/q/48034645
tags question: http://stackoverflow.com/q/48051206
tags question: http://stackoverflow.com/q/48095807
tags question: http://stackoverflow.com/q/48163430
tags question: http://stackoverflow.com/q/48034002
tags question: http://stackoverflow.com/q/48092212
tags question: http://stackoverflow.com/q/48024806
tags question: http://stackoverflow.com/q/48019927
tags question: http://stackoverflow.com/q/48023567
tags question: http://stackoverflow.com/q/48124011
tags question: http://stackoverflow.com/q/48080581
tags question: http://stackoverflow.com/q/48046440
tags question: http://stackoverflow.com/q/48138209
tags question: http://stackoverflow.com/q/48065353
tags question: http://stackoverflow.com/q/48143870
tags question: http://stackoverflow.com/q/48052576
tags question: http://stackoverflow.com/q/48161984
tags question: http://stackoverflow.com/q/48036153
tags question: http://stackoverflow.com/q/48148776

http://stackoverflow.com/q/48053433
has comment: http://stackoverflow.com/comment/83080471
has comment: http://stackoverflow.com/comment/83079376
tagged with: python
has title: Stock price prediction, choosing amount of time in the future using scikit learn
answer count: 0
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/83079215
has body: I'm trying to use machine learning to predict stock prices. I'm having issues choosing how long out to predict, I want to be able to predict out 100-200 days in the future. It seems like my code is cutting off the last 200 days and adding it's prediction there, instead of adding a additional 200 days of the prediction. For example if I have 1000 days of data I want the 1000 and the 200 0f the prediction, right now it's cutting off the last 200 and making it's prediction there instead. To make my question easier to understand, say I have a data set with integers 1,2,3,4,5,6,7,8,9,10, how do I tell the predict method I want the next 2, 10 or 20 integers in the series? I'm just starting out following a tutorial, and doing a bad job of it, it kind of just says put this here and that there, not much insight on what everything is doing. Not sure if LinearRegression is the best way to do it, would be happy with any insight you can provide, Thank you! import pandas as pd import math`enter code here` import numpy as np from sklearn import preprocessing, cross_validation, svm from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt from matplotlib import style df = pd.read_csv('spyqqqq.csv') df = df'Open','High','Low','Adj Close','Volume' df['label'] = df['Adj Close'].shift(-200) df.dropna(inplace=True) X = np.array(df.drop(['label'],1)) y = np.array(df['label']) X = preprocessing.scale(X) X_lately = X[:-200] X_train, X_text, y_train, y_text = cross_validation.train_test_split(X,y, test_size=0.1) clf = LinearRegression() clf.fit(X_train, y_train) accuracy = clf.score(X_text,y_text) forcast = clf.predict(X_lately) print("accuracy ",accuracy) print("forcast ",forcast) plt.plot(forcast,linestyle='solid',ms=0,color='blue') plt.show()
upvote count: 1
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/83091889
type: UnansweredQuestion

http://stackoverflow.com/q/48061508
has comment: http://stackoverflow.com/comment/83096062
has title: NumPy slicing: All except one array entry
has comment: http://stackoverflow.com/comment/83096019
has comment: http://stackoverflow.com/comment/83095821
has answer: http://stackoverflow.com/a/48063166
favorite count: 0
has body: What is the best way to exclude exact one NumPy array entry from an operation? I have an array x containing n values and want to exclude the i-th entry when I call numpy.prod(x). I know about MaskedArray, but is there another/better way?
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48061719
accepted answer: http://stackoverflow.com/a/48061934
answer count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/83095754
has answer: http://stackoverflow.com/a/48061719
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48061934
upvote count: 3
has answer: http://stackoverflow.com/a/48061704
has comment: http://stackoverflow.com/comment/83095664
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83095625
has answer: http://stackoverflow.com/a/48061585
downvote count: 0
has comment: http://stackoverflow.com/comment/83095995
has comment: http://stackoverflow.com/comment/83095929

http://stackoverflow.com/comment/83256902
has text: Please include your code so we can give you better help.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48139564
score: 1

http://stackoverflow.com/q/48066441
has comment: http://stackoverflow.com/comment/83107689
favorite count: 0
tagged with: memoization
tagged with: python
has comment: http://stackoverflow.com/comment/83106645
has comment: http://stackoverflow.com/comment/83107104
type: AnsweredQuestion
has body: The function to be memoized is not "pure" (its return value may change in the future) so I cannot use the memoize decoration. Moreover, I will need the list of values it was called on. What I do is def f(...): cache = {} for ...: try: x = cache[k] except KeyError: x = cache[k] = expensive(k) # use x here for x in cache.itervalues(): cleanup(x) I wonder if this is the "pythonic" way to express the paradigm. E.g., I can save 3 lines by writing def f(...): cache = {} for ...: x = cache[k] = cache.get(k) or expensive(k) # use x here for x in cache.itervalues(): cleanup(x) Instead (assume that None, 0, "", [], {} and other false values are not possible return values of expensive). Does this look better?
downvote count: 0
has comment: http://stackoverflow.com/comment/83106248
has comment: http://stackoverflow.com/comment/83106232
has title: How to implement temporary function "memoization"?
has answer: http://stackoverflow.com/a/48068245
type: Question
has comment: http://stackoverflow.com/comment/83106290
accepted answer: http://stackoverflow.com/a/48067201
score: 3
possible better answer: http://stackoverflow.com/a/48068245
has comment: http://stackoverflow.com/comment/83106233
has answer: http://stackoverflow.com/a/48067201
tagged with: python-2.7
upvote count: 3
answer count: 2

http://stackoverflow.com/a/48040045
has comment: http://stackoverflow.com/comment/83050584
has comment: http://stackoverflow.com/comment/83050627
answers question: http://stackoverflow.com/q/48040033
type: Answer
has body: Try A = 'A.mpeg' B = 'B.mpeg' C = 'C.mpeg' D = 'D.mpeg' E = 'E.mpeg' F = 'F.mpeg' G = 'G.mpeg' k = [A,B,C,D,E,F,G] for i in range(len(k)): print(i, k[i]) pygame.mixer.music.load(k[i]) pygame.mixer.music.play() time.sleep(0.7) Previously, you were trying to load a file named 'A', which I assume did not exist.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83050578
upvote count: 1

http://stackoverflow.com/q/48144580
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/48144927
answer count: 2
has title: How to launch python in Visual Studio Code with superuser permission or root permission? (i.e. using sudo command)
accepted answer: http://stackoverflow.com/a/48144927
score: 3
downvote count: 0
favorite count: 0
tagged with: sudo
has body: To execute my python program from the command line, I use sudo python myProgram.py because my program requires root privileges. To execute the same from Visual Studio Code IDE, I tried prefixing the pythonPath variable in launch.json file with the sudo command but I get the following error: Error: spawn sudo /usr/local/bin/python3 ENOENT Here is my task configuration { "name": "Python", "type": "python", "request": "launch", "stopOnEntry": true, "pythonPath": "sudo /usr/local/bin/python3", "program": "${file}", "cwd": "${workspaceFolder}", "env": {}, "envFile": "${workspaceFolder}/.env", "debugOptions": [ "RedirectOutput" ] }
tagged with: python
possible better answer: http://stackoverflow.com/a/57124233
has answer: http://stackoverflow.com/a/57124233
type: AnsweredQuestion
upvote count: 3
type: Question

http://stackoverflow.com/comment/83024559
has text: ty Dark. what is the purpose of `p4 = pd.concat([samp], keys=['p4'],axis=1)`? is there no way to combine to the ndf step?
type: AnswerComment
comment on: http://stackoverflow.com/a/48025258
score: 0
type: Comment

http://stackoverflow.com/comment/83186030
type: Comment
type: QuestionComment
has text: @Alasdair - That fixed the issue. Thank you so much.
score: 0
comment on: http://stackoverflow.com/q/48104693

phrase
type: Tag
tag name: phrase
tags question: http://stackoverflow.com/q/48096066

http://stackoverflow.com/comment/83247339
score: 0
comment on: http://stackoverflow.com/a/48135008
type: AnswerComment
has text: what does `s.loc[:, m] = np.nan` do?
type: Comment

http://stackoverflow.com/comment/134228657
has text: For those who would also want to capture infinities, use torch.all(torch.isfinite(tensor))
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48158017
score: 2

http://stackoverflow.com/q/48162390
tagged with: list
type: UnansweredQuestion
tagged with: multiprocessing
type: Question
has body: I'm trying to parse a page using BeautifulSoup. This is the function where the exception is thrown: def get_page_items(url): page = requests.get(url) soup = BeautifulSoup(page.content, 'lxml') name = soup.find(class_="ccpProductDetail__title__text").text.strip() price = soup.find(attrs={"data-price-main" : "price-main"}).text.strip() images_routes_src = soup.find_all(class_="ccpProductDetailSlideshow__slider__wrapper__list__item__image") images_routes = [] try: for image in images_routes_src: images_routes.append(image['src'].strip()) except: pass description_html = soup.find_all(class_="block large") description_html[0].div.decompose() new_tag = soup.new_tag("h3") new_tag.string = 'Hinweise' description_html[2].span.replace_with(new_tag) beschreibung_html = soup.find(class_="block large text") description_html.insert(1, beschreibung_html) item = Item(name, price, images_routes, description_html) return item And this is where the method is called using a pool: for index, page in enumerate(pages_urls): if page is not pages_urls[-len(pages_urls)]: init_BeautifulSoup(pages_urls[index]) get_all_page_item_links() page_items = pool.map(get_page_items, items_urls) total_items.extend(page_items) This is the output: Traceback (most recent call last): File "/Users/rodrigopeniche/Documents/workspace/WebScraping/conrad_scrapping (4).py", line 120, in &lt;module&gt; page_items = pool.map(get_page_items, items_urls) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py", line 251, in map return self.map_async(func, iterable, chunksize).get() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py", line 567, in get raise self._value IndexError: list index out of range I've seen in many other posts that sometimes this happens with multiprocessing, but I've tried calling the function in a for loop and I get this error: Traceback (most recent call last): File "/Users/rodrigopeniche/Documents/…
score: 0
answer count: 1
has title: Why do BeautifulSoup and multiprocessing raise an index out of range in a list?
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48162446
tagged with: python

http://stackoverflow.com/q/48057744
tagged with: h5py
type: UnansweredQuestion
tagged with: python
score: 8
downvote count: 0
upvote count: 8
tagged with: multiprocessing
type: Question
has answer: http://stackoverflow.com/a/48061531
has body: I am trying to write my data (from a single file in hdf5 format) to multiple files, and it works fine when the task is executed in serial. Now I want to improve the efficiency and modify the code using the multiprocessing module, but the output sometimes go wrong. Here's a simplified version of my code. import multiprocessing as mp import numpy as np import math, h5py, time N = 4 # number of processes to use block_size = 300 data_sz = 678 dataFile = 'mydata.h5' # fake some data mydata = np.zeros((data_sz, 1)) for i in range(data_sz): mydata[i, 0] = i+1 h5file = h5py.File(dataFile, 'w') h5file.create_dataset('train', data=mydata) # fire multiple workers pool = mp.Pool(processes=N) total_part = int(math.ceil(1. * data_sz / block_size)) for i in range(total_part): pool.apply_async(data_write_func, args=(dataFile, i, )) pool.close() pool.join() and the data_write_func()'s structure is: def data_write_func(h5file_dir, i, block_size=block_size): hf = h5py.File(h5file_dir) fout = open('data_part_' + str(i), 'w') data_part = hf['train'][block_size*i : min(block_size*(i+1), data_sz)] # np.ndarray for line in data_part: # do some processing, that takes a while... time.sleep(0.01) # then write out.. fout.write(str(line[0]) + '\n') fout.close() when I set N=1, it works well. but when I set N=2 or N=4, the result get messed sometimes(not every time!). e.g. in data_part_1 I expect the output to be: 301, 302, 303, ... But sometimes what I get is 0, 0, 0, ... sometimes I get 379, 380, 381, ... I'm new to the multiprocessing module, and find it tricky. Appreciate it if any suggestions!
has comment: http://stackoverflow.com/comment/83087928
has answer: http://stackoverflow.com/a/48058458
has comment: http://stackoverflow.com/comment/83096808
has title: how do I safely write data from a single hdf5 file to multiple files in parallel in python?
favorite count: 0
has answer: http://stackoverflow.com/a/48062739
answer count: 3

http://stackoverflow.com/a/48024987
score: 2
downvote count: 0
has body: That's because you didn't declare it to be abstract: class Activity(models.Model): name = ... class Meta: abstract = True
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48024926
accepted answer of: http://stackoverflow.com/q/48024926
type: Answer

http://stackoverflow.com/a/48165449
score: 2
upvote count: 2
has body: Do not remove elements from a collection while iterating it. Repeated calls to list.remove are also not ideal performance-wise since each removal (from a random index) is O(N). A simple way around both issues would be the following comprehension: def remove_words(listx): return [remove_words(e) for e in listx if isinstance(e, list)] The seemingly missing base case is a list with no nested lists where an empty list is returned. If you want to modify the list in-place, you can use slice assignment: def remove_words(listx): listx[:] = [remove_words(e) for e in listx if isinstance(e, list)]
downvote count: 0
answers question: http://stackoverflow.com/q/48165235
type: Answer

http://stackoverflow.com/comment/83084884
type: AnswerComment
comment on: http://stackoverflow.com/a/48053581
type: Comment
score: 0
has text: It's working fine thank you. But getting this warning message `<path>/lib/python3.6/site-packages/sklearn/utils/validation.py:578: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel(). y = column_or_1d(y, warn=True)`

http://stackoverflow.com/comment/83142409
score: 0
type: Comment
has text: Be aware that a PDF document does not inherently have a "DPI". That's because a PDF page is not a bitmap. It may _contain_ bitmaps, but many PDF files contain only text and vector graphics that can be rendered at any resolution. If you want to render each PDF document to a sequence of 300 dpi bitmaps, there are libraries that can do that. (Off-topic to ask for libraries on StackOverflow though.) And if you want to change bitmaps to monochrome or bi-level, there are libraries that can do that too. But note! some documents could get _bigger_ as a result.
type: QuestionComment
comment on: http://stackoverflow.com/q/48079656

http://stackoverflow.com/q/48016895
tagged with: python
has body: Using the code below extracts div that contains the number of votes on a website votes = soup.find('div', {'id': 'vote_text_299159'}) &lt;div id="vote_text_247231" class="left action_unclicked_show cursor" style="width:97px;margin-left:3px;" data-counttext="191 votes" data-actiontext="VOTE!" onmouseover="user_action_button_mouseover('vote','247231')" onmouseout="user_action_button_mouseout('vote', '247231')" onclick="loginPrompt(&amp;#x27;vote&amp;#x27;);clickTrack(&amp;quot;photo_vote&amp;quot;);"&gt; Which returns the div shown below the code. How can I extract data-counttext (or other categories) given this return and just using the id?
type: AnsweredQuestion
has title: BeautifulSoup - Given ID how to extract other categories in div?
accepted answer: http://stackoverflow.com/a/48016916
type: Question
possible better answer: http://stackoverflow.com/a/48016959
has answer: http://stackoverflow.com/a/48016916
score: 0
answer count: 3
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48017049
has answer: http://stackoverflow.com/a/48016959
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/83317937
score: 0
comment on: http://stackoverflow.com/q/48169101
type: Comment
type: QuestionComment
has text: Your question asks about sending, not receiving. That's the role of a client in SMTP.

http://stackoverflow.com/a/48147677
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48147323
answers question: http://stackoverflow.com/q/48147323
type: Answer
score: 2
downvote count: 0
has body: tia github page explicitly said that library compatible only with python 2.7. So I guess that is the problem.
upvote count: 2

http://stackoverflow.com/a/48062621
has body: You should extend your PYTHONPATH to the folder where your lxml or html.parser is installed. With this, "python" will know in which specific location to search for your packages. In either case, you are making your own structure of folders with dependencies since there are tools for this such as virtualenv.
answers question: http://stackoverflow.com/q/48054837
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83118425
type: Answer
accepted answer of: http://stackoverflow.com/q/48054837

http://stackoverflow.com/q/48134258
has title: Python module exists in terminal but not when run through PHP's shell_exec
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83245872
has answer: http://stackoverflow.com/a/48135122
accepted answer: http://stackoverflow.com/a/48135122
has answer: http://stackoverflow.com/a/61756663
tagged with: macos
upvote count: 6
favorite count: 0
has body: When i run a python script in terminal it works just fine. I then proceed to run the exact same script via PHP's shell_exec from localhost. shell_exec("python /Applications/MAMP/htdocs/pharm/Webmaps.py") The error it gives is: Traceback (most recent call last): File "/Applications/MAMP/htdocs/pharm/Webmaps.py", line 1, in import folium ImportError: No module named folium It doesn't recognize the modules that are installed. Needless to say that it works just fine from windows on localhost.
has comment: http://stackoverflow.com/comment/83246012
score: 6
tagged with: python
tagged with: php
tagged with: localhost
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/61756663
type: Question

http://stackoverflow.com/comment/83115320
type: Comment
has text: I can't change the functions defined in the library.
comment on: http://stackoverflow.com/a/48070598
score: 0
type: AnswerComment

http://stackoverflow.com/a/48139666
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83257629
has comment: http://stackoverflow.com/comment/83257355
has comment: http://stackoverflow.com/comment/83257300
type: Answer
has comment: http://stackoverflow.com/comment/83257623
score: 2
has body: The mean reason your code fails is because y is a 1D array with shape - X = df.iloc[:, :-1].values y = df.iloc[:, 1].values y.shape (6,) So, calling y[:, 0:1] on a 1D array is an invalid operation - y[:,0:1] IndexError: too many indices for array Instead, what you should've done was initialise y as so - y = df.iloc[:, -1:].values Which would've made y a 2D array with one column, fixing the problem. imputer accepts a 2D array with a single column, and returns a result of similar shape. Slice a single column dataframe, and pass it to imputer.fit_transform, which performs the fitting and transformation in a single step - df['Salary'] = imputer.fit_transform(df'Salary').ravel() df YearsExperience Salary 0 1.1 39343.0 1 1.3 46205.0 2 1.5 37731.0 3 2.0 43525.0 4 2.2 44689.2 5 2.9 56642.0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48139582
has comment: http://stackoverflow.com/comment/83257260
answers question: http://stackoverflow.com/q/48139582

http://stackoverflow.com/comment/83134045
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48079982
has text: in class you can use `self` - `self.firstNameText` and get value directly in method `onConfirm` - `self.firstNameText.get()`. You don't have to set it as parameter.
score: 0

http://stackoverflow.com/a/70293939
has body: This works for hours : hours = [0, 6, 12, 18] df.loc[(df.index.hour.isin(hours)),:]
answers question: http://stackoverflow.com/q/48152584
type: Answer
score: 0

http://stackoverflow.com/comment/83019190
comment on: http://stackoverflow.com/q/48024806
score: 0
has text: Your code snippet seems to use a variable for the table name. Are you getting an error when executing the delete function?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48040542
type: Answer
has body: multiple ways to fix your problem. i guess the fastest way is: &lt;form class="form-newtemp" method="post" action="{{ url_for('process')}}"&gt; and then @app.route('/ChangeTemp', methods=['POST]) def process(): new = request.form['new_sp'] return 'New set point is:' + new or you can go with not changing your template and: @app.route('/ChangeTemp', methods=['GET']) def process(): new = request.args.get('new_sp') return 'New set point is:' + new
answers question: http://stackoverflow.com/q/48040431
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48040431

http://stackoverflow.com/comment/83141988
has text: Cheers Taylor. I am ok with dict and i used the very same structure.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48083156

http://stackoverflow.com/a/48113168
has comment: http://stackoverflow.com/comment/83204783
downvote count: 0
type: Answer
upvote count: 1
has body: From the documentation of the module: Obtain commits at the specified revision repo.commit('master') repo.commit('v0.8.1') repo.commit('HEAD~10') So to retrieve a specific commit just use repo.commit('SHA-1')
score: 1
answers question: http://stackoverflow.com/q/48112931

http://stackoverflow.com/q/48038562
tagged with: scipy
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48038764
answer count: 1
downvote count: 0
has body: I would like to find out optimal parameters like bo,ho,t1 and t2 such that the error function (f) is minimum (i.e., zero or close to zero). Full code is shown below, import numpy import scipy.optimize as optimize #OPTIMISATION USING SCIPY def Obj_func(x): bo,ho,t1,t2=x f=-321226.4817 + (10400000*bo*ho**3 - 10400000*(bo - 2*t2)*(ho - 2*t1)**3)/(125 + (10400000*bo*ho**3 - 10400000*(bo - 2*t2)*(ho - 2*t1)**3)/(1563920*t1*(bo - 2*t2))) return f initial_guess=[2,2,0.2,0.2] cons = ({'type': 'eq', 'fun': lambda bo,ho,t1,t2: (bo*ho - (bo - 2*t2)*(ho - 2*t1)-7.55)}) bnds = ((0, None), (0, None),(0, None), (0, None)) #all four variables are positive and greater than zero #Always t1 and t2 should always be lesser than bo and ho #res=optimize.minimize(Obj_func, method='SLSQP',initial_guess, bounds=bnds,constraints=cons) res=optimize.minimize(Obj_func,initial_guess, bounds=bnds,constraints=cons) print ("Result",res) I am facing some issue here, Q1. lambda function created for cons is giving me an error which states`"TypeError: () missing 3 required positional arguments: 'ho', 't1', and 't2'". Why this is happening? even though i followed the syntax correctly, some thing i am missing. Q2. I need to minimize the objective function i.e., here its minimizing the error function (f) to zero or close to zero. I have mentioned optimize.minimize() without mentioning the type of optimization method. Is it ok? Will it give me the correct answer i am looking for?
tagged with: optimization
accepted answer: http://stackoverflow.com/a/48038764
favorite count: 0
has title: Scipy.optimize.minimize function to determine multiple variables
upvote count: 2
tagged with: python
tagged with: lambda
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/83140676
comment on: http://stackoverflow.com/a/48082967
type: Comment
score: 0
has text: I'm trying to use a different weight for each "class". However, my outputs are real-valued variables. A lot of them are zeros. A. very few of them are say, greater than 10. So, it's a case of imbalance, which I'm trying to cover using weighing. Something like - give lower weight to 0s and higher weight to anything more than zero. Without weighting, I end up predicting zeros!
type: AnswerComment

http://stackoverflow.com/comment/83215545
has text: @EkaterinaPremudraya ah, that means that you don't have the `ENV_URL` key in the `os.environ` dictionary. In other words, the environment variable is not set. By the way, are you sure you need to work with environment variables here at all? In your code that you've shown, you only have the `if not settings.VAR_URL`..could it be that you should "patch" this `settings` object instead? Is it a Django project? Thanks.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48119121

http://stackoverflow.com/comment/86526326
score: 0
comment on: http://stackoverflow.com/q/48018420
type: QuestionComment
type: Comment
has text: what he means is that the IDE is of no help if there are no classes created by the protoc compiler. While they are generated for Java and others, Python users have to suffer through useless runtime-level stuff.

http://stackoverflow.com/a/48146629
has comment: http://stackoverflow.com/comment/83275359
answers question: http://stackoverflow.com/q/48146408
has comment: http://stackoverflow.com/comment/83302305
has comment: http://stackoverflow.com/comment/83271449
score: 0
type: Answer
has body: I think that this post: Embedding text file into excel using Python answers the first part of your question. Concerning your path issue, you could try to use relative paths or environment variable (on Windows, you can rely on HOMEPATH). Regards.

http://stackoverflow.com/a/48105608
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/83221617
has body: Your question seems to boil down to what data to pass to the flask server. There is also another issue about what you do with that data (you're only returning the last one), but you did not ask about that. Send this as the request body. It uses list notation which is valid JSON. Your flask server can then access the list by decoding the JSON request. {"entryInfo": [[21, "denied"], [44, "Try Again"], [31, "Retry"]]} A better way though might be to use a dictionary mapping entry codes to pass codes: {"entryInfo": {"21": "denied", "44": "Try Again", "31": "Retry"}} and it's debatable whether the top-level dict is required, you could get away with: {"21": "denied", "44": "Try Again", "31": "Retry"}
accepted answer of: http://stackoverflow.com/q/48105503
has comment: http://stackoverflow.com/comment/83214485
score: 0
answers question: http://stackoverflow.com/q/48105503

http://stackoverflow.com/q/48117508
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17388213
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48118815
has answer: http://stackoverflow.com/a/48117886
has comment: http://stackoverflow.com/comment/83211480
has title: How to find a similar substring inside a large string with a similarity score in python?
accepted answer: http://stackoverflow.com/a/48117886
has body: What I'm looking for is not just a plain similarity score between two texts. But a similarity score of a substring inside a string. Say: text1 = 'cat is sleeping on the mat'. text2 = 'The cat is sleeping on the red mat in the living room'. In the above example, all the words of text1 are present in the text2 completely, hence the similarity should be 100%. If some words of text1 are missing, the score shall be less. I'm working with a large dataset of varying paragraph size, hence finding a smaller paragraph inside a bigger one with such similarity score is crucial. I found only string similarities such as cosine similarities, difflib similarity etc. which compares two strings. But not about a score of substring inside another string.
upvote count: 6
has comment: http://stackoverflow.com/comment/83212133
has comment: http://stackoverflow.com/comment/83214995
has answer: http://stackoverflow.com/a/48118207
linked to: http://stackoverflow.com/q/15173225
tagged with: distance
score: 5
has comment: http://stackoverflow.com/comment/83235965
has comment: http://stackoverflow.com/comment/83235974
tagged with: string
favorite count: 0
possible better answer: http://stackoverflow.com/a/48118815
tagged with: similarity
has answer: http://stackoverflow.com/a/76840005
tagged with: python
tagged with: nlp
answer count: 4

http://stackoverflow.com/q/48131551
has body: I have dates in mm/dd/yyyy format as well as mm/yyyy formats in my text file. How do I search dates which are mm/yyyy without showing the results from mm/dd/yyyy format. I have following 2 scenarios line starting with mm/yyyy - '^\d{1,2}/\d{4}' (No problem here) Problem arises when date in the middle or end of the line. I have dates with special characters and alphabets before them. So dates such as ~09/2009 are also required but get rejected if I search as ' \d{1,2}/\d{4}'. To avoid this I need an expression such that the date mm/yyyy doesn't follow a forward slash. but for some reason '[^/]\d{1,2}/\d{4}' isn't working. It shows dates like 01/03/2010 as 03/2010. Here's a snippet from ipython import re text1 = 'Appointment is on 10/06/2009. Next appointment in 07/2009' re.findall('[^\/](\d{1,2}/\d{4})',text1) Out: ['6/2009', '07/2009'] Krishna
score: 0
has comment: http://stackoverflow.com/comment/83240443
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48131868
upvote count: 1
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83240270
has comment: http://stackoverflow.com/comment/83240393
type: AnsweredQuestion
tagged with: date
downvote count: 1
has comment: http://stackoverflow.com/comment/83240196
type: Question
accepted answer: http://stackoverflow.com/a/48131868
has title: Searching dates in mm/yyyy format

http://stackoverflow.com/a/48051451
score: 10
answers question: http://stackoverflow.com/q/48049498
type: Answer
upvote count: 10
has comment: http://stackoverflow.com/comment/139738004
has comment: http://stackoverflow.com/comment/83075444
accepted answer of: http://stackoverflow.com/q/48049498
type: AcceptedAnswer
downvote count: 0
has body: You don't need to define fields unders widgets. Define them as static at class level. class SignUpForm(UserCreationForm): username = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'})) first_name = forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'First Name'}), max_length=32, help_text='First name') last_name=forms.CharField(forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Last Name'}), max_length=32, help_text='Last name') email=forms.EmailField(forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email'}), max_length=64, help_text='Enter a valid email address') password1=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password'})) password2=forms.CharField(forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Password Again'})) class Meta(UserCreationForm.Meta): model = User # I've tried both of these 'fields' declaration, result is the same # fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) fields = UserCreationForm.Meta.fields + ('first_name', 'last_name', 'email',)

http://stackoverflow.com/a/48096153
downvote count: 0
has comment: http://stackoverflow.com/comment/83167791
has comment: http://stackoverflow.com/comment/83168440
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48095508
has body: Here is a generator approach using itertools.product to get the indices for placing the line. itertools.product is often useful to replace nested loops of variable depth: import numpy as np import itertools def lines(n, k): for axis in range(n): ranges = ((slice(None),) if a==axis else range(k) for a in range(n)) for idx in itertools.product(*ranges): ret = np.zeros(n*(k,), dtype=int) ret[idx] = 1 yield ret for line in lines(2, 3): print(line)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48095508

http://stackoverflow.com/q/48140103
has comment: http://stackoverflow.com/comment/84270806
possible better answer: http://stackoverflow.com/a/62831784
has answer: http://stackoverflow.com/a/62831784
answer count: 2
tagged with: odoo-10
downvote count: 0
accepted answer: http://stackoverflow.com/a/48148198
favorite count: 0
upvote count: 2
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
score: 2
type: AnsweredQuestion
has body: When a sales order is created from User A which has User B as account manager, the following email is sent: Dear User B, You have been assigned to the sales order SO-0058. &lt;View sales order&gt; Powered by Odoo. Similar email is sent when an invoice is created. Where this template can be modified? Is there any way to disable this internal notifications globaly?
has answer: http://stackoverflow.com/a/48148198
type: Question
has title: Odoo 10 - Email notifications when Sales Order or Invoices are created
tagged with: odoo

http://stackoverflow.com/comment/83205232
comment on: http://stackoverflow.com/a/48102500
score: 0
type: AnswerComment
type: Comment
has text: Works great and is much faster even when I use very large values for N

http://stackoverflow.com/a/48054015
downvote count: 0
answers question: http://stackoverflow.com/q/48053960
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/83080827
has body: you can use list comprehension: final = (1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15) ar = [] ar = [final[i:i + 3] for i in range(0, len(final), 3)] print(ar) output: [(1, 2, 3), (4, 5, 7), (8, 9, 10), (11, 12, 13), (14, 15)]

oop
tags question: http://stackoverflow.com/q/48045155
tags question: http://stackoverflow.com/q/48128586
tags question: http://stackoverflow.com/q/48129617
tags question: http://stackoverflow.com/q/48082893
tags question: http://stackoverflow.com/q/48078177
tags question: http://stackoverflow.com/q/48118711
tag name: oop
tags question: http://stackoverflow.com/q/48068700
tags question: http://stackoverflow.com/q/48103889
tags question: http://stackoverflow.com/q/48160482
tags question: http://stackoverflow.com/q/48143749
tags question: http://stackoverflow.com/q/48048095
tags question: http://stackoverflow.com/q/48144150
tags question: http://stackoverflow.com/q/48159459
tags question: http://stackoverflow.com/q/48036717
tags question: http://stackoverflow.com/q/48016665
tags question: http://stackoverflow.com/q/48159155
tags question: http://stackoverflow.com/q/48127540
tags question: http://stackoverflow.com/q/48039116
tags question: http://stackoverflow.com/q/48116380
tags question: http://stackoverflow.com/q/48053797
tags question: http://stackoverflow.com/q/48039361
tags question: http://stackoverflow.com/q/48068230
tags question: http://stackoverflow.com/q/48046028
tags question: http://stackoverflow.com/q/48070833
type: Tag
tags question: http://stackoverflow.com/q/48083081
tags question: http://stackoverflow.com/q/48032262

http://stackoverflow.com/comment/83282225
has text: Please read [mcve].
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48060986

http://stackoverflow.com/a/48038451
upvote count: 1
has comment: http://stackoverflow.com/comment/83123073
has comment: http://stackoverflow.com/comment/83157370
has body: Add pygame.event.pump() in the inner while loop (and maybe in the main loop as well) or the program will "freeze" because the events are not handled. while continuer: pygame.mixer.music.play() while pygame.mixer.music.get_busy(): pygame.event.pump() pygame.time.Clock().tick(10)
answers question: http://stackoverflow.com/q/48037634
has comment: http://stackoverflow.com/comment/83146852
has comment: http://stackoverflow.com/comment/83158271
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48037634
type: Answer
score: 1

http://stackoverflow.com/q/48162428
has comment: http://stackoverflow.com/comment/83306324
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83306515
has title: Python is creating Data files rather than ASCII while using file handler with a+
type: Question
has comment: http://stackoverflow.com/comment/83327361
has comment: http://stackoverflow.com/comment/83305802
tagged with: python
has comment: http://stackoverflow.com/comment/83310396
has body: I am dumping all the output of pexpect module in a file. I am using below code to that def __init__(self, telnet_switch_ip, telnet_port): stringtosend = "telnet " + telnet_switch_ip + " " + telnet_port fileName = telnet_switch_ip + "_" + telnet_port + "_" + "_station." self.child = pexpect.spawn(stringtosend,maxread=8000) path1 = os.path.join(self.files[0], fileName) mylog = open(path1, 'a+') self.child.logfile = mylog It is creating files likes this in ubuntu 172.31.240.31_2009__station.: ASCII text, with CRLF, CR, LF line terminators 172.31.240.31_2010__station.: ASCII text, with CRLF, LF line terminators This is expected 172.31.240.31_2009__station.: data 172.31.240.31_2010__station.: ASCII text, with CRLF, LF line terminators Why I am getting sometimes data file. problem is that I am not able to open such files in mozilla firefox. Any idea why sometimes I am getting data file

http://stackoverflow.com/q/48029707
has comment: http://stackoverflow.com/comment/83125714
answer count: 0
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83125800
downvote count: 0
has body: I have a 1 GB CSV file like this (16-char-max-string;int) hello;1798732 you;1762 ... that is slow to be parsed into a dict, that's why I would like to do it once, save it as pickled file (or any other serialization method), and then reopen this already-processed file for further use. I tried: import csv, time import cPickle as pickle d = dict() start = time.time() with open('mycsv.csv', mode='r') as f: reader = csv.reader(f, delimiter=';') for r in reader: d[r[0]] = int(r[1]) print time.time() - start with open('mydict', 'wb') as f: pickle.dump(d, f) but it doesn't really work: I'm using Python 64 bit to do it, but I see memory usage during the process explodes to more than 4 GB! (and then more, and it nearly crashed my computer). How to parse this CSV file into a serialized dict in a more RAM-economic way?
has comment: http://stackoverflow.com/comment/83126345
has comment: http://stackoverflow.com/comment/83029656
favorite count: 0
tagged with: serialization
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: pickle
tagged with: python
tagged with: dictionary
has title: Big CSV to pickled dict
has comment: http://stackoverflow.com/comment/83029857

http://stackoverflow.com/comment/83128293
type: QuestionComment
has text: That’s what I wanted to know since it wasn’t clear from the question how it should behave for an element count other than 2…
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48076908

http://stackoverflow.com/a/48089176
has body: This gives the correct output: data = [ele.text for ele in soup.find_all('span', {'class':'NormalTextrun'})] print(data) Output: [' Data 1 ', ' Data 2 ', ' Data 3 ']
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48089010
score: 1

http://stackoverflow.com/a/48161161
has body: I think this is what you want: test = np.array(list(itertools.combinations(range(10),3))) mask = (test.sum(axis=1) == 10) &amp; (test.all(axis=1)) test[mask] For extra safety / readability, you may want to use (test != 0).all(axis=1) instead of test.all(axis=1).
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48161132
type: Answer
has comment: http://stackoverflow.com/comment/83302132
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83302198
accepted answer of: http://stackoverflow.com/q/48161132
has comment: http://stackoverflow.com/comment/83302161
has comment: http://stackoverflow.com/comment/83301887

http://stackoverflow.com/q/48047349
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48049337
has answer: http://stackoverflow.com/a/48050584
tagged with: smtplib
has body: I am using following code: def mailme(): print('connecting') server = smtplib.SMTP('mail.server.com', 26) server.connect("mail.server.com", 465) print('connected..') server.ehlo() server.starttls() server.ehlo() server.login('scraper@server.com', "pwd") text = 'TEST 123' server.sendmail('me@sserver.com', 'me@server2.com', text) server.quit() but it gives error: raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed When connect via Telnet it works: ~ telnet mail.zoo00ooz.com 26 Trying 1.2.3.4... Connected to server.com. Escape character is '^]'. 220-sh97.surpasshosting.com ESMTP Exim 4.87 #1 Mon, 01 Jan 2018 00:23:02 -0500 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail. ^C^C
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83067251
has title: Smtplib: Connection unexpectedly closed
score: 0
has comment: http://stackoverflow.com/comment/83069686

http://stackoverflow.com/comment/83190221
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48097514
has text: I don't know how to install the python console in spyder...
score: 0

http://stackoverflow.com/comment/83026996
type: QuestionComment
has text: Cool, could you update your question then, please?
score: 1
comment on: http://stackoverflow.com/q/48028416
type: Comment

http://stackoverflow.com/comment/83074503
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48049201
type: Comment
has text: @RolandSmith: 1:0 for you, here :)

http://stackoverflow.com/comment/83034817
comment on: http://stackoverflow.com/a/48032331
type: AnswerComment
score: 0
type: Comment
has text: Yes. I noted this. But my question revolves around why self.message is not working in my question [ without using a seperate function as you just provided].

http://stackoverflow.com/q/48037509
has comment: http://stackoverflow.com/comment/84511491
has comment: http://stackoverflow.com/comment/83045448
has comment: http://stackoverflow.com/comment/83056272
has comment: http://stackoverflow.com/comment/84494988
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/83055582
has body: I have imported a data set for a Machine Learning project. I need each "Neuron" in my first input layer to contain one numerical piece of data. However, I have been unable to do this. Here is my code: import math import numpy as np import pandas as pd; v = pd.read_csv('atestred.csv', error_bad_lines=False).values rw = 1 print(v) for x in range(0,10): rw += 1 s = (v[rw]) list(s) #s is one row of the dataset print(s)#Just a debug. myvar = s class l1neuron(object): def gi(): for n in range(0, len(s)): x = (s[n]) print(x)#Just another debug n11 = l1neuron n11.gi() What I would ideally like is a variant of this where the code creates a new variable for every new row it extracts from the data(what I try to do in the first loop) and a new variable for every piece of data extracted from each row (what I try to do in the class and second loop). If I have been completely missing the point with my code then feel free to point me in the right direction for a complete re-write. Here are the first few rows of my dataset: fixed acidity;"volatile acidity";"citric acid";"residual sugar";"chlorides";"free sulfur dioxide";"total sulfur dioxide";"density";"pH";"sulphates";"alcohol";"quality" 7.4;0.7;0;1.9;0.076;11;34;0.9978;3.51;0.56;9.4;5 7.8;0.88;0;2.6;0.098;25;67;0.9968;3.2;0.68;9.8;5 7.8;0.76;0.04;2.3;0.092;15;54;0.997;3.26;0.65;9.8;5 Thanks in advance.
has title: Data separation for ML
has comment: http://stackoverflow.com/comment/83050531
has comment: http://stackoverflow.com/comment/84511722
linked to: http://stackoverflow.com/q/2970608
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48794525
has comment: http://stackoverflow.com/comment/84495094
has comment: http://stackoverflow.com/comment/84501768
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84495125
has comment: http://stackoverflow.com/comment/84500345
has comment: http://stackoverflow.com/comment/84501281
has comment: http://stackoverflow.com/comment/84689249
downvote count: 2
upvote count: 7
has comment: http://stackoverflow.com/comment/84497777
has answer: http://stackoverflow.com/a/48839505
has comment: http://stackoverflow.com/comment/84494724
type: Question
tagged with: numpy
score: 5

http://stackoverflow.com/q/48121389
has body: I'm trying to define 'hard' limits to the return values of Scipy's odeint function but am unsure if function allows for such. I've modified this example from Scipy Cookbook so that the coupled two bodied system could collide. Image Link Graph Collision Imaginary Stop Specifically, the spring constant and mass have been changed to be weaker and lighter. You'll also notice the 'if' statement used inside the function trying to limit the travel of 'm1' no further than the initial input of 'x2'. Sorry, I don't have enough reputation points to post the graphs, but you'll clearly see the two masses can occupy the same space during portions of the solution. # Use ODEINT to solve the differential equations defined by the vector field from scipy.integrate import odeint import matplotlib.pyplot as plt import numpy as np def vectorfield(w, t, p): """ Defines the differential equations for the coupled spring-mass system. Arguments: w : vector of the state variables: w = [x1,y1,x2,y2] t : time p : vector of the parameters: p = [m1,m2,k1,k2,L1,L2,b1,b2] """ x1, y1, x2, y2 = w m1, m2, k1, k2, L1, L2, b1, b2 = p # Create f = (x1',y1',x2',y2'): f = [y1, (-b1 * y1 - k1 * (x1 - L1) + k2 * (x2 - x1 - L2)) / m1, y2, (-b2 * y2 - k2 * (x2 - x1 - L2)) / m2] if y1 &gt; x2: y1 == x2 else: y1 == y1 return f # Parameter values # Masses: m1 = 0.5 m2 = 1.5 # Spring constants k1 = 0.1 k2 = 40.0 # Natural lengths L1 = 0.5 L2 = 1.0 # Friction coefficients b1 = 0.8 b2 = 0.5 # Initial conditions # x1 and x2 are the initial displacements; y1 and y2 are the initial velocities x1 = 0.5 y1 = 0.0 x2 = 4.25 y2 = 0.0 # ODE solver parameters abserr = 1.0e-8 relerr = 1.0e-6 stoptime = 5.0 numpoints = 2500 # Create the time samples for the output of the ODE solver. # I use a large number of points, only because I want to make # a plot of the solution that looks nice. t = [stoptime * float(i) / (numpoints - 1) for i in range(numpoints)] # Pack up the parameters and initial conditions: p = [m1, m2, k1, k2, L1, L2…
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/83295788
upvote count: 1
has comment: http://stackoverflow.com/comment/83293118
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83293877
tagged with: odeint
tagged with: python
has comment: http://stackoverflow.com/comment/83279078
has title: Limit the output of ODEINT Python
downvote count: 0
score: 1

http://stackoverflow.com/comment/83347207
comment on: http://stackoverflow.com/a/48167138
has text: https://stackoverflow.com/q/48183771/2660342 Here's link of new question, didn't update this one because of confusion..
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48080567
has body: My dataframe has a month column with values that repeat as Apr, Apr.1, Apr.2 etc. because there is no year column. I added a year column based on the month value using a for loop as shown below, but I'd like to find a more efficient way to do this: Products['Year'] = '2015' for i in range(0, len(Products.Month)): if '.1' in Products['Month'][i]: Products['Year'][i] = '2016' elif '.2' in Products['Month'][i]: Products['Year'][i] = '2017'
type: Question
answer count: 2
has title: Map dataframe column value by another column's value
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48080860
has comment: http://stackoverflow.com/comment/83135587
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48081080
tagged with: python
tagged with: performance

http://stackoverflow.com/comment/83186394
type: AnswerComment
type: Comment
has text: @TerryA `s[::-1].translate(tr)` then
comment on: http://stackoverflow.com/a/48105353
score: 0

http://stackoverflow.com/comment/83144037
type: QuestionComment
comment on: http://stackoverflow.com/q/48079656
has text: Thanks. Do you know how to read a PDF then save it again in black and white?
type: Comment
score: 0

http://stackoverflow.com/q/48084973
accepted answer: http://stackoverflow.com/a/48085045
has comment: http://stackoverflow.com/comment/83145868
tagged with: python
has answer: http://stackoverflow.com/a/48085172
has comment: http://stackoverflow.com/comment/83144875
favorite count: 0
score: 4
answer count: 2
has body: Quick question, I was coding a small program in Python and was looking for a way to make a condition to only allow the input of 4 numbers if that input has the same len that I want and to make sure that all the numbers in it are unique. After searching for a bit on the web I found several people giving the same solution, it was len(set(input)) == size (size of my number) in my case. It works well, but I fail to understand how it really works and I want to know. I've also tried removing the len from that and it worked anyway so I have little clue what are the effects of each thing in this small piece of code. So even though it allows me to create a condition that makes sure each of the 4 numbers are unique I would love it if someone could explain to me how it works. Thanks in advance. PS: If anyone wonders what it is I'm practicing by making my own version of Cows &amp; Bulls. So given a random number using random.sample the user then has to try to guess what the number is. The conditions I mentioned were used upon the user's input.
upvote count: 4
has comment: http://stackoverflow.com/comment/83145003
downvote count: 0
has answer: http://stackoverflow.com/a/48085045
has title: Explanation for len(set())
type: Question
has comment: http://stackoverflow.com/comment/83144965
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48085172

http://stackoverflow.com/comment/83177436
type: Comment
has text: So you want to have your own source of data and make predictions on it using the trained model?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48071820

http://stackoverflow.com/comment/83032352
comment on: http://stackoverflow.com/q/48031020
type: Comment
score: 0
has text: It was part of the problem statement. I needed to check the first 76 digits.
type: QuestionComment

http://stackoverflow.com/q/48089571
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48089631
accepted answer: http://stackoverflow.com/a/48089631
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
type: Question
score: 0
has title: Redirecting user to profile after sign up
upvote count: 1
has body: I am overriding the sign up view in allauth by using my own. I can sign up and the user will be logged in, but I'd like to redirect the user to their profile page. I have an app called profiles that has a view called Index in the profiles.urls Index can take in 2 parameters, a slug (username) or a pk (id). After the user hits the sign up button and everything is valid, I want to redirect them to their profile page: /profiles/{their username} profiles.urls app_name = 'profiles' urlpatterns = [ url(r'^(?P&lt;pk&gt;\d+)/$', views.Index.as_view(), name='Index'), url(r'^(?P&lt;slug&gt;[\w_]+)/$', views.Index.as_view(), name='Index'), ] oauth.views class RegisterView(SignupView): form_class = RegisterForm template_name = 'oauth/auth_form.html' def form_valid(self, form): return redirect('profiles:Index', slug=form.username) oauth.views is where I make my custom SignupView. Now when I try to sign up, I don't get redirected to the user's profile. Instead I get this error: File "C:\python3.6.3\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\python3.6.3\lib\site-packages\allauth\account\views.py", line 102, in post response = self.form_valid(form) File "C:\Users\xx\PycharmProjects\examplesite\oauth\views.py", line 17, in form_valid return redirect('profiles:Index', slug=form.username) AttributeError: 'RegisterForm' object has no attribute 'username' How do I make it so that the user is redirected to their profile based on the username they selected?

http://stackoverflow.com/q/48066774
tagged with: nlp
has comment: http://stackoverflow.com/comment/83205747
favorite count: 0
has body: I'm looking to check the caption(text below each image) on a wikipedia article. I wish to parse those strings (mostly using regex) and then if it matches, I want to save the link of that image. I've been importing wikipedia directly to parse text, but after looking around the net I saw I'd need a different kind of parser for that. I tried using mwparserfromhell and pywikibot, but I couldn't resolve the pywikibot errors for me and just mwparserfromhell gives me empty results. Any help in doing the above, without using DBPpedia?
upvote count: 2
type: UnansweredQuestion
tagged with: wikipedia
tagged with: text
score: 2
has comment: http://stackoverflow.com/comment/104011989
type: Question
has title: Caption of images on wikipedia pages
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/58883000
tagged with: python

http://stackoverflow.com/a/48077601
score: 2
answers question: http://stackoverflow.com/q/48077287
has body: If you are not sure about the exception raised, you can call for generic exception information from system. Example: import sys .... try: # whatever code you want ... pass except OSError as err: # when you know and expect specific error # decide what you want to perform pass except ValueError: # when you know and expect specific error # decide what you want to perform pass except: # unhandled exceptions print("Unexpected error:", sys.exc_info()[0]) raise Database errors too have named exceptions. Relevant errors can be assumed expected and raised. Refer to documentation: Errors and Exceptions
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48077287
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/q/48027375
has comment: http://stackoverflow.com/comment/83024602
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/2612802
has comment: http://stackoverflow.com/comment/83024606
downvote count: 0
has comment: http://stackoverflow.com/comment/83025105
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48027425
has comment: http://stackoverflow.com/comment/83024886
has comment: http://stackoverflow.com/comment/83024504
linked to: http://stackoverflow.com/q/13299427
has answer: http://stackoverflow.com/a/48027531
upvote count: 2
duplicate of: http://stackoverflow.com/q/13299427
has comment: http://stackoverflow.com/comment/83024617
answer count: 2
has title: Variable scope with function
has body: Trying to understand variable scope with a function call. Code to discuss. import numpy as np import pandas as pd # Function to add a column with random stuff to a dataframe def Add_a_column(df): df['Col2']= np.sign(np.random.randn(len(df))) return df # Create a dataframe with random stuff df_full = pd.DataFrame(data=np.sign(np.random.randn(5)), columns=['Col1']) df_another = Add_a_column(df_full) df_full is global. Correct? df_another is global. Correct? df is local to Add_a_column. Correct? When I execute the code, the column get's added to df_full In[8]: df_full Out[8]: Col1 Col2 0 -1.0 -1.0 1 1.0 -1.0 2 -1.0 1.0 3 1.0 1.0 4 1.0 1.0 How do I avoid df_full being modified by the function?
favorite count: 0
tagged with: scope

geography
type: Tag
tag name: geography
tags question: http://stackoverflow.com/q/48133914

http://stackoverflow.com/a/59061470
upvote count: 1
has body: I was experiencing the same problem as you had. I used Sqlite and Pycharm Editor, I fixed the problem by refresh the database I use in Pycharm (View -> Tool Windows -> Database -> Refresh). I know the success rate is low but I hope this helps somebody experienced the same problem.
answers question: http://stackoverflow.com/q/48143659
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/83298834
type: AnswerComment
comment on: http://stackoverflow.com/a/48159476
has text: in the Python shell, you'd import the required objects, then the code for user in User.objects.all(): SCUser.objects.get_or_create(user=user)
type: Comment
score: 0

http://stackoverflow.com/a/49040299
answers question: http://stackoverflow.com/q/48037640
type: Answer
upvote count: 3
has body: I solved this error by doing: sudo pip install -U wxpython
score: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48037640

http://stackoverflow.com/comment/83298493
score: 2
comment on: http://stackoverflow.com/q/48159459
has text: That's not how it works. You must instantiate `EdgeAclControl` instead.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48146211
has comment: http://stackoverflow.com/comment/83272519
has comment: http://stackoverflow.com/comment/83274645
upvote count: 2
has comment: http://stackoverflow.com/comment/83274597
has comment: http://stackoverflow.com/comment/83287039
has body: The models used for sentiment analysis are generally the result of a machine-learning process. You can produce your own model by running the model creation on a training set where the sentiments are tagged the way you like, but this is a significant undertaking, especially if you are unfamiliar with the underpinnings. For a quick and dirty fix, maybe just make your code override the sentiment for an individual word, or (somewhat more challenging) figure out how to change its value in the existing model. Though if you can get a hold of the corpus the NLTK maintainers trained their sentiment analysis on and can modify it, that's probably much simpler than figuring out how to change an existing model. If you have a corpus of your own with sentiments for all the words you care about, even better. In general usage, "quick" is not superficially a polarized word -- indeed, "quick and dirty" is often vaguely bad, and a "quick assessment" is worse than a thorough one; while of course in your specific context, a service which delivers quickly will dominantly be a positive thing. There will probably be other words which have a specific polarity in your domain, even though they cannot be assigned a generalized polarity, and vice versa -- some words with a polarity in general usage will be neutral in your domain. Thus, training your own model may well be worth the effort, especially if you are exploring utterances in a very specific register.
downvote count: 0
has comment: http://stackoverflow.com/comment/83272396
answers question: http://stackoverflow.com/q/48145777
type: Answer
score: 2

http://stackoverflow.com/comment/83259739
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48140574
has text: The bug is involving a system log-in: clients are not able to log into a system, and I'm attempting to identify where the log in reasoning might go wrong. In general, I've been told SO is not the place to be posting specific bug instances asking for debug help, so I have refrained from doing so here.

http://stackoverflow.com/comment/83253194
score: 0
type: Comment
has text: zip will skip the last element from one the list here
comment on: http://stackoverflow.com/a/48137950
type: AnswerComment

http://stackoverflow.com/comment/83056865
type: QuestionComment
comment on: http://stackoverflow.com/q/48043009
has text: @RoadRunner exactly, initial list is constant.
score: 0
type: Comment

http://stackoverflow.com/q/48156392
tagged with: python-2.7
has body: The standard way to sort a list a based on list b, is to zip them together and use sorted, like sorted(zip(b,a)) However, if two elements in b are equal, it will automatically proceed to try to sort according to a, and that sometimes causes problems. Consider for example import numpy as np a=[np.array([4,5]),np.array([3,4])] b=[1,1] e=zip(b,a) sorted(e) this causes the error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() So when two elements in b are equal, it seems to proceed to sort according to a, but since a contains numpy arrays, the sorting algorithm complain when it tries to compare them. Anyway, is this expected behaviour of sorted? In any case, I just want to sort according to b. If two elements are equal, the order does not matter. Any ideas on how to fix this without writing a sorting algorithm myself?
tagged with: python
accepted answer: http://stackoverflow.com/a/48156462
upvote count: 1
has title: Sorting list according to other list in python not working when second list contains numpy arrays
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48156462
type: Question
tagged with: numpy
answer count: 1
downvote count: 0
tagged with: sorting
has comment: http://stackoverflow.com/comment/83293353
favorite count: 0

http://stackoverflow.com/comment/83167886
type: AnswerComment
comment on: http://stackoverflow.com/a/48096187
type: Comment
has text: Thank you! Still, it's a good solution. I thought that the problem could be solved recursively, but I couldn't make it work :)
score: 0

http://stackoverflow.com/q/48131705
has comment: http://stackoverflow.com/comment/83241164
has comment: http://stackoverflow.com/comment/83252341
tagged with: database
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/83252464
has body: I am trying to build a single custom registration form for companies, admin, and staff. When I create my superuser, my 'Account type' is 'admin', but when I try to register as a a company my 'Account type' is empty. I can set a default value in my model class, but I would like to add more different types of 'Account type' in the future. I also don't want to have a dropdown for the field models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, account_type=None, password=None): if not email: raise ValueError('Email address is required') user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, account_type = account_type ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, first_name, last_name, password): user = self.create_user( email, first_name = first_name, last_name = last_name, account_type = 'staff', password = password ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password): user = self.create_user( email, first_name = first_name, last_name = last_name, account_type = 'admin', password = password ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) account_type = models.CharField(max_length=32) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email def get_full_name(self): return "%s %s" % (self.first_name, self.last_name) def get_s…
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83252395
tagged with: models
score: 0
tagged with: mysql
has title: unable to save data before saving models in django

http://stackoverflow.com/comment/83152081
has text: Thank you for your answer. Now, you said: `instance.__class__ ` will find and execute `type(instance).__dict__['__class__'].__get__(instance, type(instance))` but if do: `type(instance).__dict__` there is not a **__ class__** descriptor, which gets me to my first question, and assume that the descriptor **__ class__** exist only in the object **type** and is passed to all their instance objects (all classes). ?
comment on: http://stackoverflow.com/a/48066241
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/q/48084007
has title: Tensorflow - why negative padding lengths with convolutions?
tagged with: image-recognition
has comment: http://stackoverflow.com/comment/83145734
score: 0
has comment: http://stackoverflow.com/comment/83147325
tagged with: convolution
has comment: http://stackoverflow.com/comment/83145069
tagged with: python
answer count: 0
type: UnansweredQuestion
has body: For tf.layers.conv2d, I noticed that padding="VALID" sometimes does padding lengths with negative values. This page in the docs says that with "VALID" padding, the padding length is calculated as follows: out_height = math.ceil(float(in_height - filter_height + 1) / float(strides[1])) pad_along_height = ((out_height - 1) * strides[1] + filter_height - in_height) If you use these values, for example: in_height = 150 filter_height = 7 strides = (1, 4, 4, 1) Then you get pad_along_height == -3. Why would tensorflow sometimes choose negative padding by default? This seems weird to me. You lose information about the previous layer. Shouldn't "VALID" padding be the minimum amount of padding to retain all the information from the previous layer? Rather than losing 3 rows, (and getting an output height of 36), I think I would've preferred padding with 1 row and getting an output height of 37. Why did Google implement it this way? It's not really "padding" is it? More like "truncating". It just doesn't make sense to me. EDIT: Note - In this case "SAME" will produce pad_along_height == 5 for an output height of 38.
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/83143863
has comment: http://stackoverflow.com/comment/83144972
linked to: http://stackoverflow.com/q/37674306
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/48153715
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83286470
type: UnansweredQuestion
has title: Regularization Term using Lambda returning "invalid syntax"
tagged with: python
tagged with: lambda
downvote count: 1
has answer: http://stackoverflow.com/a/48153870
has comment: http://stackoverflow.com/comment/83286467
type: Question
has comment: http://stackoverflow.com/comment/83286298
score: -1
has body: Trying to write the regularization term for logistic regression in python. In Octive I used the following code: reg_term = (lambda / (2 * m) * theta_revised' * theta_revised; tried the following code in python; reg_term = (lambda / (2 * m)) * np.transpose(theta_revised).dot(theta_revised); getting a SyntaxError: invalid syntax with pointer aimed at the "/" #sigmoid function that calculates 1/(1 + e**-x) def sigmoid(x): return 1 / (1+ np.exp(-x)) #h is the prediction calculated taking the sigmoid of X * theta h = sigmoid(np.dot(X,theta)); #need to remove the first theta term for regularization theta_less = theta[1:size(theta)]; theta_revised = np.append([0],theta_less); #Calculate the regularization term #reg_term = (lambda/(2*m)) * (theta_revised' * theta_revised); reg_term = (lambda / (2 * m)) * np.transpose(theta_revised).dot(theta_revised);
upvote count: 0

http://stackoverflow.com/q/48160130
tagged with: flask-socketio
has answer: http://stackoverflow.com/a/72956868
upvote count: 7
tagged with: socket.io
has comment: http://stackoverflow.com/comment/94526150
possible better answer: http://stackoverflow.com/a/72956868
has comment: http://stackoverflow.com/comment/83317251
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48174191
downvote count: 0
score: 7
favorite count: 0
type: Question
has title: Using Flask-socketio and the socketIO client
answer count: 2
has comment: http://stackoverflow.com/comment/112501789
tagged with: python
has body: I'm currently trying to understand how sockets work. I'm using Flask-socketio and a python socketio client and running through a basic example. Here is what I have done so far app.py from flask import Flask, render_template from flask_socketio import SocketIO, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @socketio.on('aaa') def test_connect(): print("Welcome, aaa received") emit('aaa_response', {'data': 'Server'}) if __name__ == '__main__': socketio.run(app, port=8000) client.py from socketIO_client import SocketIO, LoggingNamespace def on_aaa_response(args): print('on_aaa_response', args['data']) socketIO = SocketIO('localhost', 8000, LoggingNamespace) socketIO.on('aaa_response', on_aaa_response) socketIO.emit('aaa') socketIO.wait(seconds=1) I get an assertion error when I run the client.py. I do see the server printing "Welcome, aaa recived" though. I don't know what am I doing wrong here, If thats required here is my log Error log Exception in thread Thread-1: Traceback (most recent call last): File "c:\users\dj\appdata\local\programs\python\python36\Lib\threading.py", li ne 916, in _bootstrap_inner self.run() File "C:\Users\Dj\Desktop\Flask\FLASK-SOCKET\venv\lib\site-packages\socketIO_c lient\heartbeats.py", line 27, in run self._send_heartbeat() File "C:\Users\Dj\Desktop\Flask\FLASK-SOCKET\venv\lib\site-packages\socketIO_c lient\__init__.py", line 203, in _ping engineIO_packet_type, engineIO_packet_data) File "C:\Users\Dj\Desktop\Flask\FLASK-SOCKET\venv\lib\site-packages\socketIO_c lient\transports.py", line 109, in send_packet assert response.content == b'ok' AssertionError Traceback (most recent call last): File "demo.py", line 8, in &lt;module&gt; socketIO.emit('aaa') File "C:\Users\Dj\Desktop\Flask\FLASK-SOCKET\venv\lib\site-packages\socketIO_c lient\__init__.py", line 424, in emit self._message(str(socketIO_packet_type) + socketIO_packet_data) File "C:\Users\Dj\Desktop\Flask\FLASK-SOCKET\venv\lib\site-packages\so…
accepted answer: http://stackoverflow.com/a/48174191
has comment: http://stackoverflow.com/comment/83304677

cluster-analysis
tags question: http://stackoverflow.com/q/48092084
tags question: http://stackoverflow.com/q/48042797
tags question: http://stackoverflow.com/q/48051800
tags question: http://stackoverflow.com/q/48036593
tags question: http://stackoverflow.com/q/48039293
tags question: http://stackoverflow.com/q/48136738
tag name: cluster-analysis
type: Tag

http://stackoverflow.com/comment/83151217
has text: Try to reduce your program to the minimum first, but make sure that it can still be run. It often takes a lot of time to read and analyze the code of someone else. If you don't know how to minimize it, just post everything.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48069743
type: Comment

http://stackoverflow.com/q/48094160
type: Question
tagged with: indexing
type: AnsweredQuestion
has title: Python Multi-Index: Finding cordinates with level 2 index, DataFrame
has answer: http://stackoverflow.com/a/48094374
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48094374
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has body: I have an empty DataFrame with Multi-Index index and columns. I also have list of strings that is cordinates of second level indexes. Since all of my second level index are unique, I am hoping to find cordinates and input values with my list of strings. Take a look at below example df= DNA Cat2 .... Item A B C D E F F H I J DNA Item Cat2 A 0 0 0 0 0 0 0 0 0 0 B 0 0 0 0 0 0 0 0 0 0 C 0 0 0 0 0 0 0 0 0 0 D 0 0 0 0 0 0 0 0 0 0 E 0 0 0 0 0 0 0 0 0 0 F 0 0 0 0 0 0 0 0 0 0 .... str_cord = [(A,B),(A,H),(A,I),(B,H),(B,I),(H,I)] #and my output should be like below. df_result= DNA Cat2 .... Item A B C D E F F H I J DNA Item Cat2 A 0 1 0 0 0 0 0 1 1 0 B 0 0 0 0 0 0 0 1 1 0 C 0 0 0 0 0 0 0 0 0 0 D 0 0 0 0 0 0 0 0 0 0 E 0 0 0 0 0 0 0 0 0 0 F 0 0 0 0 0 0 0 0 0 0 H 0 0 0 0 0 0 0 0 1 0 .... It looks kinda complicated, but all I want to do is use my str_cord[0] as my cordinate for df_result. I tried with .loc, but it seems like I need to input level 1 index. I am looking for the way that I do not have to input Multi-Index level1 and find cordinates with level2 strings. Hope it make sense and thanks in advance! (Oh the data itself is very big, so as efficient as possible)
has comment: http://stackoverflow.com/comment/83163046
tagged with: python
score: 1
upvote count: 1
tagged with: multi-index

http://stackoverflow.com/a/48055002
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/83082462
has comment: http://stackoverflow.com/comment/83082431
downvote count: 0
has body: You put the initialization of the dict inside the function body. So each time the function gets executed, the items go back to 0:0 and 1:1. When fibMemo(3) is called, it will enter line 5, which will be: pad[3]=pad[2]+pad[1] Since pad[2] was added but later wiped out during initialization of pad. It gives the key error. You should consider moving the pad={} before the function definition.
answers question: http://stackoverflow.com/q/48054910

http://stackoverflow.com/q/48156822
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83293635
type: Question
has comment: http://stackoverflow.com/comment/83293892
has body: I'm trying to plot financial data, and everything is looking good until I add a fill, which I want to be between a line and the top of the graph. I'm doing something very wrong, but I don't know what. I receive this error: "TypeError: ufunc 'isfinite' not supported for the ed types according to the casting rule ''safe''" Here's a simplified version of the code I'm using: import mysql import matplotlib.pyplot as plt db = mysql.connect() cursor = db.cursor() contractID = input('Enter contract ID: ') prices = [] x = [] cursor.execute('SELECT * FROM prices WHERE ContractID = %s' % contractID) for i in range(0, cursor.rowcount): row = cursor.fetchone() price = row[2] # Changing this to price = int(row[2]) fixes the problem. See comments. prices.append(price) x.append(i) plt.fill_between(x, 100, prices) # TODO: This doesn't work. Everything else works if I remove this line. plt.plot(prices) plt.ylim(0, 100) plt.show() EDIT: I'd love to provide a Minimal, Complete, and Verifiable example, but when I attempt to do so, the example works. I don't know how to reproduce the error. Here's my working attempt: import matplotlib.pyplot as plt x = [] y = [] for i in range(0, 49): x.append(i) y.append(i) plt.fill_between(x, 100, y) # This works fine now plt.plot(x, '#000000') plt.ylim(0, 100) plt.show()
has comment: http://stackoverflow.com/comment/83294285
score: 0
has title: Not sure how to implement fill_between in matplotlib
has comment: http://stackoverflow.com/comment/83292877
has comment: http://stackoverflow.com/comment/83293999
has comment: http://stackoverflow.com/comment/83293754
has comment: http://stackoverflow.com/comment/83294111
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83293355
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/83294170

http://stackoverflow.com/comment/120844127
comment on: http://stackoverflow.com/a/48037175
type: AnswerComment
has text: @emanuelsanga Opening a file using `with open(...)` statement automatically closes the file when the `with` block exits. See: https://stackoverflow.com/q/31334061/1925257.
score: 0
type: Comment

http://stackoverflow.com/comment/83159347
type: AnswerComment
score: 0
type: Comment
has text: Please, give me the code how you used? May be you haven't edited your code line.Change this line `dataset.freeze(result, format='csv', filename=settings.CSV_NAME)` into `freeze(result, format='csv', filename=settings.CSV_NAME)`
comment on: http://stackoverflow.com/a/48090854

http://stackoverflow.com/a/48097685
has body: This is not how you write a decorator. A decorator is a function that returns another function; that inner function must then do some logic and (optionally) call the decorated function. The outer function itself does not take the parameters that are passed to the original function; the inner function does. def login_required(view_function): def inner(request, *args, **kwargs): print(args) print(kwargs) if not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) return view_function(request, *args, **kwargs) return inner However, all this seems pretty pointless as Django already provides a login_required decorator.
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48097400
score: 2
answers question: http://stackoverflow.com/q/48097400
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83222956
type: QuestionComment
has text: Can anybody provide a general solution or point me In the right direction please ?
score: 0
comment on: http://stackoverflow.com/q/48077286
type: Comment

tkinter
tags question: http://stackoverflow.com/q/48032488
tags question: http://stackoverflow.com/q/48046078
tags question: http://stackoverflow.com/q/48033369
tags question: http://stackoverflow.com/q/48045173
tags question: http://stackoverflow.com/q/48145182
tags question: http://stackoverflow.com/q/48033347
tags question: http://stackoverflow.com/q/48086482
tags question: http://stackoverflow.com/q/48080899
tags question: http://stackoverflow.com/q/48036468
tags question: http://stackoverflow.com/q/48141324
tags question: http://stackoverflow.com/q/48053494
tags question: http://stackoverflow.com/q/48144228
tags question: http://stackoverflow.com/q/48054027
tags question: http://stackoverflow.com/q/48087148
tags question: http://stackoverflow.com/q/48052036
tags question: http://stackoverflow.com/q/48129567
tags question: http://stackoverflow.com/q/48136409
tags question: http://stackoverflow.com/q/48025042
tags question: http://stackoverflow.com/q/48129903
tags question: http://stackoverflow.com/q/48117575
tags question: http://stackoverflow.com/q/48091080
tag name: tkinter
tags question: http://stackoverflow.com/q/48139440
tags question: http://stackoverflow.com/q/48079105
tags question: http://stackoverflow.com/q/48046884
tags question: http://stackoverflow.com/q/48045147
tags question: http://stackoverflow.com/q/48028698
tags question: http://stackoverflow.com/q/48062717
tags question: http://stackoverflow.com/q/48057591
tags question: http://stackoverflow.com/q/48149467
tags question: http://stackoverflow.com/q/48045799
tags question: http://stackoverflow.com/q/48103836
tags question: http://stackoverflow.com/q/48148640
tags question: http://stackoverflow.com/q/48130943
tags question: http://stackoverflow.com/q/48086375
tags question: http://stackoverflow.com/q/48132282
tags question: http://stackoverflow.com/q/48143566
tags question: http://stackoverflow.com/q/48051627
tags question: http://stackoverflow.com/q/48036557
tags question: http://stackoverflow.com/q/48029920
tags question: http://stackoverflow.com/q/48142102
tags question: http://stackoverflow.com/q/48044766
tags question: http://stackoverflow.com/q/48125292
tags question: http://stackoverflow.com/q/48105438
tags question: http://stackoverflow.com/q/48038174
tags question: http://stackoverflow.com/q/48142104
tags question: http://stackoverflow.com/q/48052766
tags question: http://stackoverflow.com/q/48079022
tags question: http://stackoverflow.com/q/48027440
tags question: http://stackoverflow.com/q/48023433
tags question: http://stackoverflow.com/q/48135260
tags question: http://stackoverflow.com/q/48052848
tags question: http://stackoverflow.com/q/48122796
tags question: http://stackoverflow.com/q/48085771
tags question: http://stackoverflow.com/q/48019791
tags question: http://stackoverflow.com/q/48147780
tags question: http://stackoverflow.com/q/48142010
tags question: http://stackoverflow.com/q/48119322
tags question: http://stackoverflow.com/q/48033209
tags question: http://stackoverflow.com/q/48020987
tags question: http://stackoverflow.com/q/48146801
tags question: http://stackoverflow.com/q/48019622
tags question: http://stackoverflow.com/q/48149922
tags question: http://stackoverflow.com/q/48133862
tags question: http://stackoverflow.com/q/48064607
tags question: http://stackoverflow.com/q/48120967
tags question: http://stackoverflow.com/q/48131344
tags question: http://stackoverflow.com/q/48079982
tags question: http://stackoverflow.com/q/48158903
tags question: http://stackoverflow.com/q/48088685
tags question: http://stackoverflow.com/q/48032739
tags question: http://stackoverflow.com/q/48133372
tags question: http://stackoverflow.com/q/48038526
tags question: http://stackoverflow.com/q/48111245
tags question: http://stackoverflow.com/q/48121492
tags question: http://stackoverflow.com/q/48111728
tags question: http://stackoverflow.com/q/48085597
tags question: http://stackoverflow.com/q/48141423
tags question: http://stackoverflow.com/q/48138390
tags question: http://stackoverflow.com/q/48130901

http://stackoverflow.com/q/48051081
has comment: http://stackoverflow.com/comment/95288686
has comment: http://stackoverflow.com/comment/83104048
tagged with: web
has comment: http://stackoverflow.com/comment/88056744
favorite count: 0
tagged with: python-3.x
tagged with: telegram
type: UnansweredQuestion
score: 6
tagged with: python
has answer: http://stackoverflow.com/a/66921502
upvote count: 6
has title: invite user by username to telegram channel
has comment: http://stackoverflow.com/comment/83079352
has comment: http://stackoverflow.com/comment/83077465
has body: i trying to add users by usernames to my channel. I am using python 3.6 telethon library and pythonanywhere server: api_hash = 'b7**' phone = '+7***' client = TelegramClient('new_ses', api_id, api_hash) client.connect() client = TelegramClient('session_neworig', api_id, api_hash,) client.connect() from telethon.tl.functions.channels import InviteToChannelRequest from telethon.tl.functions.contacts import ResolveUsernameRequest from telethon.tl.types import InputPeerChannel ,InputPeerUser,InputUser from telethon.tl.functions.channels import JoinChannelRequest chann=client.get_entity('channelname') #its public channel print(chann.id) 1161823752 print(chann.access_hash) 8062085565372622341 time.sleep(30) chan=InputPeerChannel(chann.id, chann.access_hash) user = client(ResolveUsernameRequest('Chai***')) print(user.users[0].id) 193568760 print(user.users[0].access_hash) -4514649540347033311 time.sleep(1*30) user=InputUser(user.users[0].id,user.users[0].access_hash,) client.invoke(InviteToChannelRequest(chan,[user])) This dosent work and i get -telethon.errors.rpc_error_list.PeerFloodError: (PeerFloodError(...), 'Too many requests') what am i doing wrong? how to avoid it ? this one code is worked for me , but i am gone to flood after added let's say 20 users : from telethon.helpers import get_input_peer client.invoke(InviteToChannelRequest( get_input_peer(client.get_entity(chan), [get_input_peer(client.get_entity(user))] )) Please help , how to add 200 users by username without any ban , maybe there is another way to do it by python ? another lib or by api ?
has comment: http://stackoverflow.com/comment/83077586
has comment: http://stackoverflow.com/comment/83079576
has comment: http://stackoverflow.com/comment/83078305
type: Question
tagged with: telethon
answer count: 2
has answer: http://stackoverflow.com/a/63617565
downvote count: 0
has comment: http://stackoverflow.com/comment/83079359
has comment: http://stackoverflow.com/comment/83077333
has comment: http://stackoverflow.com/comment/104867871

http://stackoverflow.com/a/48150009
has body: Something using itertools.chain might suit your needs, but you might run into performance problems if the returned dataset is large: from itertools import chain collections = list(chain( TokenCollection.objects.filter(title__istartswith=query), TokenCollection.objects.filter(title__icontains=query) .exclu‌​de(title__istartswit‌​h=query) ))
has comment: http://stackoverflow.com/comment/83279312
score: 0
has comment: http://stackoverflow.com/comment/83279604
type: Answer
has comment: http://stackoverflow.com/comment/83279070
has comment: http://stackoverflow.com/comment/83279691
answers question: http://stackoverflow.com/q/48149945
has comment: http://stackoverflow.com/comment/83279203
has comment: http://stackoverflow.com/comment/83279497

http://stackoverflow.com/q/48122916
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48123085
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48123020
has title: JSON to Python objects
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
tagged with: object
answer count: 2
has body: I am deliberating about how to transfer the complex information from a JSON API response to (several) Python objects. I have included the (lengthy) model response below. Note that some values are not always included in the response, and some values are a list of dictionaries. Is there an "easy" way to map the JSON response to Python objects? How would I ideally lay out the classes? Model JSON response: { "accounts" : { "accounting_reference_date" : { "day" : "integer", "month" : "integer" }, "last_accounts" : { "made_up_to" : "date", "period_end_on" : "date", "period_start_on" : "date", "type" : "string" }, "next_accounts" : { "due_on" : "date", "overdue" : "boolean", "period_end_on" : "date", "period_start_on" : "date" }, "next_due" : "date", "next_made_up_to" : "date", "overdue" : "boolean" }, "annual_return" : { "last_made_up_to" : "date", "next_due" : "date", "next_made_up_to" : "date", "overdue" : "boolean" }, "branch_company_details" : { "business_activity" : "string", "parent_company_name" : "string", "parent_company_number" : "string" }, "can_file" : "boolean", "company_name" : "string", "company_number" : "string", "company_status" : "string", "company_status_detail" : "string", "confirmation_statement" : { "last_made_up_to" : "date", "next_due" : "date", "next_made_up_to" : "date", "overdue" : "boolean" }, "date_of_cessation" : "date", "date_of_creation" : "date", "etag" : "string", "external_registration_number" : "string", "foreign_company_details" : { "accounting_requirement" : { "foreign_account_type" : "string", "terms_of_account_publication" : "string" }, "accounts" : { "account_period_from" : { "day" : "integer", "month" : "integer" }, "account_period_to" : { "day" : "integer", "month" : "integer" }, "must_file_within" : { "months" : "integer" } }, "business_activity" : "string", "company_type" : "string", "governed_by" : "string", "is_a_credit_finance_institution" : "boolean", "originating_registry" : { "country" : "string", "name" : "string" }, "r…
downvote count: 0
tagged with: class
tagged with: api

http://stackoverflow.com/q/48076780
has answer: http://stackoverflow.com/a/62045966
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/48077080
accepted answer: http://stackoverflow.com/a/48077080
downvote count: 4
tagged with: indices
type: AnsweredQuestion
has body: I am trying to find the start and stop indices of chunks of positive numbers in a list. cross = [7,5,8,0,0,0,0,2,5,8,0,0,0,0,8,7,9,3,0,0,0,3,2,1,4,5,0,0,0,7,5] For the given example input, the desired output is: [(0, 2), (7, 9), (14, 17), (21, 25), (29, 30)]
tagged with: list
linked to: http://stackoverflow.com/q/7270321
has title: Find starting and ending indices of list chunks satisfying given condition
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/62045966
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83127475

http://stackoverflow.com/a/48158427
downvote count: 1
accepted answer of: http://stackoverflow.com/q/48119483
upvote count: 5
score: 4
answers question: http://stackoverflow.com/q/48119483
type: AcceptedAnswer
type: Answer
has body: I found a solution, this simple python script writes response body to the file, and if request repeats - overwrites it every time. import mitmproxy def response(flow): if flow.request.pretty_url.endswith("example.com/orders"): with open("orders.html","wb") as f: f.write(flow.response.content) Save this script to save_body.py and use it with mitmdump -s save_body.py

http://stackoverflow.com/comment/83179306
type: Comment
has text: Do you have strings for the count columns, not lists?
comment on: http://stackoverflow.com/q/48101560
score: 0
type: QuestionComment

subprocess
tags question: http://stackoverflow.com/q/48170031
tag name: subprocess
tags question: http://stackoverflow.com/q/48137974
tags question: http://stackoverflow.com/q/48066887
tags question: http://stackoverflow.com/q/48117642
tags question: http://stackoverflow.com/q/48159538
tags question: http://stackoverflow.com/q/48144116
tags question: http://stackoverflow.com/q/48137522
tags question: http://stackoverflow.com/q/48028520
type: Tag
tags question: http://stackoverflow.com/q/48161117
tags question: http://stackoverflow.com/q/48100820
tags question: http://stackoverflow.com/q/48147289
tags question: http://stackoverflow.com/q/48025875
tags question: http://stackoverflow.com/q/48140941
tags question: http://stackoverflow.com/q/48173364
tags question: http://stackoverflow.com/q/48088276
tags question: http://stackoverflow.com/q/48036598
tags question: http://stackoverflow.com/q/48024209
tags question: http://stackoverflow.com/q/48017009

http://stackoverflow.com/a/48149971
has comment: http://stackoverflow.com/comment/83299469
has body: You can use ffill (fillna with method='ffill') with clip: x = x.ffill().clip(0,0) Alternative solutions with boolean mask and where or mask: x = x.where(x.ffill().isnull(), 0) x = x.mask(x.ffill().notnull(), 0) print (x) a b c d e f g h 1 NaN NaN 0.0 NaN NaN NaN NaN NaN 2 NaN 0.0 0.0 0.0 0.0 NaN NaN NaN 3 0.0 0.0 0.0 0.0 0.0 0.0 NaN 0.0 Detail: print (x.ffill()) a b c d e f g h 1 NaN NaN 2.0 NaN NaN NaN NaN NaN 2 NaN 2.0 2.0 10.0 23.0 NaN NaN NaN 3 3.0 2.0 23.0 42.0 232.0 3.0 NaN 5.0 print (x.ffill().isnull()) a b c d e f g h 1 True True False True True True True True 2 True False False False False True True True 3 False False False False False False True False
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48149856
answers question: http://stackoverflow.com/q/48149856
type: Answer
score: 0

http://stackoverflow.com/comment/83074232
comment on: http://stackoverflow.com/a/48051213
score: 0
type: AnswerComment
has text: I'm sorry, can you add an example or link, where I can read, how I can realize it? Thanks.
type: Comment

http://stackoverflow.com/comment/83060508
type: QuestionComment
comment on: http://stackoverflow.com/q/48033323
type: Comment
has text: Did you try pycharm man it's greate IDE for python
score: 0

http://stackoverflow.com/comment/83327345
type: QuestionComment
has text: Most likely it has to do with Intel's MKL python version
score: 0
comment on: http://stackoverflow.com/q/48165702
type: Comment

http://stackoverflow.com/a/49484380
upvote count: 12
score: 10
answers question: http://stackoverflow.com/q/48072587
has body: @Lê Huy Hùng Please check official documentations before posting a question like this. Here's the official documentation of pip uninstall Here's how I uninstalled it pip uninstall opencv-python Uninstalling opencv-python-3.4.0.12: /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/.dylibs/QtCore /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/.dylibs/QtGui /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/.dylibs/QtTest /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/.dylibs/libavcodec.57.107.100.dylib /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/.dylibs/libavformat.57.83.100.dylib /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/.dylibs/libavresample.3.7.0.dylib /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/.dylibs/libavutil.55.78.100.dylib /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/.dylibs/libmp3lame.0.dylib /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/.dylibs/libswresample.2.9.100.dylib /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/.dylibs/libswscale.4.8.100.dylib /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/LICENSE-3RD-PARTY.txt /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/LICENSE.txt /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/init.py /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/pycache/init.cpython-35.pyc /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/cv2.cpython-35m-darwin.so /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/data/init.py /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/data/pycache/init.cpython-35.pyc /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/data/haarcascade_eye.xml /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/data/haarcascade_eye_tree_eyeglasses.xml /Users/name/.virtualenvs/LT/lib/python3.5/site-packages/cv2/data/haarcascade_frontalcatface.xml /Users/name/.virtualenvs/LT/lib/python3.5/sit…
downvote count: 2
type: Answer

http://stackoverflow.com/comment/83285601
type: Comment
has text: That's a good goal, but keep in mind that the TCP stack itself already runs in parallel to your code -- that is, each TCP socket has an outgoing-data buffer (which you can configure using the SO_SNDBUF TCP option), usually located in kernel space, which the TCP stack drains as fast it can shovel data across the network. Therefore data transmission happens even while your other code is executing; as long as your code is producing data fast enough that the buffer rarely or never becomes empty, then you'll be getting the benefit you want anyway.
comment on: http://stackoverflow.com/q/48143565
score: 1
type: QuestionComment

http://stackoverflow.com/q/48025088
tagged with: python
has comment: http://stackoverflow.com/comment/83020869
has answer: http://stackoverflow.com/a/48025132
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83019794
score: 1
has comment: http://stackoverflow.com/comment/83020872
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83019607
accepted answer: http://stackoverflow.com/a/48025132
downvote count: 0
answer count: 1
tagged with: header
has title: write csv rows one by one rather than all at once in python3 using writer.writerows(reader)
favorite count: 0
has body: I am saving a csv file after skipping the rows before the header: print (latest_file) with open(latest_file, "r",encoding="utf8") as infile: reader = csv.reader(infile) for row in reader: #look for if row[0] == 'date/time': print (row) break else: print("{} not found".format('name')) with open("C:/s3/"+str(p.from_date)+'_'+str(p.to_date)+'_'+str(merchant["country"])+'_'+str(merchant["company"])+'_'+"payments.csv", "w", newline='') as outfile: writer = csv.writer(outfile) writer.writerow(row) # headers I am writing the remaining rows all at once to the file: try: writer.writerows(reader) # remaining rows except Exception as e: print (e) I would like to write the rows once by one because windows throws the following error: 'charmap' codec can't encode character '\x83' in position 142: character maps to &lt;undefined&gt; It seems to be a windows issue, and since it happens so rarely, I would prefer to save the rows to the file one by one so only the problematic rows are skipped.
has comment: http://stackoverflow.com/comment/83021143
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/48064419
score: 0
tagged with: function
has comment: http://stackoverflow.com/comment/83102215
has title: Python : Using one function to filter out a list present in another function
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/83102118
type: Question
has body: I have the following code: from lxml import etree from datetime import datetime file = "Loja_mais_avancado.xml" treeDoc = etree.parse(file) listaUtilizadores = treeDoc.xpath("//Utilizador") listaCompras = treeDoc.xpath("//compra") listaProdutos = treeDoc.xpath("//produto") for compra in listaCompras: data = compra.xpath("//compra/@data_de_compra") coid = compra.xpath("//compra/@coid") estado = compra.xpath("//compra/@estado") compradorId = compra.xpath("//compra/@id") rangeCompra = compra.xpath("count(//compra)") for produto in listaProdutos: produtoId = produto.xpath("//produto/@iid") rangeProduto = produto.xpath("count(//produto)") compradorId = [word.replace("U01", "Xavier Ribeiro André") for word in compradorId] compradorId = [word.replace("U02", "Francisco Varela") for word in compradorId] compradorId = [word.replace("U03", "Miguel Garcia") for word in compradorId] compra = [0, 0, 0, 0] produto = [0, 0, 0, 0] for g in range(int(rangeCompra)): dataParsed = datetime.strptime(data[g], "%Y/%m/%d") compra[g] = (dataParsed.year, coid[g], compradorId[g], data[g], estado[g]) for p in range(int(rangeProduto)): dataParsed = datetime.strptime(data[p], "%Y/%m/%d") produto[p] = (dataParsed.year, coid[p], produtoId[p]) def compraPorAno(ano): print("Compras em:", ano) for (a, b, c, d, e) in compra: if ano == a: print("ID:", b) print("Comprador:", c) print("Data de inserção:", d) print("Estado de Compra:", e) produtosNasCompras(ano) def produtosNasCompras(ano): for (a, b, c, d, e) in compra: for (f, g, h) in produto: if ano == f: if g == b: print(" Produtos:", h) compraPorAno(2017) With the following output: Compras em: 2017 ID: CO02 Comprador: Xavier Ribeiro André Data de inserção: 2017/10/15 Estado de Compra: emExpedicao Produtos: I03 Produtos: I01 Produtos: I02 ID: CO03 Comprador: Miguel Garcia Data de inserção: 2017/10/20 Estado de Compra: entregue Produtos: I03 Produtos: I01 Produtos: I02 ID: CO04 Comprador: Miguel Garcia Data de inserção: 2017/10/20 Estado de Compra: ent…

http://stackoverflow.com/comment/83103596
type: Comment
has text: Yes, windows 10.
type: AnswerComment
comment on: http://stackoverflow.com/a/48065090
score: 0

http://stackoverflow.com/comment/83110894
type: Comment
comment on: http://stackoverflow.com/a/48068048
has text: He's only interested in `data_list['words']`, why loop over all of `data_list`?
type: AnswerComment
score: 0

function-parameter
type: Tag
tags question: http://stackoverflow.com/q/48030117
tag name: function-parameter

http://stackoverflow.com/q/48127309
answer count: 1
has answer: http://stackoverflow.com/a/48127390
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/83231425
has comment: http://stackoverflow.com/comment/83266529
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: How can i convert i large xml (500M)with complex structure in to csv ? Sample XML: 2 www.mysite.com/45656.jpeg 2 www.mysite.com/354456.jpeg Code Python : from xmlutils.xml2csv import xml2csv converter = xml2csv("/home/mehul/Downloads/instant/static/images.xml", "/home/mehul/Downloads/instant/static/images.csv", encoding="utf-8") converter.convert(tag="image") Actual Output: id,title,url 2,,www.mysite.com/45656.jpeg 2,,www.mysite.com/354456.jpeg Expected Output: id,ismain sml med big,title,url 2,,,,,www.mysite.com/45656.jpeg 2,,,,,www.mysite.com/354456.jpeg
score: 0
type: Question
has title: xml2csv with xml Attribute and Values in Python
tagged with: converters

http://stackoverflow.com/q/48132817
downvote count: 0
answer count: 1
has title: Python by Example Book: url_patterns syntax deprecated
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83242931
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83242810
type: Question
has answer: http://stackoverflow.com/a/48133113
has body: In setting up Login and Logout url patterns, the book (which I believe uses Django 1.8) cites: from django.conf.urls import url from . import views url(r'^login/$', 'django.contrib.auth.views.login', name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'), url(r'^logout-then-login/$','django.contrib.auth.views.logout_then_login',name='logout_then_login'), where login, logout and logout_then_login have corresponding .html files in the same app template/account directory. However, on Django 1.11, these give errors of: "TypeError: view must be a callable or a list/tuple in the case of include()" which I believe is because this syntax is now deprecated for 1.10 and above). Tried: from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views url(r'^login/$', auth_views.LoginView.as_view(template_name='registration/login.html')), url(r'^logout/$', auth_views.LogoutView.as_view(template_name='registration/logged_out.html')), url(r'^logout-then-login/$', auth_views.LogoutThenLogin.as_view(template_name='logout_then_login.html')), instead, but now getting "no reverse match" errors in my main "base.html" code, at the: Log-in line in: {% load staticfiles %} {% block title %}{% endblock %} Bookmarks {% if request.user.is_authenticated %} My dashboard Images People {% endif %} {% if request.user.is_authenticated %} Hello {{ request.user.username }}, Logout {% else %} Log-in {% endif %} {% block content %} {% endblock %} which didn't occur before in the earlier version of the code in the book, which used a local 'login.html' view pointed at by: url(r'^login/$', views.user_login, name='login'), and used exactly the same html code. FWIW, I have the project settings.py file set with: from django.core.urlresolvers import reverse_lazy LOGIN_REDIRECT_URL = reverse_lazy('dashboard') # redirect after login if no next parameter LOGIN_URL = reverse_lazy('login') # redirect to login if login_required decorator set LOGOUT…

http://stackoverflow.com/a/48127306
answers question: http://stackoverflow.com/q/48127273
score: 3
has comment: http://stackoverflow.com/comment/83231235
type: AcceptedAnswer
downvote count: 0
has body: You can create groups by consecutive values with compare shifted values and cumsum and use it for cumcount: s = pd.Series([True, False, False, False, True, True, False]) s1 = s.groupby(s.ne(s.shift()).cumsum()).cumcount().add(1) print (s1) 0 1 1 1 2 2 3 3 4 1 5 2 6 1 dtype: int64 Detail: print (s.ne(s.shift()).cumsum()) 0 1 1 2 2 2 3 2 4 3 5 3 6 4 dtype: int32 Another solution is count Trues and Falses separately and then sum outputs: cm1 = s.cumsum() s1 = cm1-cm1.where(~s).ffill().fillna(0) cm2 = (~s).cumsum() s2 = cm2-cm2.where(s).ffill().fillna(0) s3 = s1.add(s2).astype(int) print (s3) 0 1 1 1 2 2 3 3 4 1 5 2 6 1 dtype: int32 Detail: print (s1) 0 1.0 1 0.0 2 0.0 3 0.0 4 1.0 5 2.0 6 0.0 dtype: float64 print (s2) 0 0.0 1 1.0 2 2.0 3 3.0 4 0.0 5 0.0 6 1.0 dtype: float64 Timings: np.random.seed(2018) N = 1000000 s = pd.Series(np.random.choice([True, False], N)) #print (s) def jez1(s): return s.groupby(s.ne(s.shift()).cumsum()).cumcount().add(1) def jez2(s): cm1 = s.cumsum() s1 = cm1-cm1.where(~s).ffill().fillna(0) cm2 = (~s).cumsum() s2 = cm2-cm2.where(s).ffill().fillna(0) return s1.add(s2).astype(int) print (jez1(s)) print (jez2(s)) In [173]: %timeit jez1(s) 1 loop, best of 3: 199 ms per loop In [174]: %timeit jez2(s) 10 loops, best of 3: 92 ms per loop
accepted answer of: http://stackoverflow.com/q/48127273
type: Answer
upvote count: 3

http://stackoverflow.com/a/48057239
accepted answer of: http://stackoverflow.com/q/48021882
type: Answer
score: 2
has body: First you must access Rows for it we use ids since he has an id: Rows: id: rows Then you access each Row through children since when you use add_widget is stored in this ListProperty, and the same is done with Row but isinstance() is used to filter the TextInput, after that the text is obtained and added to the list. It should be noted that the oldest children are at the end because of it reversed() is used. from kivy.uix.textinput import TextInput [...] def insert_value(self): values = [] rows = self.ids.rows for row in reversed(rows.children): for ch in row.children: if isinstance(ch, TextInput): values.append(ch.text) print(values)
upvote count: 2
answers question: http://stackoverflow.com/q/48021882
has comment: http://stackoverflow.com/comment/119430661
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/65367978
upvote count: 4
answers question: http://stackoverflow.com/q/48158017
has body: True if any value is nan: torch.any(tensor.isnan()) True if all is nan: torch.all(tensor.isnan())
downvote count: 0
score: 4
type: Answer

http://stackoverflow.com/q/48122105
answer count: 0
linked to: http://stackoverflow.com/q/18792918
score: 0
has comment: http://stackoverflow.com/comment/83221046
has comment: http://stackoverflow.com/comment/83221079
type: Question
has comment: http://stackoverflow.com/comment/83221208
linked to: http://stackoverflow.com/q/38775588
tagged with: pandas
has title: Combine Multiple Pandas DataFrames Via Index
duplicate of: http://stackoverflow.com/q/38775588
tagged with: data-analysis
has comment: http://stackoverflow.com/comment/83221520
type: UnansweredQuestion
tagged with: python
has body: I am going cross eyed on this and hopefully someone can answer the question for me. I have a list of DataFrames with only a timestamp as an index and a column for sales (depending on state). What I am trying to do is combine all the DataFrames in the list and output a new one. Example Dataframes would appear: | time | USA | |-----------|-----| | 12-1-2012 | 1 | | 12-2-2012 | 1 | | 12-3-2012 | 1 | | 12-4-2012 | 3 | | 12-5-2012 | 5 | | 12-6-2012 | 6 | | 12-7-2012 | 4 | | 12-8-2012 | 2 | | 12-9-2012 | 5 | | time | UK | |-----------|-----| | 12-1-2012 | 1 | | 12-2-2012 | 1 | | 12-5-2012 | 5 | | 12-6-2012 | 6 | | 12-7-2012 | 4 | | 12-8-2012 | 2 | | 12-9-2012 | 5 | | time | CAN | |-----------|-----| | 12-1-2012 | 1 | | 12-2-2012 | 1 | | 12-4-2012 | 3 | | 12-6-2012 | 4 | | 12-8-2012 | 2 | | 12-9-2012 | 5 | | time | USA | UK | CAN | |-----------|-----|-----|-----| | 12-1-2012 | 1 | 1 | 1 | | 12-2-2012 | 1 | 1 | 1 | | 12-3-2012 | 1 | NaN | NaN | | 12-4-2012 | 3 | NaN | NaN | | 12-5-2012 | 5 | 5 | NaN | | 12-6-2012 | 6 | 6 | 6 | | 12-7-2012 | 4 | 4 | 4 | | 12-8-2012 | 2 | 2 | 2 | | 12-9-2012 | 5 | 5 | 5 | The last table is technically what I want to happen. I want all of them to be combined on the time and if it doesn't have that key then just add a NaN value for now. I am running into some oddities. The frames are stored in a list: dataframes = [d1,d2,d3] What I have tried is to use a reduce method while joining and it seems to mangle the data. Here is a full example. d1 = ts.copy() d1.columns = ['time'] d1.index = d1['time'] # del d1['time'] d1['USA'] = range(9) d2 = ts.copy() d2.columns = ['time'] d2.index = d2['time'] # del d2['time'] d2['UK'] = range(9) d3 = ts.copy() d3.columns = ['time'] d3.index = d3['time'] # del d3['time'] d3['UK'] = range(9) d2.drop(d2.index[[2,3]]) d3.drop(d3.index[[2,4,6]]) dataframes = [d1, d2, d3] df_final = reduce(lambda left,right: pd.merge(left,right,on='time'), dataframes) df_final # Output time USA UK_x UK_y 0 2012-12-01 0 0 0 1 2012-12-02…

http://stackoverflow.com/q/48052036
has answer: http://stackoverflow.com/a/48054338
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/48054338
has comment: http://stackoverflow.com/comment/83076193
tagged with: tkinter
tagged with: turtle-graphics
has body: I saw the sorting example in turtle demo which python includes and I would like to add similar animations in my program. My program is based in tkinter and I would like to insert turtle animations in a tkinter canvas (with RawTurtle) so first I tried to create a black box in the canvas and I get the following error message: AttributeError: 'RawTurtle' object has no attribute 'Turtle' Here's my code: import tkinter from turtle import * class MyApp(): def __init__(self, parent): self.p = parent self.f = tkinter.Frame(self.p).pack() self.c = tkinter.Canvas(self.f, height = '640', width = '1000') self.c.pack() self.t = RawTurtle(self.c) self.main(5) def main(self, size): self.t.size = size self.t.Turtle.__init__(self, shape="square", visible=False) self.t.pu() self.t.shapesize(5, 1.5, 2) self.t.fillcolor('black') self.t.st() if __name__ == '__main__': root= tkinter.Tk() frame = MyApp(root) root.mainloop()
score: 0
answer count: 1
has title: 'RawTurtle' object has no attribute 'Turtle'
tagged with: canvas
type: AnsweredQuestion

http://stackoverflow.com/q/48113250
has body: There is a python code, which is supposed to support Python 3, but may or may not run in Python 2.7. For example, this snippet can run in both Python 2.7 and Python 3. What is the standard way to enforce and recommend Python 3 compatibility in strict mode, even if the code runs fine on Python 2.7 ? print('This file works in both') print('How to throw an exception,and suggest recommendation of python 3 only ?') Python 2.7 : https://ideone.com/bGnbvd Python 3.5 : https://ideone.com/yrTi3p There can be multiple hacks and exceptions, which work in Python 3, and not in Python 2.7, which can be used to achieve this. I am looking for most recommended way of doing this in the beginning of files/modules/projects.
upvote count: 10
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48113307
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/48113307
type: Question
has title: What is the standard way to recommend "Python 3 only" compatibility for a Python module?
favorite count: 0
tagged with: python-3.x
score: 9
has answer: http://stackoverflow.com/a/48113373
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/48113373

http://stackoverflow.com/comment/83226499
score: 0
type: Comment
has text: You wouldn't need the list comprehension inside the call to `set()`. Just call it directly on the Series.
type: AnswerComment
comment on: http://stackoverflow.com/a/48124725

http://stackoverflow.com/a/48158303
has comment: http://stackoverflow.com/comment/83521541
score: 0
has body: "Referring to these stores from another model" implies that there should be some kind of (logical) relationship between those models. This is usually depicted by connecting the models with a foreign key. In other words, you can try something like this: from django.db import models class Store(models.Model): name = models.CharField(max_length=50) id = models.CharField(max_length=5) def __str__(self): return 'Store is named: %s' % self.name class Stores(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE) def __str__(self): return "Stores is at %s store" % (self.store) Create your store and save it: kittenstore = Store(name='kittenstore', id='1') kittenstore.save() Instantiate your Stores: st = Stores(id=None, store=kittenstore) st.save() And now you can access your store object like this: st.kittenstore The relationship I used in this example is a Many-to-one relationship. You should decide on the relationship that best suits your needs by taking a look at the Django documentation regarding model relationship. ***EDIT***If you mean associate them via the model's attributes then you can assign a model attribute to an instance of a class. For a related example on the matter, take a look at this.
has comment: http://stackoverflow.com/comment/83521449
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48157613
answers question: http://stackoverflow.com/q/48157613
has comment: http://stackoverflow.com/comment/83334526
has comment: http://stackoverflow.com/comment/83319135

http://stackoverflow.com/a/48068633
type: Answer
has body: Next step is to read each line. lines = file.readlines() Then you have to split each line on the spaces. This gives you an numbers array. for i, line in enumerate(lines): numbers = line.split(' ') dict1[i + 1] = numbers All together: def to_dictionary(filename): dict1 = {} with open (filename) as file: lines = file.readlines() for i, line in enumerate(lines): numbers = line.split(' ') dict1[i + 1] = numbers return dict1
answers question: http://stackoverflow.com/q/48068546
score: 0

http://stackoverflow.com/a/62372246
upvote count: 3
has comment: http://stackoverflow.com/comment/137388068
answers question: http://stackoverflow.com/q/48152908
type: Answer
has body: I had somehow the same problem, when using autocomplete_fields the limit_choices_to was not taking affect, and then I found a solution for my case which may help others too. this an idea and a solution for my case, anybody should change the code for his/her use. imagine we have two models model_A and modle_B: we are going to override the "get_search_results" of model-admin of model_A(because model_B has a foreign_key(or m2m) to it) in my case I just want to limit choices to all model_A objects which currentlly dont have a model_B connected object(s) or in case of updating an object of model_B limit to just the previous model_A object(s). so we go # moodels.py class model_A(models.Model): name = models.CharField() class model_B(models.Model): name = models.CharField() fk_field = models.OneToOneField( #ManyToManyField or ForeignKey model_A, related_name='fk_reverse', on_delete=models.CASCADE) # admin.py class model_A_Admin(admin.ModelAdmin): search_fields = ('name', ) def get_search_results(self, request, queryset, search_term): import re queryset, use_distinct = super().get_search_results(request, queryset, search_term) # note: str(request.META.get('HTTP_REFERER')) is the url from which the request had come/previous url. if "model_b/add/" in str(request.META.get('HTTP_REFERER')): # if we were in creating new model_B instanse page # note: the url is somehow containing model_Bs calss name then / then "add" # so there is no related object(of model_A) for non exsisting object(of model_B) queryset = self.model.objects.filter(fk_reverse=None) elif re.search(r"model_b/\d/change/", str(request.META.get('HTTP_REFERER'))): # if we were in updatineg page of an exsisting model_B instanse # the calling page url contains the id of the model_B instanse # we are extracting the id and use it for limitaion proccess pk = int(re.findall(r'\d+', str(str(request.META.get('HTTP_REFERER')).split('/')[-3: ]))[-1]) queryset = self.model.objects.filter(fk_reverse=pk) return queryset, use_disti…
downvote count: 0
score: 3

connexion
tag name: connexion
type: Tag
tags question: http://stackoverflow.com/q/48130372

http://stackoverflow.com/q/48131106
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83244573
type: Question
has comment: http://stackoverflow.com/comment/120923161
upvote count: 0
answer count: 1
tagged with: neural-network
has body: Currently studying the 'Deep Learning with Python' book by Francios Chollet. I am very new to this and I am getting this error code despite following his code verbatim. Can anyone interpret the error message or what needs to be done to solve it? Any help would be greatly appreciated! from keras.datasets import imdb import numpy as np from keras import models from keras import layers (train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000) def vectorize_sequences(sequences, dimension=10000): results = np.zeros((len(sequences), dimension)) for i, sequence in enumerate(sequences): results[i, sequence] = 1. return results x_train = vectorize_sequences(train_data) y_train = vectorize_sequences(test_data) x_train = np.asarray(train_labels).astype('float32') y_test = np.asarray(test_labels).astype('float32') model = models.Sequential() model.add(layers.Dense(16, activation='relu', input_shape=(10000,))) model.add(layers.Dense(16, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) model.fit(x_train, y_train, epochs=4, batch_size=512) results = model.evaluate(x_test, y_test) Edit: Here is an image of the error code that I am getting:
accepted answer: http://stackoverflow.com/a/48135788
linked to: http://stackoverflow.com/q/68422410
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/83239285
has comment: http://stackoverflow.com/comment/83243969
tagged with: python
score: -1
has title: Invalid array shape with neural network using Keras?
has comment: http://stackoverflow.com/comment/83244553
downvote count: 1
has answer: http://stackoverflow.com/a/48135788

http://stackoverflow.com/a/48142415
type: Answer
answers question: http://stackoverflow.com/q/48142388
score: 2
upvote count: 2
has body: The order in which a+b is calculated changes. In the first case, a+b is calculated after a=b is executed. In the second case, a+b is calculated before any assignment happens. In general, what happens in Python is that things at the right of = are evaluated before the assignment happens. If you're curious, you can take a look of what's happening behind the scenes using dis, that will show you the bytecode: &gt;&gt;&gt; dis.dis('a, b = b, a+b') 1 0 LOAD_NAME 0 (b) # Push the value of 'b' on top of the stack 2 LOAD_NAME 1 (a) # Push the value of 'a' 4 LOAD_NAME 0 (b) # Push the value of 'b' 6 BINARY_ADD # Compute the sum of the last two values on the stack # Now the stack contains the value of 'b' and of 'a+b', in this order 8 ROT_TWO # Swap the two values on top of the stack # Now the stack contains the value of 'a+b' and of 'b', in this order 10 STORE_NAME 1 (a) # Store the value on top of the stack inside 'a' 12 STORE_NAME 0 (b) # Store the value on top of the stack inside 'b'
has comment: http://stackoverflow.com/comment/83263491
downvote count: 0

http://stackoverflow.com/comment/83024505
type: QuestionComment
has text: @9000 I did not realize that! Without declaring anything as global, it seems to work. If you post that as an answer I can mark it
comment on: http://stackoverflow.com/q/48026961
score: 0
type: Comment

http://stackoverflow.com/comment/83236668
has text: Michael, thanks very much for the new code. I'm doing some tests right now and I will reply back shortly.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48122238

http://stackoverflow.com/q/48173041
score: 2
has comment: http://stackoverflow.com/comment/83329934
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83325907
has title: Alternative to 'for loops' in python which will run fast
has answer: http://stackoverflow.com/a/48175791
has body: In my python script, I have a 2d numpy array(named original_data) in which 1) I have to find all the unique rows 2)create an empty array 3)compare all the rows in the original_data with this unique_rows, when it matches with any row of unique_rows append the rowindex of that particular row of unique values to the created new array original_data = np.array([[1, 2, 7, 1, 2, 1], [1, 2, 7, 1, 2, 1], [1, 2, 7, 1, 2, 1], [1, 2, 6, 1, 2, 1], [1, 3, 5, 1, 1, 1], [1, 2, 5, 1, 1, 1], [1, 2, 5, 1, 1, 1], [1, 2, 5, 1, 1, 1], [1, 2, 5, 1, 1, 1], [1, 2, 5, 1, 1, 1]]) y = np.ascontiguousarray(original_data).view(np.dtype((np.void, original_data.dtype.itemsize * original_data.shape[1]))) _, idx = np.unique(y, return_index=True) unique_rows = original_data[idx] att = [] for i in range(original_data.shape[0]): for j in range(unique_rows.shape[0]): if(np.array_equal(original_data[i],unique_rows[j])): att.append(j) break else: continue this is running good but if I consider large dataset then this for loops is not a good option as it takes so much time to run. Can anyone suggest me a good replacement for these 2 forloops which runs much faster.
has comment: http://stackoverflow.com/comment/83340150
type: Question
tagged with: numpy
answer count: 2
tagged with: arrays
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83330411
has answer: http://stackoverflow.com/a/48175993
tagged with: python
has comment: http://stackoverflow.com/comment/83333335

http://stackoverflow.com/a/48026333
has body: you're basically merging on none existing columns. this is because reset_index creates a new data-frame rather than changing the data frame it's applied to. setting the parameter inplace=True when using reset_index should resolve this issue, alternatively merge on the index of each data-frame. i.e. pd.merge(df1,df2,left_index=True,right_index=True,how='left')
downvote count: 0
answers question: http://stackoverflow.com/q/48026254
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83022522

http://stackoverflow.com/q/48115107
downvote count: 0
tagged with: dialogflow-es
type: Question
has answer: http://stackoverflow.com/a/48120950
score: 3
upvote count: 3
answer count: 1
has body: I want to know if there is some way through which I can manage, update or delete Intents in Dialogflow programmatically using python. I have been able to send and get response from dialogflow using apiai library, but i want to be able to input intents, it's questions and the text response. I went through dialogflow library, which i think does help with that, but it has some requirements on making account on google console clouds. Is there a way to do what I want, without having to create/do billings or whatever it mentions in it's documentation in Dialogflow. If there is, please point me in the right direction. Thank you.
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: Managing Intents in Dialogflow
tagged with: python

http://stackoverflow.com/comment/101256174
comment on: http://stackoverflow.com/a/56226777
has text: I use part of your answer, it works, thank you so much. BTW the `request.path==` can be found in admin page source code, search: `data-ajax--url`. I didn't use /admin/ as my admin URL path. So it didn't work at the beginning.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83026939
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/48028417
has text: Sounds like not all values in `row['do']` are strings. Instead you have some floats in there as well. So you can simply do `if len(str(row['do'])) < 4` or you can force all values in the `do` column to be strings before you try and process each row.
type: Comment

http://stackoverflow.com/q/48128029
linked to: http://stackoverflow.com/q/38411942
accepted answer: http://stackoverflow.com/a/48129025
has body: Is there any way to install a specific build+version of a package in Anaconda? Stack Overflow post "anaconda/conda - install a specific package version" shows how to install a specific version of the package. But look below--there are several pillow packages version 4.2.1 that has "py27" prefix on it. Background: I am scratching my head to figure the meaning of "conda search" output. For example, on my installation, conda search pillow gives: pillow 2.1.0 py26_0 defaults ... * 3.3.1 py27_0 defaults 3.3.1 py34_0 defaults 3.3.1 py35_0 defaults .... 4.2.1 py27_0 defaults 4.2.1 py35_0 defaults 4.2.1 py36_0 defaults 4.2.1 py27h7cd2321_0 defaults 4.2.1 py35h03abc04_0 defaults 4.2.1 py36h9119f52_0 defaults 4.3.0 py35h550890c_1 defaults 4.3.0 py27h353bd0c_1 defaults 4.3.0 py36h6f462bf_1 defaults I understand the meaning of 2.1.0, 3.3.1, and so on--the version numbers. But what do py27_0 and defaults mean? More mind boggling was new appearance of the trailing hex numbers like in py27h7cd2321_0 . After researching some more: https://www.anaconda.com/blog/developer-blog/package-better-conda-build-3/ tells me that that's a new way to encode the specific build of the package. So back to my question: given that I'm still on Python 2.7 line of anaconda, how do we choose the py27_0 build instead of the other one (py27h7cd2321_0) when we do conda install?
type: AnsweredQuestion
tagged with: anaconda
type: Question
upvote count: 94
answer count: 1
downvote count: 0
has title: Installing specific BUILD of an anaconda package
favorite count: 0
has answer: http://stackoverflow.com/a/48129025
score: 94
tagged with: python

http://stackoverflow.com/q/48145845
has comment: http://stackoverflow.com/comment/83270018
type: Question
has comment: http://stackoverflow.com/comment/83269752
score: -2
has comment: http://stackoverflow.com/comment/83280683
upvote count: 0
has comment: http://stackoverflow.com/comment/83280708
has comment: http://stackoverflow.com/comment/83270187
answer count: 1
has comment: http://stackoverflow.com/comment/83270900
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/83270814
has comment: http://stackoverflow.com/comment/83269890
has body: # here i create a array of all div as arrayOfdivAfterContent but can,t get it.... import urllib2 import csv import requests import os, sys from bs4 import BeautifulSoup from datetime import datetime try : quote_page = "http://nari.nic.in/schemes?`field_age_group_value[0]=2&amp;field_age_group_value[1]=3&amp;field_age_group_value[2]=4&amp;field_age_group_value[3]=5&amp;field_area_value[0]=2&amp;field_area_value[1]=3&amp;field_area_value[2]=4&amp;field_area_value[3]=5&amp;field_area_value[4]=6&amp;field_state_value[0]=2&amp;field_state_value[1]=3&amp;field_state_value[2]=4&amp;field_state_value[3]=5&amp;field_state_value[4]=6&amp;field_state_value[5]=7&amp;field_state_value[6]=8&amp;field_state_value[7]=9&amp;field_state_value[8]=10&amp;field_state_value[9]=11&amp;field_state_value[10]=12&amp;field_state_value[11]=13&amp;field_state_value[12]=14&amp;field_state_value[13]=15&amp;field_state_value[14]=16&amp;field_state_value[15]=17&amp;field_state_value[16]=18&amp;field_state_value[17]=19&amp;field_state_value[18]=20&amp;field_state_value[19]=21&amp;field_state_value[20]=22&amp;field_state_value[21]=23&amp;field_state_value[22]=24&amp;field_state_value[23]=25&amp;field_state_value[24]=26&amp;field_state_value[25]=27&amp;field_state_value[26]=28&amp;field_state_value[27]=29&amp;field_state_value[28]=30&amp;field_state_value[29]=31&amp;field_state_value[30]=32&amp;field_state_value[31]=33&amp;field_state_value[32]=34&amp;field_state_value[33]=35&amp;field_state_value[34]=36&amp;field_state_value[35]=37&amp;field_state_value[36]=38&amp;page=12"` page = urllib2.urlopen(quote_page) soup = BeautifulSoup(page, "html.parser") headingValue = soup.find_all('h3', attrs={"class": "views- accordion- schemes-schemedisplay-header"}) view_content = soup.find('div', attrs={"class":"view-content"}) arrayOfdivAfterContent = view_content.find_next('div') except Exception as E: print(E)
tagged with: python
has answer: http://stackoverflow.com/a/48146141
type: UnansweredQuestion
has title: find all children of same level of a div element using bs4 in python
downvote count: 2

http://stackoverflow.com/comment/137028243
type: Comment
has text: Set default tensor type to CUDA is deprecated and torch.set_default_device('cuda') is used. nowadays
comment on: http://stackoverflow.com/a/66533975
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83186929
has text: This code produces some error on my computer – "Indentation" something something.
type: Comment
comment on: http://stackoverflow.com/q/48105436
score: 0
type: QuestionComment

http://stackoverflow.com/a/48142162
has comment: http://stackoverflow.com/comment/83370844
has comment: http://stackoverflow.com/comment/83368478
has body: What defines the goal state? When all 4 corners are touched. Given that you have all 4 corner coordinates already, you can use a simple Python list to store the corners as you pass the state along in the successor, removing from the list of corners when you reach that state. (The check itself would go in the getSuccessors() function since you pass along a state containing your current position). Then it should be simple for your goal condition to check this list.
type: Answer
answers question: http://stackoverflow.com/q/48142107
downvote count: 1
upvote count: 0
score: -1

http://stackoverflow.com/comment/83031398
type: QuestionComment
comment on: http://stackoverflow.com/q/48030522
score: 0
has text: @Yangyang.Guo. But what type of object is a `document`? Show the definition of the namedtuple and all the objects it contains.
type: Comment

http://stackoverflow.com/comment/83134458
type: QuestionComment
score: 0
has text: What encoding is the input? Looks a bit like yaml but not quite. Would it be enough to just fish out all uninterrupted character sequences?
comment on: http://stackoverflow.com/q/48080163
type: Comment

http://stackoverflow.com/comment/83025567
score: 0
comment on: http://stackoverflow.com/q/48027855
type: Comment
type: QuestionComment
has text: Have you tried anything at all? SO is *not* a free coding service.

http://stackoverflow.com/a/56061136
type: Answer
upvote count: 2
has body: I ran into the same issue when I was wanting to include a .ico file to use as the icon for my tkinter app. Here's how I got it to work: When building the .exe file with PyInstaller, I specified the --add-data option with the full path to my .ico. When the app starts up, it has to unpack everything from the .exe in a temp directory, so I get the path to that temp directory and use it to specify the temp location of my .ico file. Before the mainloop is kicked off, and using 'tempfile' to get the temp file directory and 'glob' to check for a file pattern match: tempdir = tempfile.gettempdir() icon_path = tempdir + '\\' + 'next_subdirectory_pattern' + '\\' + '*.ico' icon_matches = glob.glob(icon_path) if len(icon_matches) &gt; 0: logo = icon_matches[0] else: logo = '' tk.Tk.iconbitmap(self, default=logo) Probably not the most eloquent way to do it, but it works.
score: 2
answers question: http://stackoverflow.com/q/48134269
downvote count: 0

http://stackoverflow.com/q/48103801
has title: Matplotlib put x ticks above bar
has answer: http://stackoverflow.com/a/48104159
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83185083
has answer: http://stackoverflow.com/a/48105432
has comment: http://stackoverflow.com/comment/83183918
answer count: 2
tagged with: figure
has body: Is there any way to put the x-ticks above each stacked bar in a stacked bar chart, rather than below the x-axis? To be clear, I don't mean place the x-tick above each individual bar in a single stacked bar, I mean place the x-tick above the stacked bar itself. Here's how I'm creating my plot: df = pd.DataFrame(np.random.randint(1, 5, size=(3200, 3))) df.loc[np.random.choice(df.index, size=3190, replace=False), :] = 0 df_select = df[df.sum(axis=1)&gt;1] fig, ax = plt.subplots() ax.bar(df_select.index, df_select.iloc[:,0], label = df_select.columns[0], wdith = 15) if df_select.shape[1] &gt; 1: for i in range(1, df_select.shape[1]): bottom = df_select.iloc[:,np.arange(0,i,1)].sum(axis=1) ax.bar(df_select.index, df_select.iloc[:,i], bottom=bottom, label = df_select.columns[i], width = 15) ax.set_xticks(df_select.index) plt.legend(loc='best', bbox_to_anchor=(1, 0.5)) plt.xticks(rotation=90, fontsize=8) #this puts the x ticks below the x axis Additionally, I'd like to place some text at specific points along the x axis. I'm storing these sites in a list: sites = [19, 173, 1002] # the number and elements of this list vary So, for example, at x = 173, I'd like to place the text 'site (173)' along with a tick at position 173. For your reference, I've posted images for what my current code produces, and what I would like to produce: current: https://i.sstatic.net/QDlEP.png goal: https://i.sstatic.net/IJJo4.png
score: 0
has comment: http://stackoverflow.com/comment/83183987
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48105432
has comment: http://stackoverflow.com/comment/83184457
tagged with: python
type: AnsweredQuestion
tagged with: plot
type: Question
possible better answer: http://stackoverflow.com/a/48104159

http://stackoverflow.com/comment/83224279
type: QuestionComment
type: Comment
has text: With schema modification it is pretty straightforward query `db.collection_name.aggregate([ {"$unwind": "$users"}, { "$sort": { "users.position": 1 } }, { "$group": { "_id": "$users.position", "names": {"$addToSet:"$users.name"} }} ])`. Without schema modification it involves an extra stage to transform to array structure `db.collection_name.aggregate([ {"users:{"$objectToArray":"$users}}, {"$unwind": "$users"}, { "$sort": { "users.k": 1 } }, { "$group": { "_id": "$users.k", "names": {"$addToSet:"$users.v"} }} ])`. All queries are 3.4 shell based.
comment on: http://stackoverflow.com/q/48123581
score: 1

http://stackoverflow.com/a/48065234
answers question: http://stackoverflow.com/q/48063076
has comment: http://stackoverflow.com/comment/83123970
has comment: http://stackoverflow.com/comment/83109369
score: 4
has body: I am thinking about giving normalized original signal as input to the network, is this a good approach? Yes this is a good approach. It is actually quite standard for Deep Learning algorithms to give them your input normalized or rescaled. This usually helps your model converge faster, as now you are inside smaller range (i.e.: [-1, 1]) instead of greater un-normalized ranges from your original input (say [0, 1000]). It also helps you get better, more precise results, as it helps solve problems like the vanishing gradient as well as adapting better to modern activation and optimizer functions. I also need to understand training input shape for LSTM as ECG signals are of variable length (9000 to 18000 samples) and usually classifier need fixed variable input. How can i handle such type of input in case of LSTM. This part is really important. You are correct, LSTM expects to receive inputs with a fixed shape, one that you know beforehand (in fact, any Deep Learning layer expects fixed shape inputs). This is also explained in the keras docs on Recurrent Layers where they say: Input shape 3D tensor with shape (batch_size, timesteps, input_dim). As we can see, it expects your data to have a number of timesteps as well as a dimension on each one of those timesteps (batch size is usually 1). To exemplify, suppose your input data consists of elements like: [[1,4],[2,3],[3,2],[4,1]]. Then, using a batch_size of 1, the shape of your data would be (1,4,2). As you have 4 timesteps, each with 2 features. So bottom line, you have to make sure that you pre-process you data so it has a fixed shape you can then pass to your LSTM layers. This one you will have to find out by yourself, as you know your data and problem better than we do. Maybe you can fix the samples you obtain from your signal, discarding some and keeping others so every signal is of the same length (if you say your signals are between 9k and 18k choosing 9000 could be the logical choice, discarding samples from the …
has comment: http://stackoverflow.com/comment/83108260
has comment: http://stackoverflow.com/comment/83109079
has comment: http://stackoverflow.com/comment/83109266
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/83108324
downvote count: 0
has comment: http://stackoverflow.com/comment/83109415
has comment: http://stackoverflow.com/comment/83110143
has comment: http://stackoverflow.com/comment/83109622

http://stackoverflow.com/q/48041482
type: Question
has title: Python Dataframe how to sum row values with groupby
tagged with: group-by
tagged with: dataframe
tagged with: pandas-groupby
tagged with: pandas
has body: I'm trying to group a column 'Over_Id' in Dataframe and also sum values of column runs_scored while grouping. If I use groupby, I loose my other columns Eg: ball.groupby(['Match_Id','Innings_Id','Over_Id'])['runs_scored'].sum() I was able to get my runs_scored column, but in a new Dataframe, not my actual as seen in the image. I can't merge, because my addition of runs_scored column is based on 3 columns. In short, I want only 1 entry for each Over_Id and it's corresponding runs_scored. How can I do that?
answer count: 1
accepted answer: http://stackoverflow.com/a/48041499
downvote count: 0
score: 1
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48041499

http://stackoverflow.com/q/48102142
tagged with: list
has answer: http://stackoverflow.com/a/48102232
downvote count: 2
upvote count: 4
answer count: 4
has title: Python Combine Repeating Elements
tagged with: sorting
has answer: http://stackoverflow.com/a/48102303
accepted answer: http://stackoverflow.com/a/48102232
score: 2
type: AnsweredQuestion
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/48102246
has body: I have a list of stings that have some repeating elements that I want to combine into a shorter list. The original list contents look something like this: lst = [['0.1', '0', 'RC', '100'], ['0.2', '10', 'RC', '100'], ['0.3', '5', 'HC', '20'], ['0.4', '5', 'HC', '20'], ['0.5', '5', 'HC', '20'], ['0.6', '5', 'HC', '20'], ['0.7', '5', 'HC', '20'], ['0.8', '5', 'HC', '20'], ['0.9', '10', 'RC', '100'], ['1.0', '0', 'RC', '100']] After running it through the function it would become: lst = [['0.1', '0', 'RC', '100'], ['0.2', '10', 'RC', '100'], ['0.3', '5', 'HC', '20'], ['0.9', '10', 'RC', '100'], ['1.0', '0', 'RC', '100']] The list will always have this general structure, so essentially I want to combine the list based on whether or not the last 3 columns are exactly the same. I want it to be a callable function so it would look some thing like: def combine_list(lst): if sublist[1:3] == next_sublist[1:3]: let.remove(next_sublist) My initial research on this showed many methods to remove a sublist based on its index, but that is not necessarily known before hand. I also found the re module, however I have never used it and unsure on how to implement it. Thank you in advanced
possible better answer: http://stackoverflow.com/a/48102203
type: Question
has answer: http://stackoverflow.com/a/48102203
tagged with: python

http://stackoverflow.com/a/48075007
has comment: http://stackoverflow.com/comment/83123715
type: Answer
has body: You encoder is fitted on refreshed_df which contains 10 columns and your refreshed_df1 contains only 4, literally what it is reported in the error. You have either to delete the columns not appearing on your refreshed_df1 or just fit your encoder to a new version of refreshed_df that only contains the 4 columns appearing in refreshed_df1 .
has comment: http://stackoverflow.com/comment/83124149
downvote count: 1
answers question: http://stackoverflow.com/q/48074462
has comment: http://stackoverflow.com/comment/83123746
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/83124475
has comment: http://stackoverflow.com/comment/83129983

http://stackoverflow.com/q/48126047
has comment: http://stackoverflow.com/comment/83234417
type: UnansweredQuestion
tagged with: python
has title: Python selenium: Need help in selection using ActionChains
score: 2
answer count: 0
upvote count: 2
tagged with: selenium
type: Question
has body: How to select these 2 devices using ActionChains? Click and hold some place near B1 and dragging the selection till some offset after B2 to select B1 and B2. Need to select 2 devices BL1 and BL2. Xpath for them: BL1: dropdown = driver.find_element_by_xpath( ".//*[@class='n9k healthscore90 sb-node']//*[@class='sb-node-display-text'][text()='BL-1']/..//*[@class='sb-node-display-icon']") BL2: dropdown1 = driver.find_element_by_xpath( ".//*[@class='n9k healthscore90 sb-node']//*[@class='sb-node-display-text'][text()='BL-2']/..//*[@class='sb-node-display-icon']") Tried: a = ActionChains(driver).move_to_element(dropdown).move_by_offset(-100,-100).click_and_hold().perform() This helps us to hold some place near B1. How to drag this point till B2 and select these devices? I tried the following, but got this error: actionChains = ActionChains(driver) actionChains.move_to_element(dropdown).move_by_offset(-100,-100).click_and_hold().perform() actionChains.move_to_element(dropdown1).perform() selenium.common.exceptions.WebDriverException: Message: UnknownError: Cannot press more then one button or an already pressed button.'UnknownError: Cannot press more then one button or an already pressed button.' when calling method: [wdIMouse::down] Since, this page is not a public site, I am not able to share the link.
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83230623

http://stackoverflow.com/q/48087556
tagged with: jinja2
tagged with: web-development-server
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/48087660
type: Question
has title: Unable to login to the admin panel in Django
has body: The site is working fine but when I switch to http://127.0.0.1:8000/admin/ it shows AttributeError at /admin/ .I tried to include MIDDLEWARE_CLASSES in the mysite/settings.py but to no avail . Here are some details : Django mysite.settings INSTALLED_APPS = [ 'personal', 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] http://127.0.0.1:8000/admin/ page :: Django mysite.urls :: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('personal.urls')), url(r'^blog/', include('blog.urls')), ] Am I missing something? Ask for more info if required . Thanks!
downvote count: 0
answer count: 1
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48087660
tagged with: django
upvote count: 1

http://stackoverflow.com/comment/83265360
type: AnswerComment
has text: @LokeshCherukuri What I meant is that if your code is not expecting to work with specifically an IO stream then you don't have to worry about creating one. In some other cases it could happen that your code is much better understood if it is clear that the stream of bytes comes from IO source. In such situation for the sake of more clarity and maybe compatibility, it's probably better to use the IO. Semantics are not necessarily concerned with performance, but rather clarity, so in the end you be the judge of what's more important.
comment on: http://stackoverflow.com/a/48134752
type: Comment
score: 1

http://stackoverflow.com/comment/83293332
score: 0
comment on: http://stackoverflow.com/q/48156043
type: Comment
type: QuestionComment
has text: @scarecrow I don't really know what you mean by "The end goal is go have all rows that condition is unoccupied in a column as long as the building, floor, and location matches. And time is greater then the occupied time." Can you just give us some sample input and output here?

http://stackoverflow.com/q/48166581
tagged with: python
has answer: http://stackoverflow.com/a/48166669
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48166669
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48167268
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/48166727
has comment: http://stackoverflow.com/comment/83312815
type: Question
upvote count: 1
tagged with: locate
has comment: http://stackoverflow.com/comment/83312689
has body: Consider following dataframe: m.transmission eff inv-cost fix-cost var-cost Site In Site Out Transmission Commodity Mid North hvac Elec 0.90 1650000 16500 0 Mid South hvac Elec 0.90 1650000 16500 0 North Mid hvac Elec 0.90 1650000 16500 0 North South hvac Elec 0.85 3000000 30000 0 South Mid hvac Elec 0.90 1650000 16500 0 South North hvac Elec 0.85 3000000 30000 0 I would like to filter values according to, if Site In == 'Mid' or Site Out == 'Mid' How would I do it? Before saying anything, this is not the desired outcome: m.transmission.loc'Mid' Site In Site Out Transmission Commodity Mid North hvac Elec Mid South hvac Elec because it just filters if Site In == 'Mid' Desired output would be (ofc with the columns; such as eff, inv-cost, fix-cost, var-cost): Site In Site Out Transmission Commodity Mid North hvac Elec Mid South hvac Elec North Mid hvac Elec South Mid hvac Elec EXTRA (Pdb) m.transmission.columns Index(['eff', 'inv-cost', 'fix-cost', 'var-cost', 'inst-cap', 'cap-lo', 'cap-up', 'wacc', 'depreciation'], dtype='object') (Pdb) m.transmission.index MultiIndex(levels=[['Mid', 'North', 'South'], ['Mid', 'North', 'South'], ['hvac'], ['Elec']], labels=[[0, 0, 1, 1, 2, 2], [1, 2, 0, 2, 0, 1], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]], names=['Site In', 'Site Out', 'Transmission', 'Commodity'])
favorite count: 0
tagged with: filter
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48166727
has title: Filtering Pandas Dataframe according to indices

http://stackoverflow.com/comment/83055790
comment on: http://stackoverflow.com/a/48037680
type: AnswerComment
has text: I came across 'g' yesterday but didn't have time to test it myself. Try looking up: from flask import Flask, g
score: 0
type: Comment

http://stackoverflow.com/q/48082138
type: AnsweredQuestion
has title: Is it possible to disable the zoom/pan window on a plotly.py candlestick chart?
tagged with: plotly
type: Question
has answer: http://stackoverflow.com/a/71167235
has body: I am creating a candlestick plot using plotly.py. I would like to have a horizontal split and place the candlestick data in the top split and some data curves in the bottom bottom split. I do not need panning and zooming and that lower section of the candlestick chart with the zoom/pan controls is getting in my way.
downvote count: 0
has answer: http://stackoverflow.com/a/48082201
has answer: http://stackoverflow.com/a/58494665
score: 13
possible better answer: http://stackoverflow.com/a/48731009
has answer: http://stackoverflow.com/a/48731009
favorite count: 0
has answer: http://stackoverflow.com/a/78359694
answer count: 5
accepted answer: http://stackoverflow.com/a/58494665
tagged with: python
upvote count: 13

http://stackoverflow.com/comment/83034687
comment on: http://stackoverflow.com/q/48032243
has text: are you overriding the `__str__()` function in the class? cuz it's the one that's called when you print the object or when the admin page renders it.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48087700
tagged with: python
has comment: http://stackoverflow.com/comment/83150664
has comment: http://stackoverflow.com/comment/83150356
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48089521
tagged with: calculated-columns
score: 0
tagged with: pandas
answer count: 1
has body: How do I go about adding a new column in a pandas dataframe, where I want the column to have a counter based on anothers column criteria, for example (desired output shown): WeekCounter DayofWeeek 1 Monday 1 Monday 1 Tuesday 1 Sunday 2 Monday 2 Wednesday 2 Thursday 2 Sunday 3 Monday 3 Monday 3 Monday How do I create a column that acts as a counter whenever the column value changes from Sunday to Monday? My original attempt would be a for loop with a nested if statement, but is there a more pandas-native manner in accomplishing this?
favorite count: 0
has title: Counter Column in Pandas DataFrame where it changes based on other column
has answer: http://stackoverflow.com/a/48089521

http://stackoverflow.com/comment/83245641
type: Comment
type: QuestionComment
has text: do you want some special pandas function or looping would work?
score: 0
comment on: http://stackoverflow.com/q/48133983

http://stackoverflow.com/comment/83144210
comment on: http://stackoverflow.com/q/48080239
has text: I tried it already and got:ValueError: could not broadcast input array from shape (11,1) into shape (11)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83278782
comment on: http://stackoverflow.com/q/48150251
type: QuestionComment
score: 0
has text: Can you rename hashsets? if so, build a new one, and switch the name.
type: Comment

http://stackoverflow.com/a/52878668
answers question: http://stackoverflow.com/q/48016629
score: 0
has body: print('Max value:', df.stack().max()) print('Parameters :', df.stack().idxmax()) This is the best way imho.
type: Answer

opencv
tags question: http://stackoverflow.com/q/48087661
tags question: http://stackoverflow.com/q/48118893
tags question: http://stackoverflow.com/q/48169528
type: Tag
tags question: http://stackoverflow.com/q/48070612
tags question: http://stackoverflow.com/q/48109899
tags question: http://stackoverflow.com/q/48103802
tags question: http://stackoverflow.com/q/48057268
tags question: http://stackoverflow.com/q/48114302
tags question: http://stackoverflow.com/q/48043090
tags question: http://stackoverflow.com/q/48098785
tags question: http://stackoverflow.com/q/48065702
tags question: http://stackoverflow.com/q/48072587
tags question: http://stackoverflow.com/q/48160105
tags question: http://stackoverflow.com/q/48081791
tags question: http://stackoverflow.com/q/48171436
tags question: http://stackoverflow.com/q/48088193
tags question: http://stackoverflow.com/q/48103432
tags question: http://stackoverflow.com/q/48129595
tags question: http://stackoverflow.com/q/48046864
tags question: http://stackoverflow.com/q/48025689
tags question: http://stackoverflow.com/q/48049886
tags question: http://stackoverflow.com/q/48114148
tags question: http://stackoverflow.com/q/48163539
tags question: http://stackoverflow.com/q/48125095
tags question: http://stackoverflow.com/q/48126335
tags question: http://stackoverflow.com/q/48087613
tags question: http://stackoverflow.com/q/48085005
tags question: http://stackoverflow.com/q/48134525
tags question: http://stackoverflow.com/q/48029089
tags question: http://stackoverflow.com/q/48055628
tags question: http://stackoverflow.com/q/48093358
tags question: http://stackoverflow.com/q/48019058
tags question: http://stackoverflow.com/q/48076358
tags question: http://stackoverflow.com/q/48023127
tags question: http://stackoverflow.com/q/48069356
tags question: http://stackoverflow.com/q/48158912
tags question: http://stackoverflow.com/q/48139889
tags question: http://stackoverflow.com/q/48037197
tags question: http://stackoverflow.com/q/48061623
tags question: http://stackoverflow.com/q/48158601
tags question: http://stackoverflow.com/q/48040138
tags question: http://stackoverflow.com/q/48162710
tags question: http://stackoverflow.com/q/48040323
tags question: http://stackoverflow.com/q/48055817
tags question: http://stackoverflow.com/q/48144883
tags question: http://stackoverflow.com/q/48160827
tag name: opencv
tags question: http://stackoverflow.com/q/48021226
tags question: http://stackoverflow.com/q/48055368
tags question: http://stackoverflow.com/q/48101474
tags question: http://stackoverflow.com/q/48052032
tags question: http://stackoverflow.com/q/48046865
tags question: http://stackoverflow.com/q/48049601
tags question: http://stackoverflow.com/q/48051769
tags question: http://stackoverflow.com/q/48124891
tags question: http://stackoverflow.com/q/48090903
tags question: http://stackoverflow.com/q/48034370
tags question: http://stackoverflow.com/q/48145249
tags question: http://stackoverflow.com/q/48032299
tags question: http://stackoverflow.com/q/48035930
tags question: http://stackoverflow.com/q/48109650
tags question: http://stackoverflow.com/q/48158187
tags question: http://stackoverflow.com/q/48063525
tags question: http://stackoverflow.com/q/48163837
tags question: http://stackoverflow.com/q/48088534
tags question: http://stackoverflow.com/q/48076009
tags question: http://stackoverflow.com/q/48099343
tags question: http://stackoverflow.com/q/48106513
tags question: http://stackoverflow.com/q/48136978
tags question: http://stackoverflow.com/q/48021459
tags question: http://stackoverflow.com/q/48033369
tags question: http://stackoverflow.com/q/48154642
tags question: http://stackoverflow.com/q/48020440
tags question: http://stackoverflow.com/q/48138778
tags question: http://stackoverflow.com/q/48090962
tags question: http://stackoverflow.com/q/48108977
tags question: http://stackoverflow.com/q/48123342
tags question: http://stackoverflow.com/q/48024578

http://stackoverflow.com/q/48144067
favorite count: 0
has comment: http://stackoverflow.com/comment/83266543
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83266642
has title: PYTHON- Merging CSV file based on same value in colunm 1
tagged with: merge
has body: I have 2 CSV files, both with thousands of lines each, which I would like to merge and output to a new file (results.csv). I have looked here at other answers but now need assistance. Please note: -Neither file have headers - I do NOT want to use PANDA File 1 (file.csv) contains: 041, 2017111, 50501342, 20058987, 200765893, PPP, PLUS, D, NSW 455, 2017082, 50513457, 20068678, 200476768, BBB, LONG, A, NSW 178, 2017976, 50586956, 20089765, 200886565, LLL, PLUS, D, QLD File 2 (file2.csv) contains: 019, 0.000, 20150907, 20170308 041, 0.000, 20160806, 20170504 455, 147.533, 20140402, 20170506 Expected (results.csv) output: 041, 2017111, 50501342, 20058987, 200765893, PPP, PLUS, D, NSW, 0.000, 20160806, 20170504 455, 2017082, 50513457, 20068678, 200476768, BBB, LONG, A, NSW, 147.533, 20140402, 20170506 So the code will sort through and join when column 1 is the same. So far I have tried the below but the output is in the wrong format: f1 = open(file.csv', 'r') f2 = open(file2.csv', 'r') f3 = open('results.csv', 'w') c1 = csv.reader(f1) c2 = csv.reader(f2) c3 = csv.writer(f3) file2 = list(c2) for file1_row in c1: row = 1 found = False results_row = file1_row for file2_row in file2: x = file2_row[1:] if file1_row[0] == file2_row[0]: results_row.append(x) found = True break row += 1 if not found: results_row.append('Not found') c3.writerow(results_row) f1.close() f2.close() f3.close() Any help will be appreciated. Thanks
downvote count: 1
has answer: http://stackoverflow.com/a/48144091
type: Question
has comment: http://stackoverflow.com/comment/83266338
score: 0
tagged with: http://stackoverflow.com/tag/csv
answer count: 1

http://stackoverflow.com/comment/83293663
score: 0
has text: We use ATOMIC_REQUESTS in settings.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48154246

cx-oracle
tags question: http://stackoverflow.com/q/48166813
tags question: http://stackoverflow.com/q/48100774
type: Tag
tag name: cx-oracle

http://stackoverflow.com/a/48045142
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48045072
downvote count: 0
has body: Template inherits from a metaclass. The metaclass's __init__ method performs some setup using Template's delimiter. (Specifically, it creates the regexes used to match delimited text.) Changing delimiter after this setup has taken place does not re-initialise the setup, hence you need to use a subclass so that the desired value of delimiter is used.
type: Answer

http://stackoverflow.com/comment/83261715
type: QuestionComment
has text: [this](https://stackoverflow.com/a/773472/6689249)
comment on: http://stackoverflow.com/q/48141841
score: 1
type: Comment

http://stackoverflow.com/q/48173347
has answer: http://stackoverflow.com/a/48174325
has title: Do Django Model Managers require using=self._db
score: 10
tagged with: database
upvote count: 10
has body: In working with the Django user model I've noticed model managers include a using=self._db parameter when acting on a database. If I'm only using a single database, is this necessary? What does using=self._db do other than specify the database. Is this specified as a fail-safe in the event another database is added?
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48174325
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: django
type: Question

http://stackoverflow.com/q/48159102
possible better answer: http://stackoverflow.com/a/48159143
favorite count: 0
has answer: http://stackoverflow.com/a/48159143
tagged with: operating-system
accepted answer: http://stackoverflow.com/a/48159190
has body: I am trying to write a Python script that creates a directory and saves some images into that directory. Please check the below piece of code, person = 0 # Increase this by one every iteration if os.path.isdir('./training__data/s{str(person)}') is False: # if, for ex. s0 does not exist os.mkdir('./training__data/s' + str(person)) # create s0, for ex. for (x,y,w,h) in faces: samples += 1 person += 1 cv2.imwrite("training__data/s{str(person)}" + str(samples) + ".png", \ gray[y:y+h, x:x+w]) What I am trying to achieve is that I want to create a file tree described below, -- training__data/ -- s0 -- 0.png -- 1.png -- n.png # goes until the nth picture -- s1 -- 0.png -- 1.png -- n.png -- . # goes until the nth directory So my question is how can I name the directories as s0, s1, s2, etc.? I tried adding this --> s{str(person)} which did not resolve the issue. Thanks for your help in advance, Regards.
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has title: Dynamically create directories and files based on some value as part of there name
has answer: http://stackoverflow.com/a/48159190
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/83139900
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48082725
has text: Is 'Y' not a list?

http://stackoverflow.com/comment/83159197
comment on: http://stackoverflow.com/a/48080569
type: AnswerComment
type: Comment
has text: You don't need the `is True` part - `isinstance()` returns a bool already. As a general rule, all python objects (hence all python expressions since an expression always evals to an object) have a truth value, so there's usually no reason to _explicitely_ test against `True` or `False`. Also, `is` is the identity operator and should not be used for value equality testing. For example, `1 is True` is false, while `1 == True` is true. This can lead to unexpected results when combined with the logical ` and` and `or` operators which don't yield booleans (read the doc about it for more)
score: 0

http://stackoverflow.com/a/57493455
downvote count: 0
has comment: http://stackoverflow.com/comment/107777852
type: Answer
has comment: http://stackoverflow.com/comment/101802517
answers question: http://stackoverflow.com/q/48163641
has body: My problem was that I was trying to import before the setup was ran. Here's my solution: make the import after the setup: import django # some variable declarations world_mapping = { 'osm_id': 'osm_id', } if __name__ == '__main__': django.setup() # import AFTER setup from app.models import WorldBorder # from now I can access WorldBorder!!
upvote count: 9
score: 9
has comment: http://stackoverflow.com/comment/107656016

http://stackoverflow.com/q/48040691
tagged with: python-3.x
has title: Prioritise celery queues/tasks
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
tagged with: celery
type: Question
has answer: http://stackoverflow.com/a/48043450
has body: I have the basic understanding of celery and that how it works. In my current project, I have run into a need to prioritise tasks. I mean if there are two kinds of tasks, say A and B in the celery queue, celery should prioritise task B irrespective of which task is on the head of the queue. Is there a way to do that? Queue prioritisation is also fine with me. Meaning that I can make 2 different queues, say high_priority_queue and low_priority_queue, and celery should always execute the tasks in high_priority_queue first and then go towards low_priority_queue. I also know the fact that we can assign different workers to the two queues, but that would mean that tasks in both the queues are being executed concurrently. I need the tasks in the high_priority_queue to be executed first. Any ideas? Thanks
linked to: http://stackoverflow.com/q/47979831
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48043450
favorite count: 0

deployment
tags question: http://stackoverflow.com/q/48159326
tag name: deployment
tags question: http://stackoverflow.com/q/48128419
type: Tag

scrapy
tags question: http://stackoverflow.com/q/48031314
tags question: http://stackoverflow.com/q/48051879
tags question: http://stackoverflow.com/q/48055590
tags question: http://stackoverflow.com/q/48066352
tags question: http://stackoverflow.com/q/48171609
tags question: http://stackoverflow.com/q/48101662
tags question: http://stackoverflow.com/q/48015404
tags question: http://stackoverflow.com/q/48161575
tags question: http://stackoverflow.com/q/48086330
tags question: http://stackoverflow.com/q/48122018
tags question: http://stackoverflow.com/q/48026031
tags question: http://stackoverflow.com/q/48088582
tags question: http://stackoverflow.com/q/48122080
tags question: http://stackoverflow.com/q/48065020
tags question: http://stackoverflow.com/q/48129892
tags question: http://stackoverflow.com/q/48054053
tags question: http://stackoverflow.com/q/48046391
tags question: http://stackoverflow.com/q/48028931
tags question: http://stackoverflow.com/q/48042872
tags question: http://stackoverflow.com/q/48109678
tags question: http://stackoverflow.com/q/48051158
tags question: http://stackoverflow.com/q/48140281
tags question: http://stackoverflow.com/q/48127226
tags question: http://stackoverflow.com/q/48085607
tags question: http://stackoverflow.com/q/48022598
tags question: http://stackoverflow.com/q/48028041
tags question: http://stackoverflow.com/q/48055395
tags question: http://stackoverflow.com/q/48164675
tags question: http://stackoverflow.com/q/48145427
tags question: http://stackoverflow.com/q/48114098
tags question: http://stackoverflow.com/q/48072862
tag name: scrapy
tags question: http://stackoverflow.com/q/48047024
tags question: http://stackoverflow.com/q/48054233
tags question: http://stackoverflow.com/q/48069410
tags question: http://stackoverflow.com/q/48146944
tags question: http://stackoverflow.com/q/48050573
tags question: http://stackoverflow.com/q/48054343
tags question: http://stackoverflow.com/q/48103402
tags question: http://stackoverflow.com/q/48030717
tags question: http://stackoverflow.com/q/48033398
type: Tag
tags question: http://stackoverflow.com/q/48065361
tags question: http://stackoverflow.com/q/48021091
tags question: http://stackoverflow.com/q/48047466
tags question: http://stackoverflow.com/q/48085924

http://stackoverflow.com/comment/116310272
type: AnswerComment
has text: Wow! I didn't know `nan != nan`. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/48171528
score: 0

http://stackoverflow.com/comment/83066083
has text: Possible duplicate of [list index out of range in python](https://stackoverflow.com/questions/5308022/list-index-out-of-range-in-python)
score: 1
comment on: http://stackoverflow.com/q/48047254
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83099629
comment on: http://stackoverflow.com/q/48062717
has text: If you notice, the code itself isn't drawing the same thing over and over, as It randomly will set its own direction and forward values, there is no way for me to set a shorter 'forward' and actually still keep it in screen, as it may choose to just go forward multiple times the same number. The directional values will not make it turn; etc. also I want the window set as a tkinter screen value, not a set number of pixels, so on different computers, this could vary. I want for it to know, that if it is hitting the edge of the canvas, it needs to hit another value and turn some other way. How?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83214511
has text: Are those growth rates instantaneous growth rates, i.e. derivative values, or are they discrete? What is the time unit for those growth rates, e.g. starting at 200% per hour, per day, per year or other?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48118345

http://stackoverflow.com/q/48020089
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48020327
tagged with: list
has comment: http://stackoverflow.com/comment/83009285
has answer: http://stackoverflow.com/a/48020327
type: Question
accepted answer: http://stackoverflow.com/a/48020212
has body: I have a input list, n = [0, 6, 12, 18, 24, 30, 36, 42, 48] # Here, the list is multiples of 6 # but need not always be, could be of different numbers or unrelated. Now I would like to generate pair of numbers from the list so the output is, output = [(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)] I have below snippet to get it done. zip([(i+1) for i in n[:-1]], n[1:]) Just out of curious, I would like to know the other approaches than what I have!
has comment: http://stackoverflow.com/comment/83009203
has title: Finding combinations pairs of list items forward
has answer: http://stackoverflow.com/a/48020438
has answer: http://stackoverflow.com/a/48032339
favorite count: 0
answer count: 5
has comment: http://stackoverflow.com/comment/83009301
has answer: http://stackoverflow.com/a/48020212
upvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/83009278
has answer: http://stackoverflow.com/a/48047032
downvote count: 1
tagged with: combinations
score: 2

http://stackoverflow.com/comment/83034044
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48031599
has text: @taesu I did syncing(in windows settings) but the problem happens
score: 0

http://stackoverflow.com/a/48111335
type: Answer
has comment: http://stackoverflow.com/comment/83225203
answers question: http://stackoverflow.com/q/48111231
has comment: http://stackoverflow.com/comment/83226999
score: 0
has body: If you only want to exclude all the laps in AUS_2016 that appear in df_pitLaps that is simply done by: AUS_2016[~AUS_2016['lap'].isin(df_pitLaps['lap'].unique())]

http://stackoverflow.com/comment/83177367
type: AnswerComment
comment on: http://stackoverflow.com/a/48071714
score: 0
type: Comment
has text: space complexity and using those data structures will consume a lot of memory? Or because SQL has indexing option so maybe that already serve as a grouping mechanism?

http://stackoverflow.com/a/48086840
answers question: http://stackoverflow.com/q/48086820
has body: A combination of zip() and itertools.chain() would do it: In [1]: from itertools import chain In [2]: [list(chain(*lists)) for lists in zip(*a)] Out[2]: [[0, 1, 2, 3, 4, 5], [10, 11, 12, 13, 14, 15]]
score: 3
downvote count: 0
type: AcceptedAnswer
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/48086820

http://stackoverflow.com/comment/83283202
comment on: http://stackoverflow.com/q/48152343
type: Comment
type: QuestionComment
score: 1
has text: I not sure, but try `if i == pick` instead of `if i in pick`, because `pick` is `int` and not iterable object.

http://stackoverflow.com/a/48039656
downvote count: 0
has comment: http://stackoverflow.com/comment/83049761
answers question: http://stackoverflow.com/q/48039581
accepted answer of: http://stackoverflow.com/q/48039581
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: The following nested comprehension should work: tags = [tag for v in raw_data['list'].values() for tag in v.get('tags', {})]
score: 2

http://stackoverflow.com/comment/83266746
type: Comment
score: 0
has text: @shoaibqureshi what are you trying to calculate using this function, can you add that part in the question
comment on: http://stackoverflow.com/q/48144281
type: QuestionComment

http://stackoverflow.com/a/53374933
has comment: http://stackoverflow.com/comment/114529321
has comment: http://stackoverflow.com/comment/97569213
score: 265
has comment: http://stackoverflow.com/comment/97566787
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48152674
has comment: http://stackoverflow.com/comment/97569079
has comment: http://stackoverflow.com/comment/97565498
has comment: http://stackoverflow.com/comment/107262577
has comment: http://stackoverflow.com/comment/120294473
has comment: http://stackoverflow.com/comment/97566375
has comment: http://stackoverflow.com/comment/97563743
upvote count: 266
has body: As it hasn't been proposed here, I'm adding a method using torch.device, as this is quite handy, also when initializing tensors on the correct device. # setting device on GPU if available, else CPU device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') print('Using device:', device) print() #Additional Info when using cuda if device.type == 'cuda': print(torch.cuda.get_device_name(0)) print('Memory Usage:') print('Allocated:', round(torch.cuda.memory_allocated(0)/1024**3,1), 'GB') print('Cached: ', round(torch.cuda.memory_reserved(0)/1024**3,1), 'GB') Edit: torch.cuda.memory_cached has been renamed to torch.cuda.memory_reserved. So use memory_cached for older versions. Output: Using device: cuda Tesla K80 Memory Usage: Allocated: 0.3 GB Cached: 0.6 GB As mentioned above, using device it is possible to: To move tensors to the respective device: torch.rand(10).to(device) To create a tensor directly on the device: torch.rand(10, device=device) Which makes switching between CPU and GPU comfortable without changing the actual code. Edit: As there has been some questions and confusion about the cached and allocated memory I'm adding some additional information about it: torch.cuda.max_memory_cached(device=None) Returns the maximum GPU memory managed by the caching allocator in bytes for a given device. torch.cuda.memory_allocated(device=None) Returns the current GPU memory usage by tensors in bytes for a given device. You can either directly hand over a device as specified further above in the post or you can leave it None and it will use the current_device(). Additional note: Old graphic cards with Cuda compute capability 3.0 or lower may be visible but cannot be used by Pytorch! Thanks to hekimgil for pointing this out! - "Found GPU0 GeForce GT 750M which is of cuda capability 3.0. PyTorch no longer supports this GPU because it is too old. The minimum cuda capability that we support is 3.5."
has comment: http://stackoverflow.com/comment/114539414

http://stackoverflow.com/comment/83213043
type: QuestionComment
has text: What is the type of `marks` before you do `str(marks)` inside of your call to `.format()`? What's the code for the stored procedure `s4u155_examcorrector.submit_result`? What code produced that Python debugging output? What code produced the MySQL output?
comment on: http://stackoverflow.com/q/48118224
score: 0
type: Comment

http://stackoverflow.com/a/48110982
score: 1
has comment: http://stackoverflow.com/comment/83509462
upvote count: 1
downvote count: 0
has body: Okey, Let me correct some problem I found with your code! First, you need to use FormData object from javascript in order to send bytes data to the server (your compressed image ) in this case. to do that I have added the following code : console.log("Starting Upload..."); var formData = new FormData(); formData.append("fileToUpload", result_image_obj.src); and now you can easily now send it via ajax : $.ajax({ url:"/users/api/v1/uploadimage", type:'POST', data:formData, processData: false, // important contentType: false, // important enctype: 'multipart/form-data', error:function(){ console.log("upload error") }, success:function(data){ console.log(data) console.log("upload success") } }) Note That you have to send the formData object as parameter of data in your ajax and with enctype : 'multipart/form-data'. Now in your flask server use this code : @app.route('/users/api/v1/uploadimage', methods=['GET', 'POST']) def uploadimage(): """ this will try to upload an image """ print "In uploadimage()" try: a_file = request.get_data(cache=False, as_text=False, parse_form_data=False) print "Filename", a_file except Exception as exce: print str(exce) return "True" return "oke" as said in here the get_data method This reads the buffered incoming data from the client into one bytestring. By default this is cached but that behavior can be changed by setting cache to False now the second problem is to find how to save that string-byte file as an image on your server : still looking how to do that will add it soon.
has comment: http://stackoverflow.com/comment/83343234
type: Answer
answers question: http://stackoverflow.com/q/48089942

nlp
tags question: http://stackoverflow.com/q/48053823
tags question: http://stackoverflow.com/q/48049104
tags question: http://stackoverflow.com/q/48135562
tags question: http://stackoverflow.com/q/48090426
tags question: http://stackoverflow.com/q/48112057
tags question: http://stackoverflow.com/q/48140848
tags question: http://stackoverflow.com/q/48165486
tags question: http://stackoverflow.com/q/48145658
tags question: http://stackoverflow.com/q/48159755
tags question: http://stackoverflow.com/q/48074642
tags question: http://stackoverflow.com/q/48057991
tags question: http://stackoverflow.com/q/48153854
tags question: http://stackoverflow.com/q/48049619
tags question: http://stackoverflow.com/q/48058311
tags question: http://stackoverflow.com/q/48117508
tags question: http://stackoverflow.com/q/48145777
tags question: http://stackoverflow.com/q/48115965
tags question: http://stackoverflow.com/q/48158356
tags question: http://stackoverflow.com/q/48137617
tags question: http://stackoverflow.com/q/48053981
tags question: http://stackoverflow.com/q/48028391
tags question: http://stackoverflow.com/q/48079577
tags question: http://stackoverflow.com/q/48066774
tags question: http://stackoverflow.com/q/48019843
tag name: nlp
type: Tag
tags question: http://stackoverflow.com/q/48143769
tags question: http://stackoverflow.com/q/48129527
tags question: http://stackoverflow.com/q/48026532

http://stackoverflow.com/q/48028234
upvote count: 3
has comment: http://stackoverflow.com/comment/83026494
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/83026533
tagged with: python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83026589
has answer: http://stackoverflow.com/a/48028643
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83026574
score: 3
downvote count: 0
has title: Sum based on date range in two separate columns
type: Question
has comment: http://stackoverflow.com/comment/83026577
has comment: http://stackoverflow.com/comment/83026518
has answer: http://stackoverflow.com/a/48029072
accepted answer: http://stackoverflow.com/a/48029072
has answer: http://stackoverflow.com/a/48028829
possible better answer: http://stackoverflow.com/a/48028643
has body: I want to sum all the value in one column based on a range of date in two column: Start_Date Value_to_sum End_date 2017-12-13 2 2017-12-13 2017-12-13 3 2017-12-16 2017-12-14 4 2017-12-15 2017-12-15 2 2017-12-15 A simple groupby won't do it since it would only add the value for a specific date. We could do an embeeded for loop but it would take forever to run: unique_date = carry.Start_Date.unique() carry = pd.DataFrame({'Date':unique_date}) carry['total'] = 0 for n in tqdm(range(len(carry))): tr = data.loc[data['Start_Date'] &gt;= carry['Date'][n]] for i in tr.index: if carry['Date'][n] &lt;= tr['End_date'][i]: carry['total'][n] += tr['Value_to_sum'][i] Something like that would work but like I said would take forever. The expected output is unique date with the total for each day. Here it would be 2017-12-13 = 5, 2017-12-14 = 7, 2017-12-15 = 9. How do I compute the sum based on the date ranges?
has comment: http://stackoverflow.com/comment/83026526

http://stackoverflow.com/comment/83298438
has text: a tiny tune-up: `a.astype(str).groupby(a.number, as_index=False).agg('; '.join)`
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48159402
type: Comment

http://stackoverflow.com/q/48154642
has comment: http://stackoverflow.com/comment/83288692
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83350354
has answer: http://stackoverflow.com/a/48155164
linked to: http://stackoverflow.com/q/44439555
downvote count: 1
has body: I want to count number of dots in an image. The image looks like I referred to this SOF link count colored dots in image But this is for colored links , So anyone here can guide me over how to handle this and count black dots out of white back.
type: Question
has comment: http://stackoverflow.com/comment/83288415
upvote count: 5
score: 4
answer count: 2
accepted answer: http://stackoverflow.com/a/48155313
favorite count: 0
has comment: http://stackoverflow.com/comment/83289458
has title: How to count number of dots in an image using python and Opencv?
tagged with: python
has answer: http://stackoverflow.com/a/48155313
possible better answer: http://stackoverflow.com/a/48155164
has comment: http://stackoverflow.com/comment/83289409

http://stackoverflow.com/comment/83080495
comment on: http://stackoverflow.com/q/48051319
has text: Has your question been answered?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83140829
type: QuestionComment
comment on: http://stackoverflow.com/q/48083114
score: 1
has text: Did you look at the resulting file? You're saving in *text* format: a small number will need fewer (decimal) digits than a larger number. There's no basis for assuming 8 bytes per entry.
type: Comment

http://stackoverflow.com/a/48055958
has comment: http://stackoverflow.com/comment/83084352
has comment: http://stackoverflow.com/comment/83098660
score: 5
accepted answer of: http://stackoverflow.com/q/48055942
upvote count: 5
answers question: http://stackoverflow.com/q/48055942
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: In a1, you're iterating over a string and converting each of its characters into an int, the result is an iterator of ints, check the documentation for map: list(a1) # use `list()` to consume the iterator =&gt; [2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 1, 1] In a2, you're converting a string into an int, the result is an int. They're very different things! a2 =&gt; 222211112211 That's why you can iterate over a1, because it's an iterator, not an int. And that's why you can't iterate over a2, it's just an int.

http://stackoverflow.com/q/48118426
tagged with: python
score: -2
has body: To be more specific, given a string as such: XOOOO.XO. I need to see how many instances of the format "X", followed by any number of "O"'s, followed by a "." is there in the string. I also would need to get the index of the period. Examples of strings I would need to find: XO. XOO. XOOO. Non-examples: X.O X..O X.OOOO. OX.
has comment: http://stackoverflow.com/comment/83213298
accepted answer: http://stackoverflow.com/a/48118666
downvote count: 3
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83213523
has title: How do you find a series of characters in python?
has answer: http://stackoverflow.com/a/48118666
type: AnsweredQuestion
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83215399

http://stackoverflow.com/a/48102203
has comment: http://stackoverflow.com/comment/83179912
has comment: http://stackoverflow.com/comment/83179776
has comment: http://stackoverflow.com/comment/83179831
type: Answer
answers question: http://stackoverflow.com/q/48102142
has comment: http://stackoverflow.com/comment/83179828
score: 2
has comment: http://stackoverflow.com/comment/83179707
has body: Maybe just use a set to keep track of duplicates? def combine_list(lst): out = [] seen = set() for item in lst: if not tuple(item[1:]) in seen: out.append(item) seen.add(tuple(item[1:])) return out Lists are a mutable data structure. And so there is no guarantee that the contents of a list does not change over time. That means it cannot be used in a hashing function (which the set uses). The tuple, on the other hand, is immutable, and hence hashable.
upvote count: 3
has comment: http://stackoverflow.com/comment/83179743
downvote count: 1

http://stackoverflow.com/q/48015460
has title: Replace when n or less consecutive values are found
has answer: http://stackoverflow.com/a/48015601
has answer: http://stackoverflow.com/a/48015517
has body: this is perhaps a very simple question I have a list that looks like this: a=[0,1,1,2,3,2,1,2,0,3,4,1,1,1,1,0,0,0,0,4,5,1,1,1,3,2,0,2,1,1,3,4,1] I am struggling to find a simple python code that replaces when n or less consecutive 1s are found to 0s and creates a new list with the new values So if n = 2 b = [0,0,0,2,3,2,0,2,0,3,4,1,1,1,1,0,0,0,0,4,5,1,1,1,3,2,0,2,0,0,3,4,0] if n = 3 b = [0,0,0,2,3,2,0,2,0,3,4,1,1,1,1,0,0,0,0,4,5,0,0,0,3,2,0,2,0,0,3,4,0] I have highlighted the new replaces values in each example
favorite count: 0
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48015652
upvote count: 2
has answer: http://stackoverflow.com/a/48015656
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48015573
downvote count: 3
score: -1
tagged with: replace
possible better answer: http://stackoverflow.com/a/48015601
accepted answer: http://stackoverflow.com/a/48015573

http://stackoverflow.com/a/48095141
has comment: http://stackoverflow.com/comment/83166618
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83167004
type: Answer
has comment: http://stackoverflow.com/comment/83168435
has body: Python has a mechanism to let multiple variables refer to the same object, with: a = b = c = [[] for e in range(6)] But you probably do not want that, since now a, b and c refer to the very same list. So if we append to a, then that change is also reflected in b and c. We can however use iterable unpacking with: a, b, c = [[[] for e in range(6)] for _ in range(3)] So here we construct a list that contains three lists, and we then unpack that list in three variables, such that each variable obtains its own sublist. Or in general, if you have a certain expression that needs to be evaluated n times, and then assigned to n variables, you can use: x1, x2, xn = [&lt;expr&gt; for _ in range(n)] Here &lt;expr&gt; should of course be replaced with a real expression, and variables xi with real variables.
upvote count: 6
has comment: http://stackoverflow.com/comment/83165248
has comment: http://stackoverflow.com/comment/83168385
accepted answer of: http://stackoverflow.com/q/48095092
has comment: http://stackoverflow.com/comment/83170337
score: 6
has comment: http://stackoverflow.com/comment/83169553
answers question: http://stackoverflow.com/q/48095092
has comment: http://stackoverflow.com/comment/83168553
has comment: http://stackoverflow.com/comment/83169287

http://stackoverflow.com/q/48120556
downvote count: 1
type: Question
has body: noob here having a heck of time trying to click on a webelement within LinkedIn with no success. To begin here is the source code I'm dealing with: this is my login: from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException import urllib, os, urllib.request import time driver = webdriver.Safari() usrName = 'your_email' pssWrd = "your_password" driver.maximize_window() driver.get("https://www.linkedin.com/uas/login?") driver.find_element_by_name('session_key').send_keys(usrName) driver.find_element_by_class_name('password').send_keys(pssWrd) driver.find_element_by_name('signin').click() time.sleep(15) driver.get("https://www.linkedin.com/search/results/people/facetNetwork=%5B%22S%22%5D&amp;keywords=software%20engineers&amp;origin=FACETED_SEARCH") this is the block that I'm trying to find. &lt;button aria-label="Connect with LJ Wilson" class="search-result__actions--primary button-secondary-medium m5" data-ember-action="" data-ember-action-5373="5373" data-is-animating-click="true"&gt; Connect &lt;/button&gt; I can login and and navigate to the page just fine (after you set a sleep for linkedIn to load past a firewall), but I have done everything to try to click on the button with no success. I've tried: driver.find_element_by_xpath("//button[@class='search-result__actions--primary button-secondary-medium m5']"[1]).click() and driver.find_element_by_xpath("//button[contains(text()="Connect])).click() nothing.... any help would be much appreciated. I haven't been able to click on LinkedIn buttons or elements since it changed it's platform around this time in 2016. These are the 3 errors I'm getting: An element command could not be completed because the element is not visible on the page. An element could not be located on the page …
possible better answer: http://stackoverflow.com/a/48120810
has answer: http://stackoverflow.com/a/49261852
has answer: http://stackoverflow.com/a/48120958
has title: Clicking a LinkedIn button using selenium (python)
has comment: http://stackoverflow.com/comment/83218224
accepted answer: http://stackoverflow.com/a/48215772
tagged with: linkedin-api
has comment: http://stackoverflow.com/comment/83218886
favorite count: 0
upvote count: 2
tagged with: python
answer count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83218796
score: 1
has answer: http://stackoverflow.com/a/48120810
has answer: http://stackoverflow.com/a/48215772
tagged with: selenium

http://stackoverflow.com/comment/83262830
has text: (I thought you were looking for an idea to replace `level1` (/2/3) - which *may* be a good idea)
comment on: http://stackoverflow.com/q/48141655
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/70503958
has body: Add fields like this: comment = models.TextField() starting_time = models.TimeField() ending_time = models.TimeField() date = models.DateField() you need to add parentheses in the end.
answers question: http://stackoverflow.com/q/48083587
type: Answer
score: 0

http://stackoverflow.com/q/48096812
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48274159
tagged with: keras
favorite count: 0
has body: Introduction I would like to implement a custom loss function to Keras. I want to do this, because I am not happy with the current result for my dataset. I think the reason for this is because currently the built-in loss functions focuses on the whole dataset. And I just want to focus on the top values in my dataset. That is why I came up with the following idea for a custom loss function: Custom Loss Function Idea The custom loss function should take the top 4 predictions with the highest value and subtract it with the corresponding true value. Then take the absolute value from this subtraction, multiply it with some weights and add it to the total loss sum. For better understanding of this custom loss function I programmed it with a list input. Hopefully it is better understandable with this example: The following example calculates the loss = 4*abs(0.7-0.5)+3*abs(0.5-0.7)+2*abs(0.4-0.45) +1*abs(0.4-0.3) = 1.6 for i=0 Then it divides it by div_top which in this example is 10 (for i=0 it would be 0.16), repeats everything for all other i and finally takes the average over all samples. top = 4 div_top = 0.5*top*(top+1) def own_loss(y_true, y_pred): loss_per_sample = [0]*len(y_pred) for i in range(len(y_pred)): sorted_pred, sorted_true = (list(t) for t in zip(*sorted(zip(y_pred[i], y_true[i])))) for k in range(top): loss_per_sample[i] += (top-k)*abs(sorted_pred[-1-k]-sorted_true[-1-k]) loss_per_sample = [t/div_top for t in loss_per_sample] return sum(loss_per_sample)/len(loss_per_sample) y_pred = [[0.1, 0.4, 0.7, 0.4, 0.4, 0.5, 0.3, 0.2], [0.3, 0.8, 0.5, 0.3, 0.1, 0.0, 0.1, 0.5], [0.5, 0.6, 0.6, 0.8, 0.3, 0.6, 0.7, 0.1]] y_true = [[0.2, 0.45, 0.5, 0.3, 0.4, 0.7, 0.22, 0.1], [0.4, 0.9, 0.3, 0.0, 0.2, 0.1, 0.11, 0.8], [0.4, 0.7, 0.4, 0.3, 0.4, 0.7, 0.6, 0.05]] print(own_loss(y_true, y_pred)) # Output is 0.196667 Implementation to Keras I would like to use this function in Keras as a custom loss function. This would look like this: import numpy as np from keras.datasets…
linked to: http://stackoverflow.com/q/43576922
upvote count: 5
tagged with: python
type: AnsweredQuestion
tagged with: backend
tagged with: tensorflow
type: Question
has title: How can I sort the values in a custom Keras / Tensorflow Loss Function?
tagged with: loss-function
accepted answer: http://stackoverflow.com/a/48274159
score: 5

http://stackoverflow.com/q/48172439
accepted answer: http://stackoverflow.com/a/48172508
type: Question
type: AnsweredQuestion
tagged with: python
tagged with: pygame
score: 0
tagged with: bullet
answer count: 1
has answer: http://stackoverflow.com/a/48172508
has title: Space Invaders - Pygame - Make enemy shoot
has body: I am making the game Space Invaders with Pygame and I am trying to make the enemy shoot, firstly by pressing the TAB button. When I get this working I will let the enemy shoot randomly. At this moment I cannot see the BulletEnemy and when I press TAB it does not shoot anything. What am I doing wrong? Thanks. import pygame, sys from pygame.locals import * import random screenWidth = 800 screenHeight = 600 FPS = 60 pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((screenWidth,screenHeight)) pygame.display.set_caption("Space Invaders") clock = pygame.time.Clock() shipWidth = 78 #colors black=(0,0,0) blue=(0,0, 255) green=(0,128,0) red=(255,0,0) white=(255,255,255) yellow=(255,255,0) def app_quit(): pygame.quit() sys.exit("System exit.") class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("spaceship7.png").convert() self.image.set_colorkey(white)#make white transparant self.rect = self.image.get_rect() self.rect.centerx = screenWidth / 2 self.rect.bottom = screenHeight - 10 self.speedx = 0 def update(self): self.speedx = 0 if event.type == KEYDOWN and event.key == K_LEFT: self.speedx = -2 elif event.type == KEYDOWN and event.key == K_RIGHT: self.speedx = 2 self.rect.x += self.speedx if self.rect.right &gt; screenWidth: self.rect.right = screenWidth if self.rect.left &lt; 0: self.rect.left = 0 def shootPlayer(self): bulletPlayer = BulletPlayer(self.rect.centerx, self.rect.top) allSprites.add(bulletPlayer) bulletsPlayer.add(bulletPlayer) class Enemy(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("enemy.png").convert() self.image.set_colorkey(white) self.rect = self.image.get_rect() self.rect.x = 0 self.rect.y = random.randrange(0, 200) self.speedx = random.randrange(1,2) def update(self): self.rect.x += self.speedx if self.rect.right &gt; screenWidth: self.rect.x = 50 self.rect.y = random.randrange(0, 250) self.speedx = ra…

http://stackoverflow.com/comment/83378938
type: Comment
has text: That's when it should actually check to see if the line is in the output and count how many times it appears
score: 0
comment on: http://stackoverflow.com/a/48158647
type: AnswerComment

http://stackoverflow.com/comment/83185220
score: 0
type: Comment
has text: nothing wrong with grouping, I'm just trying to get better with regex and thought there might be something more straightforward for grabbing all of these different numbers that I may have overlooked. I have a feeling I was way over-complicating things
comment on: http://stackoverflow.com/a/48045996
type: AnswerComment

http://stackoverflow.com/a/48122723
score: 11
accepted answer of: http://stackoverflow.com/q/48122696
answers question: http://stackoverflow.com/q/48122696
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: read_csv with thousands=',' df = pd.read_csv('file.csv', thousands=',') This fixes the problem while reading your data. replace and to_numeric df['Principal Remaining'] = pd.to_numeric( df['Principal Remaining'].str.replace(',', ''), errors='coerce') If the first option isn't a choice, you'll need to get rid of the commas first using str.replace, then call pd.to_numeric as shown here.
upvote count: 11

http://stackoverflow.com/a/48058245
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48057845
score: 2
downvote count: 0
has body: You are essentially doing matrix-matrix multiplication where the first factor is weights[0] and the second is data[i] chopped up into 30 equal slices that form the columns. import numpy as np sizes = [784,30,10] weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1],sizes[1:])] k = 2 # create sparse data data = np.maximum(np.random.uniform(-100, 1, (k, 23520)), 0) foo = np.kron(np.identity(30),weights[0]) # This is the original loop as a list comprehension bar = [np.dot(foo,d) for d in data] # This is the equivalent using matrix multiplication. # We can take advantage of the fact that the '@' operator # can do batch matrix multiplication (it uses the last two # dimensions as the matrix and all others as batch index). # The reshape does the chopping up but gives us rows where columns # are required, hence the first swapaxes. # The second swapaxes is to make the result directly comparable to # the `np.kron` based result. bar2 = (weights[0] @ data.reshape(k, 30, 784).swapaxes(1, 2)).swapaxes(1, 2) # Instead of letting numpy do the batching we can glue all the # columns of all the second factors together into one matrix bar3 = (weights[0] @ data.reshape(-1, 784).T).T.reshape(k, -1) # This last formulation works more or less unchanged on sparse data from scipy import sparse dsp = sparse.csr_matrix(data.reshape(-1, 784)) bar4 = (weights[0] @ dsp.T).T.reshape(k, -1) print(np.allclose(bar, bar2.reshape(k, -1))) print(np.allclose(bar, bar3)) print(np.allclose(bar, bar4)) Prints: True True True

http://stackoverflow.com/comment/83115370
score: 0
type: Comment
has text: You will get more and better answers if you create a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example. Especially make sure that the input and expected data are complete (not pseudo-data), and can be easily cut and and paste into an editor to allow testing proposed solutions.
type: QuestionComment
comment on: http://stackoverflow.com/q/48070828

http://stackoverflow.com/q/48055762
has title: Unknown Python syntax in PyTorch: a instance can directly receive a parameter
has answer: http://stackoverflow.com/a/48055800
favorite count: 0
tagged with: pytorch
upvote count: 2
accepted answer: http://stackoverflow.com/a/48055800
tagged with: python
score: 2
type: AnsweredQuestion
has body: I have a question about Python syntax when I'm learning PyTorch. The following codes are an example from the PyTorch document. m = nn.Linear(20, 30) input = autograd.Variable(torch.randn(128, 20)) output = m(input) print(output.size()) This first line is to create an instance m, but why this instance m can directly receive a parameter like the line 3? I think it should use method to deal with parameter like m.method(input).
type: Question
downvote count: 0
answer count: 1

http://stackoverflow.com/q/48055016
type: UnansweredQuestion
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/48055110
score: -1
type: Question
has comment: http://stackoverflow.com/comment/83082403
upvote count: 0
has body: This function works only when I call with: def prodo(L): sum = 1 for i in range(0, len(L)): sum = L[i] * sum return sum these lines: d = prodo([3, -1, 4, -1, -5]) print(d) But the following function using L returns 375 and not -60 def prod(L): sum = 1 for i in L: if i&gt;=len(L): break sum = L[i] * sum return sum Question: What am I doing wrong and why?
has title: sum of a List Function difference
favorite count: 0
linked to: http://stackoverflow.com/q/9884132
tagged with: product
has answer: http://stackoverflow.com/a/48055068
has comment: http://stackoverflow.com/comment/83082439
answer count: 4
has answer: http://stackoverflow.com/a/48055041
has answer: http://stackoverflow.com/a/48055071

http://stackoverflow.com/comment/83137434
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48081557
has text: Thanks, would've never thought that that's the issue.

http://stackoverflow.com/a/48170291
type: Answer
has body: I couldn't think of any simple solution using just the new rolling method. It seems that the only way is to create a dataframe and create a new column with the weighted values. &gt;&gt;&gt; df = pd.DataFrame([1,1,1], index=pd.date_range('1/1/2000', periods=3), columns=['value']) &gt;&gt;&gt; df['weight'] = [2, 2, 2] &gt;&gt;&gt; df['weighted'] = df['value'] * df['weight'] &gt;&gt;&gt; df value weight weighted 2000-01-01 1 2 2 2000-01-02 1 2 2 2000-01-03 1 2 2 Calculating the sum is pretty straightforward. After creating your dataframe, use the rolling method and sum. Using the example you provided, it looks like the window is size of 3. &gt;&gt;&gt; df_rolled = df.rolling(3).sum() &gt;&gt;&gt; df_rolled['weighted'] 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 6.0 Freq: D, Name: weighted, dtype: float64 Calculating the weighted mean however will require you to generate another column that calculates the weighted mean where you're taking the values in the weighted column and dividing them by the values in the weight column. This ensures that you're calculating the weighted mean, not the mean of the weighted values... big difference here. &gt;&gt;&gt; df_rolled['w_mean'] = df_rolled['weighted'] / df_rolled['weight'] &gt;&gt;&gt; df_rolled['w_mean'] 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 1.0 Freq: D, Name: w_mean, dtype: float64 Another example to check if the solution works, and it does: &gt;&gt;&gt; df['value'] = [2, 4, 6] &gt;&gt;&gt; df['weight'] = [1, 3, 5] &gt;&gt;&gt; df['weighted'] = df['value'] * df['weight'] &gt;&gt;&gt; df value weight weighted 2000-01-01 2 1 2 2000-01-02 4 3 12 2000-01-03 6 5 30 &gt;&gt;&gt; df_rolled = df.rolling(3).sum() &gt;&gt;&gt; df_rolled['weighted'] # weighted sum 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 44.0 Freq: D, Name: weighted, dtype: float64 &gt;&gt;&gt; df_rolled['w_mean'] = df['weighted'] / df['weight'] &gt;&gt;&gt; df_rolled['w_mean'] # weighted mean 2000-01-01 NaN 2000-01-02 NaN 2000-01-03 4.888889 Freq: D, Name: w_mean, dty…
has comment: http://stackoverflow.com/comment/83322953
answers question: http://stackoverflow.com/q/48167165
score: 0

http://stackoverflow.com/q/48111119
tagged with: python
favorite count: 0
type: UnansweredQuestion
score: -4
has title: How to get customer details from a file?
has comment: http://stackoverflow.com/comment/83205856
has answer: http://stackoverflow.com/a/48114929
has body: I am new to Python but trying to create a Bank account system. I did create the BankAccount class and the customer records but how do I put the two codes together
has comment: http://stackoverflow.com/comment/83197875
type: Question
downvote count: 4
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83198833

http://stackoverflow.com/a/48886816
has comment: http://stackoverflow.com/comment/124520045
downvote count: 3
score: 34
has comment: http://stackoverflow.com/comment/128848459
has comment: http://stackoverflow.com/comment/88555021
upvote count: 37
has comment: http://stackoverflow.com/comment/93956237
answers question: http://stackoverflow.com/q/48163641
has body: Please run check django-admin command to see if it have detected any errors. python manage.py check and/or django-admin check
type: Answer
has comment: http://stackoverflow.com/comment/91304077

http://stackoverflow.com/comment/83104503
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48065637
has text: You can achieve it by: `[[{y} for y in x] for x in my_list]`. But why do you want that?
score: 1

http://stackoverflow.com/q/48149649
has comment: http://stackoverflow.com/comment/83298794
has body: I'm trying to interpolate a gap I have between data points. The data I have is 2 arrays of time and acceleration. The acceleration array consist of values that can be considered periodic. The original data points with the gap look like this: data points with gap I am trying to do the interpolation by using the scipy.interpolate.interp1d as illustrated below: interpolation_func = interpolate.interp1d(time, acceleration, kind='slinear') new_time = np.arange(np.min(time), np.max(time), 0.1) new_acc = interpolation_func(new_time) plt.figure(2, figsize=(14, 8)) plt.title('Interpolated uncalibrated acceleration data') plt.scatter(new_time, new_acc, c=new_time[:], s=1, vmin=np.min(new_time), vmax=np.max(new_time)) plt.colorbar() plt.xlabel('Time [s]') plt.ylabel('Acceleration') plot_fig2 = (output_folder + "kinematic_plot2.png") plt.savefig(plot_fig2) However, the result I'm getting is not accurate because I'm get a line that connects the last point from 1st group of scattered points, on the left side of the gap, and the first point from the 2nd group of points, on the right side of the gap. The wrong result looks like this: Wrong result I have tried other options from the scipy.interpolate.interp1d function, other than the kind slinear, but all of them would flatten the scattered points on both sides of the gap and fill in the gap with a polynomial graph, which is not what I need. Are there any options in python to interpolate the gap I have between the scattered points?
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83279508
has comment: http://stackoverflow.com/comment/83279418
has comment: http://stackoverflow.com/comment/83279174
has title: Python - Interpolating a gap in scattered data points
favorite count: 0
tagged with: python
tagged with: interpolation
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 1

http://stackoverflow.com/a/48150417
downvote count: 0
has body: Cloudshell-Shell-Core &amp; Cloudshell-Core are not dependent on server version. This means that you can develop your shells with the latest versions of Cloudshell-Shell-Core (and Cloudshell-Core) for all Cloudshell server versions.
type: Answer
answers question: http://stackoverflow.com/q/48150348
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48150348
score: 3
type: AcceptedAnswer

http://stackoverflow.com/q/48039587
tagged with: new-operator
type: Question
upvote count: 4
has body: I have this very simple program that has a singleton implemented as a base class that simply defines a new that is used implement the "single-ness". However I can no longer send arguments to the init method - when I do I get a "TypeError: object() takes no parameters" from the singleton new super call: class Singleton(object): _instances = {} def __new__(cls, *args, **kwargs): print(args, kwargs) if cls._instances.get(cls, None) is None: cls._instances[cls] = super(Singleton, cls).__new__(cls, *args, **kwargs) return Singleton._instances[cls] class OneOfAKind(Singleton): def __init__(self): print('--&gt; OneOfAKind __init__') Singleton.__init__(self) class OneOfAKind2(Singleton): def __init__(self, onearg): print('--&gt; OneOfAKind2 __init__') Singleton.__init__(self) self._onearg = onearg x = OneOfAKind() y = OneOfAKind() print(x == y) X = OneOfAKind2('testing') The output is: () {} Traceback (most recent call last): File "./mytest.py", line 29, in &lt;module&gt; x = OneOfAKind() File "./mytest.py", line 10, in __new__ cls._instances[cls] = super(Singleton, cls).__new__(cls, (), {}) TypeError: object() takes no parameters
has title: python override __new__ cannot send arguments to __init__
score: 4
tagged with: singleton
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83049841
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48039850

http://stackoverflow.com/comment/83225554
comment on: http://stackoverflow.com/q/48123619
type: QuestionComment
type: Comment
score: 0
has text: @Satendra I wanna make only one method which has functions of DetailView&CommentCreateView&ReCommentCreateView .So these classes use general class ,so I do not know how I can make my ideal method. How should I fix this?

http://stackoverflow.com/q/48137755
type: AnsweredQuestion
score: 1
has body: In Python 3.5, given this string: "rsFooBargrdshtrshFooBargreshyershytreBarFootrhj" and the index 17 -- so, the F at the start of the second occurrence of FooBar -- how can I check that "FooBar" exists? In this case, it should return True, while if I gave it the index 13 it should return false.
tagged with: substring
type: Question
accepted answer: http://stackoverflow.com/a/48138139
has answer: http://stackoverflow.com/a/48137864
downvote count: 0
has answer: http://stackoverflow.com/a/48137795
tagged with: string
has title: Check if string contains substring at index
possible better answer: http://stackoverflow.com/a/48137795
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48137815
has answer: http://stackoverflow.com/a/48138139
answer count: 5
has answer: http://stackoverflow.com/a/48137863
upvote count: 1

http://stackoverflow.com/a/48138256
has body: The feed_dict should contain numerical values, not tf.Variable. Replace your definition of test with: test = {"A":np.random.randn(20,20), "B":np.random.randn(20,20)} Also you should import numpy as np at the beginning, of course. The code then behaves as you want it to. For a bit more explanation, you can think of the feed_dict as the numerical values you give to your computational graph, not part of the computational graph (as a tf.Variable would be).
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/48138218
upvote count: 3
answers question: http://stackoverflow.com/q/48138218

http://stackoverflow.com/q/48155106
has answer: http://stackoverflow.com/a/48155247
tagged with: dictionary
answer count: 4
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/48155247
upvote count: 1
has answer: http://stackoverflow.com/a/48157732
type: Question
linked to: http://stackoverflow.com/q/17915117
tagged with: dictionary-comprehension
accepted answer: http://stackoverflow.com/a/48157732
downvote count: 0
has body: This question is about nested dictionary comprehension and I have referred the link1 and link2 before asking this. I have a list whose first element is None and the remaining of it is a list of sorted positive numbers. sorted_ar = [None, 10, 10, 12, 12, 12, 15, 25] My requirement is to build a dictionary as: key_dict = {10: [3, 2], 12: [12, 3], 15: [6, 1], 25: [7, 1]} The values of the dictionary are a two element list, first element is the sum of indexes of the occurrences of key, second is the number of occurrences. For example for element 12, sum of indexes = 3+4+5 = 12 and number of occurrences is 3. The following code does it. key_dict = {k:[0,0] for k in sorted_ar if k!=None} for i in range(len(sorted_ar)): if sorted_ar[i]: key_dict[sorted_ar[i]][0] += i key_dict[sorted_ar[i]][1] += 1 My requirement is to prepare the key_dict dictionary using dictionary comprehension. My attempt: key_dict = { sorted_ar[i]:[ key_dict[sorted_ar[i]][0] + i,key_dict[sorted_ar[i]][0] + 1] for i in range(1,len(sorted_ar)) if sorted_ar[i]!=None } But this is giving some erroneous result as key_dict = {10: [2, 1], 12: [5, 1], 15: [6, 1], 25: [7, 1]} How should I write the dictionary comprehension in this case?
favorite count: 0
has answer: http://stackoverflow.com/a/48155152
has answer: http://stackoverflow.com/a/48156311
tagged with: python-3.x
has title: Dictionary creation from sorted list
linked to: http://stackoverflow.com/q/20489609
tagged with: python

http://stackoverflow.com/q/48083811
type: Question
tagged with: split
score: 0
has comment: http://stackoverflow.com/comment/83356237
has comment: http://stackoverflow.com/comment/83364285
tagged with: python
has title: Define parameter of variable length after specific string, but before the next line
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
duplicate of: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/83142310
tagged with: python-3.6
has body: I've done my due diligence trying to find an answer to this, but haven't had any luck. Example string: test = 'CurrentEmail:EMAIL@gmail.com\n' \ 'CurrentTime:TIME\n' \ 'CurrentLocation:LOCATION' What I am trying to do is define each one of those parameters separately as in: CurrentEmail = 'EMAIL@gmail.com', CurrentTime = 'TIME', CurrentLocation = 'LOCATION'. So somehow extracting between the : and the next line, \n all from that same test string. Thank you very much for your help! EDIT: I was able to use the following. new_test = test.splitlines() for lines in new_test: if 'CurrentEmail:' in lines: CurrentEmail = lines.replace('CurrentEmail:', '') elif 'CurrentTime' in lines: CurrentTime = lines.replace('CurrentTime:', '') elif 'CurrentLocation:' in lines: CurrentLocation = lines.replace('CurrentLocation:', '') else: continue

http://stackoverflow.com/a/48139848
answers question: http://stackoverflow.com/q/48139804
has comment: http://stackoverflow.com/comment/83257454
has body: You can separate number picker: def pick_num(text): while True: try: a = float(input(text)) return a except ValueError: print('This is not a number') def tile_cost(): w = pick_num('What is the width: ') l = pick_num('What is the height: ') c = pick_num('What is the cost: ') print("The cost of tiling the floor will be: £%.2f" % (w * l * c))
score: 0
type: Answer

http://stackoverflow.com/a/48069645
has comment: http://stackoverflow.com/comment/83154384
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48067160
downvote count: 0
has body: Your code works as is after the CloseHandle edit. When you weren't closing the file handle in CreateFile(), the file open in ReadAFile failed because the file was already open. You didn't check the error so your call to ReadFile failed. Now that the code is edited to have the CloseHandle in CreateFile, it works. Note you may need to close and re-open your IDE as it may keep a handle open to the file until you kill the process since it was a handle leak (I had that issue). I also find in ctypes that being explicit and defining argtypes, restype, and errcheck is useful. errcheck especially, since code will throw an error and you don't have to check return values for failure. Note: Original Python 2 code edited for Python 3 and updated to use Unicode Win32 APIs. See edit history for original. import ctypes as ct import ctypes.wintypes as w INVALID_HANDLE_VALUE = w.HANDLE(-1).value GENERIC_ALL = 0x10000000 OPEN_ALWAYS = 4 FILE_ATTRIBUTE_NORMAL = 0x80 kernel32 = ct.WinDLL('kernel32', use_last_error=True) CreateFileW = kernel32.CreateFileW WriteFile = kernel32.WriteFile ReadFile = kernel32.ReadFile CloseHandle = kernel32.CloseHandle def validate_handle(result, func, args): if result == INVALID_HANDLE_VALUE: raise ct.WinError(get_last_error()) return result def validate_bool(result, func, args): if not result: raise ct.WinError(get_last_error()) CreateFileW.argtypes = w.LPCWSTR, w.DWORD, w.DWORD, ct.c_void_p, w.DWORD, w.DWORD, w.HANDLE CreateFileW.restype = w.HANDLE CreateFileW.errcheck = validate_handle WriteFile.argtypes = w.HANDLE, ct.c_void_p, w.DWORD, w.LPDWORD, ct.c_void_p WriteFile.restype = w.BOOL WriteFile.errcheck = validate_bool ReadFile.argtypes = w.HANDLE, w.LPVOID, w.DWORD, w.LPDWORD, ct.c_void_p ReadFile.restype = w.BOOL ReadFile.errcheck = validate_bool CloseHandle.argtypes = w.HANDLE, CloseHandle.restype = w.BOOL CloseHandle.errcheck = validate_bool def CreateFile(file_name='', data=''): file_handler = CreateFileW(file_name, GENERIC_ALL, 0, None, OPEN_ALWA…
accepted answer of: http://stackoverflow.com/q/48067160
type: Answer
has comment: http://stackoverflow.com/comment/83138484
score: 4
has comment: http://stackoverflow.com/comment/83154291
has comment: http://stackoverflow.com/comment/114740198
has comment: http://stackoverflow.com/comment/83138581
has comment: http://stackoverflow.com/comment/83138826
upvote count: 4

http://stackoverflow.com/comment/83277703
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48035341
has text: One very common suggestion, like ABC, is just "run SysInternals Process Monitor; tune it to filter file I/o events from your python app, and then catch that very moment of failed process (here: DB connection attempt) into logs. Then check which files (DLLs) and where it tries to look for". Usually this gives a clue what kind of settings need fixing.
score: 0

http://stackoverflow.com/q/48030002
has body: I'm using the built in Python library to send email. Everything works, except when I put a time in the message that I'm sending. like 7:30 pm. When I put a time in the email message, the email recipient just gets a blank email. If I remove the time, the email sends just fine. I'm guessing that something with the time screws up the email. What should I change in my code, so I can put a time in the email body. Thanks! from smtplib import SMTP def sendEmail(message,address): debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) #connect to the email server smtp.connect('smtp.gmail.com', 587) smtp.starttls() smtp.login('ouremail@gmail.com', 'ourpassword') #set the email to be sent from from_addr = "Auto Notification &lt;sender email&gt;" #send the email from our address and the message and recepients provided in the function definition. smtp.sendmail(from_addr, address, message) smtp.quit() finalStr = "The Girls Varsity Basketball has been changed to 02/06/2018 at 7:30 pm * - ( previously 6:15 pm ) at Clear Lake High School" sendEmail(finalStr, 'myemail@gmail.com')
has comment: http://stackoverflow.com/comment/83030245
score: 0
tagged with: email
answer count: 1
tagged with: smtp
has comment: http://stackoverflow.com/comment/83030232
has answer: http://stackoverflow.com/a/48030291
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83030204
type: Question
has comment: http://stackoverflow.com/comment/83030465
has title: Python SMTP Library Blank Email with time
accepted answer: http://stackoverflow.com/a/48030291

http://stackoverflow.com/a/48043050
has body: Your code is correct. Seems like this resource is trying to block bots in simplest manner (by checking if request was sent from browser or not). You can set dummy user agent with appropriate header to solve this issue: request = urllib.request.Request(url, headers={'User-Agent': 'Browser'}) urllib.request.urlopen(request).read()
has comment: http://stackoverflow.com/comment/83057544
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83060791
accepted answer of: http://stackoverflow.com/q/48042973
type: Answer
has comment: http://stackoverflow.com/comment/83056826
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48042973

http://stackoverflow.com/a/48110678
accepted answer of: http://stackoverflow.com/q/48110587
has comment: http://stackoverflow.com/comment/83197030
has comment: http://stackoverflow.com/comment/83197142
has body: use this and dont forget to migrate after makemigrations @python_2_unicode_compatible class TestModelLog(models.Model): description = models.CharField(max_length=34) foreignkey = models.ForeignKey(TestModel_2, related_name='test_foreignkey_1', on_delete=models.DO_NOTHING ,null=True, blank=True) foreignkey_2 = models.ForeignKey(TestModel_2, related_name='test_foreignkey_2',on_delete=models.DO_NOTHING, null=True, blank=True) def __str__(self): return "TestModelLog %s" % self.description
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83196833
has comment: http://stackoverflow.com/comment/83197103
downvote count: 0
has comment: http://stackoverflow.com/comment/83197113
type: Answer
has comment: http://stackoverflow.com/comment/83197074
answers question: http://stackoverflow.com/q/48110587
has comment: http://stackoverflow.com/comment/83197043
score: 1
upvote count: 1

http://stackoverflow.com/a/48152534
has comment: http://stackoverflow.com/comment/83291763
type: AcceptedAnswer
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/48148123
type: Answer
has comment: http://stackoverflow.com/comment/83283939
score: 2
has body: Have a look https://kivy.org/docs/api-kivy.uix.screenmanager.html. ScreenManager can manage your blank/main screen transitions
has comment: http://stackoverflow.com/comment/83305186
accepted answer of: http://stackoverflow.com/q/48148123

http://stackoverflow.com/comment/83190008
type: Comment
has text: if i use axis=0, 2 data frames combined to 1 but the order of header is not kept.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48106822

http://stackoverflow.com/comment/83213272
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48115869
score: 0
has text: dear jdehesa, I compiled the myProgram.py output like: give [playername]/[randomgun]. the ServerProgram is like a batchfile and the command needs to be only copied from the shell to the batchfile while running. do you know a module or a way that copies one variable and pasts it in the server console. here is a picture of the server console: https://www.google.nl/search?q=unturned+server&client=firefox-b-ab&dcr=0&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjY2snSocHYAhUNDuwKHXsVAvMQ_AUICygC&biw=1920&bih=940#imgrc=t157-RmP7Ws5QM: sorry for my bad inglish

http://stackoverflow.com/comment/83226830
type: Comment
has text: If it's just about capitalization why don't you just use `s.lower()`?
score: 1
comment on: http://stackoverflow.com/q/48124970
type: QuestionComment

http://stackoverflow.com/a/48115213
has comment: http://stackoverflow.com/comment/83210036
has comment: http://stackoverflow.com/comment/83209797
has body: As I did say in the comment your code can be improved You can use a function and return once your condition is satisfied def func(array1, to_remove): for lst in array1: for index, n in enumerate(lst): if array1[0][index] &lt; n: array1.remove(to_remove) return True return False Or use a flag flag = False for lst in array1: for index, n in enumerate(lst): if array1[0][index] &lt; n: array1.remove([7,2,3,5]) flag = True break if flag: break
upvote count: 1
has comment: http://stackoverflow.com/comment/83209439
has comment: http://stackoverflow.com/comment/83208573
has comment: http://stackoverflow.com/comment/83210129
has comment: http://stackoverflow.com/comment/83206435
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83206369
answers question: http://stackoverflow.com/q/48114794
type: Answer
has comment: http://stackoverflow.com/comment/83206452
has comment: http://stackoverflow.com/comment/83209197

http://stackoverflow.com/a/61103586
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48125215
upvote count: 1
type: Answer
has body: On MacOS Catalina (10.5.2) you may have followed all the guidelines and got a similar error: ImportError: pycurl: libcurl link-time ssl backend (none/other) is different from compile-time ssl backend (openssl) This is a result of curl missing openssl, which doesn't come with MacOS now. As described in https://blog.birkhoff.me/switching-to-the-openssl-version-of-curl/ To fix: $ brew upgrade $ brew uninstall curl $ brew install curl-openssl $ echo 'export PATH="/usr/local/opt/curl-openssl/bin:$PATH"' &gt;&gt; ~/.zshrc

http://stackoverflow.com/a/48053264
accepted answer of: http://stackoverflow.com/q/48042177
type: Answer
upvote count: 1
downvote count: 1
has body: You can control several lights with an Esp2866 or raspberry using wifi and relays outputs, but you have to setup the device on a IOT platform like Blynk Or My Devices Cayenne, both have their own API and documentation you should take a look.
score: 0
answers question: http://stackoverflow.com/q/48042177
type: AcceptedAnswer

http://stackoverflow.com/q/48123843
has body: My program makes a simple chart using pygal, and outputs the chart as a URI string. I want to convert this URI into an image that I can then manipulate with pillow. I've tried decoding the string but haven't been able to make it work. The current version of my code takes the URI and converts it into bytes as I was hoping that would make conversion easier, if I don't need to do this I can remove that line. #Pygal graphing test import pygal import base64 from PIL import Image #Get number of loops needed user_num = int(input("How many people are taking the survey?")) print() #Give values to colour variables red = 0 orange = 0 yellow = 0 green = 0 blue = 0 purple = 0 #Loop getting data from user for x in range(1,user_num + 1): user_colour = input("What is your favourite colour?") print() if user_colour == "red": red = red + 1 elif user_colour == "orange": orange = orange + 1 elif user_colour == "yellow": yellow = yellow + 1 elif user_colour == "green": green = green + 1 elif user_colour == "blue": blue = blue + 1 elif user_colour == "purple": purple = purple + 1 #Create bar graph object bar_chart = pygal.Bar() #Title of graph bar_chart.title = "Favourite Colour" #X-Axis label bar_chart.x_labels = ("Red", "Orange", "Yellow", "Green", "Blue", "Purple") #Add values bar_chart.add('Favourite Colours', [red,orange,yellow,green,blue,purple]) #Save chart data = bar_chart.render_data_uri() #Convert string to bytes b = bytes(data, 'utf-8')
linked to: http://stackoverflow.com/q/3600164
type: AnsweredQuestion
tagged with: uri
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48124665
upvote count: 1
has title: How to convert URI of image to image file in python
tagged with: pygal
answer count: 1
linked to: http://stackoverflow.com/q/6589358
tagged with: python-imaging-library
accepted answer: http://stackoverflow.com/a/48124665
tagged with: image

http://stackoverflow.com/q/48106417
has comment: http://stackoverflow.com/comment/83189196
has body: i tried get method but response is not found file. when i get other own file. when i get file info my own file. it is possible. how to access other own file... this is my code file_id value replace [google_id] cause security SCOPES = ['https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.scripts', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.metadata' ] credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('drive', 'v2', http=http) file_id = '[google_id]' file = service.files().get( fileId=file_id, supportsTeamDrives=True).execute() new_title = '[bob]' file['title'] = new_title new_filename = '[bob].mp4' new_revision = True updated_file = service.files().update( fileId=file_id, body=file, newRevision=new_revision, media_body=('__init__.py'), supportsTeamDrives=True).execute() print(repr(updated_file))
score: -1
accepted answer: http://stackoverflow.com/a/48109721
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83189278
favorite count: 0
has comment: http://stackoverflow.com/comment/83189137
has comment: http://stackoverflow.com/comment/83188720
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48109721
has title: how to get other own file in googledrive with apiclient in python?
has comment: http://stackoverflow.com/comment/83189183
has comment: http://stackoverflow.com/comment/83194521
downvote count: 1
has comment: http://stackoverflow.com/comment/83189223
type: Question

http://stackoverflow.com/comment/83459616
type: Comment
has text: It worked, I have a question related, but not being solved yet. Could you please take a look, I don't know how to privately message you. Thanks.https://stackoverflow.com/q/48225888/2525479
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48098169

binary-tree
tags question: http://stackoverflow.com/q/48063966
tag name: binary-tree
tags question: http://stackoverflow.com/q/48061939
type: Tag
tags question: http://stackoverflow.com/q/48134865
tags question: http://stackoverflow.com/q/48054654

http://stackoverflow.com/a/48141803
score: 0
type: AcceptedAnswer
has body: Your purpose on this program to allow user input up to 3 Error value. You can pass index as argument that counts incorrect entry by user and retain this value by calling the function recursively See the complete rewrite with that approach. def level_selection(index): level1, level2, level3 = "level1", "level2","level3" level = input("Choose the desired level of difficulty: easy, medium or hard") if level.lower() == "easy": return level1 if level.lower() == "medium": return level2 if level.lower() == "hard": return level3 else: print("Error") index -= 1 if index &gt; 0: return level_selection(index) return print(level_selection(3))
type: Answer
answers question: http://stackoverflow.com/q/48141655
accepted answer of: http://stackoverflow.com/q/48141655

http://stackoverflow.com/comment/83424234
type: Comment
comment on: http://stackoverflow.com/q/48028416
type: QuestionComment
score: 1
has text: Yeah, some data would be nice. Tip, use `zip` to avoid half of the loops and the `_.index()` part that does not really increase readability.

http://stackoverflow.com/q/48030850
has body: I am trying to understand this tutorial code. from flask import Flask from flask_mail import Mail, Message app =Flask(__name__) mail=Mail(app) # &lt;-- This app.config['MAIL_SERVER']='smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = 'yourId@gmail.com' app.config['MAIL_PASSWORD'] = '*****' app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True mail = Mail(app) # &lt;-- This @app.route("/") def index(): msg = Message('Hello', sender = 'yourId@gmail.com', recipients = ['id1@gmail.com']) msg.body = "Hello Flask message sent from Flask-Mail" mail.send(msg) return "Sent" if __name__ == '__main__': app.run(debug = True) At the line 5 and 13, Mail object are instantiated and assigned to mail. Even if I comment out the first instantiation in line 5, I can still send emails, so can I say it is just a typo, or it is necessary?
type: AnsweredQuestion
tagged with: web-applications
has answer: http://stackoverflow.com/a/48030894
accepted answer: http://stackoverflow.com/a/48030894
type: Question
score: 0
upvote count: 1
answer count: 1
tagged with: email
downvote count: 1
tagged with: flask
favorite count: 0
tagged with: flask-mail
has title: Flask-Mail Mail() instantiated twice
tagged with: python

http://stackoverflow.com/comment/83014478
comment on: http://stackoverflow.com/q/48022598
has text: I am not trying to scrape a full map, just a specific number on the pane that is on the lest side of the map. Also the google maps api does not returns the number of reviews as of now.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83218910
has text: Thanks very much !! Now I have re-measured the time and see 4x speedup (see last update)
comment on: http://stackoverflow.com/a/48121074
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48087744
has comment: http://stackoverflow.com/comment/83150500
has comment: http://stackoverflow.com/comment/83153710
upvote count: 1
answers question: http://stackoverflow.com/q/48087138
has comment: http://stackoverflow.com/comment/83178382
has body: In Django you can generate aggregates over an entire queryset using aggregate() or an independent summary for each object using annotate(). Here is the documentation. In your case, it seems you want to annotate the average lead__price to each university object: university = University.objects.all().annotate(Avg('lead__price')) Note you may have to adjust the lead__price reference so that it matches your data model, which you haven't provided.
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83153979
type: Answer
has comment: http://stackoverflow.com/comment/83154957
has comment: http://stackoverflow.com/comment/83185062

http://stackoverflow.com/comment/83265071
type: Comment
type: QuestionComment
has text: I've updated the first [example](https://stackoverflow.com/a/45404355/6220679).
comment on: http://stackoverflow.com/q/48128206
score: 0

http://stackoverflow.com/q/48173141
linked to: http://stackoverflow.com/q/9097994
tagged with: mutability
type: AnsweredQuestion
type: Question
upvote count: 4
downvote count: 0
answer count: 1
has body: When I try to modify string using += operator, and use id() method to check object's identity, string seems to be mutable. Did someone face with such a weird python behaviour? a = '123' print id(a) # 89806008 a += '1' print id(a) # 89245728 a += '1' print id(a) # 89245728 print a # '12311' Using a = a + '1' doesnt have the same effect, and change the string id.
tagged with: string
score: 4
has comment: http://stackoverflow.com/comment/83326040
favorite count: 0
has answer: http://stackoverflow.com/a/48173299
tagged with: python-2.7
tagged with: python
linked to: http://stackoverflow.com/q/24245324
has comment: http://stackoverflow.com/comment/83325973
has comment: http://stackoverflow.com/comment/83326023
has comment: http://stackoverflow.com/comment/83326053
has title: Does Python += operator make string mutable?
accepted answer: http://stackoverflow.com/a/48173299

http://stackoverflow.com/comment/83215878
score: 0
type: Comment
type: QuestionComment
has text: @freakish, could you post a solution?
comment on: http://stackoverflow.com/q/48119634

http://stackoverflow.com/comment/83128811
type: Comment
type: QuestionComment
has text: @famargar - If it is very sparse, use `df = df.stack().map(d).unstack()`
score: 0
comment on: http://stackoverflow.com/q/48076607

http://stackoverflow.com/comment/83184456
type: Comment
score: 0
has text: @Gagravarr that's kinda my last resort... i'll try the latest server if needed, however having everything running under pip helps keep everything centralized.
type: QuestionComment
comment on: http://stackoverflow.com/q/48103065

http://stackoverflow.com/comment/83254756
type: Comment
has text: I accepted your answer because it led me to double checking the original values, so It works now. thanks for your help
comment on: http://stackoverflow.com/a/48138073
type: AnswerComment
score: 0

http://stackoverflow.com/q/48141809
tagged with: windows
tagged with: python
has title: No Module Name django right after installing
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83261688
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83261590
tagged with: django
type: Question
linked to: http://stackoverflow.com/q/40926512
tagged with: environment-variables
linked to: http://stackoverflow.com/q/20862704
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/48142026
has body: I'm trying to install django in a virtual environment on my Windows machine (I have python 3.6.4). I create the virtual environment and install django and get the success message. But when I try to see my django installation, I get the error below: I'm seeing several similar questions on Stackoverflow like this or this but they are either on a different OS or have used a different means of installation and I've tried some of the suggestions with no luck. Does anyone know what is causing this and how to resolve?

http://stackoverflow.com/comment/83029954
comment on: http://stackoverflow.com/a/48029907
has text: Would be better to not build that `cor` in the first place.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83097903
comment on: http://stackoverflow.com/a/48062613
has text: Well it doesn't work properly, the first test being the sentence you have above where it gave 5am istaed of 5 only, the other when i substitued 5am to 5pm i got only pm and then i changed 5am to 12 am and got 12.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48081124
accepted answer: http://stackoverflow.com/a/48081452
has body: I'd delete this question, as it turns out to be my mistake. The bottleneck I had was related to network latency. I have a Python application that gets as an input a text file that contains 4096 real numbers. It looks like this: 0.3421,0.1215,..........,1.242 No matter what approach I try, it takes Python about a whole second to parse the text into an actual Python array of floats. Note that I am using Python 3.5 So far I tried: Parsing manually and creating the list using list comprehensions: arr = [float(val) for val in text.split(',')] Appending '[' and ']' wrapping signs and using eval function: arr = eval('[' + text + ']') Appending '[' and ']' wrapping signs and using json.loads function: import json arr = json.loads('[' + text + ']') Creating a Numpy array of strings and converting its data type to float: import numpy as np arr = np.array(text.split(',')).astype(np.float) Using Numpy's fromstring method import numpy as np arr = np.fromstring(text, sep=',') None of these options worked faster than a whole second. How do I get it to convert faster?
has comment: http://stackoverflow.com/comment/83137318
has title: Python: Parsing a long double array represented by text is very slow
upvote count: 1
has comment: http://stackoverflow.com/comment/83136822
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83137198
possible better answer: http://stackoverflow.com/a/48081458
has comment: http://stackoverflow.com/comment/83136981
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48081458
score: 1
tagged with: floating-point
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48081452

http://stackoverflow.com/q/48043009
has comment: http://stackoverflow.com/comment/83056839
has comment: http://stackoverflow.com/comment/83056949
tagged with: python
has answer: http://stackoverflow.com/a/48043150
has body: I have a list of numbers ; 1 6 3 15 54... Let's say list is L, I want to apply this condition as simple as possible ; L[2]-L[1] L[4]-L[3] . . . Then a new list emerges let's say L2, apply the same rule again ; L2[2]-L2[1] L2[4]-L2[3] . . . Until there is only one number is left from the initial L list. I am currently working on something like this ; for n in range(2,len(L),1): r.append(s[n]-s[n-1]) works for 1 loop but to introduce corresponding iterations I am looking for a decent approach. I will gladly accept the innovative answer. Thank you!
has answer: http://stackoverflow.com/a/48044890
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83056754
linked to: http://stackoverflow.com/q/17579357
score: -4
upvote count: 1
linked to: http://stackoverflow.com/q/3323001
type: Question
has comment: http://stackoverflow.com/comment/83056807
possible better answer: http://stackoverflow.com/a/48043157
has comment: http://stackoverflow.com/comment/83056865
downvote count: 5
has title: Nested loop variables in Python
answer count: 3
has comment: http://stackoverflow.com/comment/83057035
accepted answer: http://stackoverflow.com/a/48043150
has comment: http://stackoverflow.com/comment/83056802
has comment: http://stackoverflow.com/comment/83056827
has comment: http://stackoverflow.com/comment/83056856
favorite count: 0
has comment: http://stackoverflow.com/comment/83056851
has answer: http://stackoverflow.com/a/48043157

http://stackoverflow.com/a/48111503
has body: Due to case inconsistency I would suggest you to use upper(): df['category'] = df['title'].apply(lambda x: list([y for y in console_list if y.upper() in x.upper()]))
has comment: http://stackoverflow.com/comment/83198751
upvote count: 1
answers question: http://stackoverflow.com/q/48111324
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/83153985
has text: @ABDULNIYASPM Yes i have.
comment on: http://stackoverflow.com/q/48089703
score: 0
type: Comment
type: QuestionComment

identifier
tag name: identifier
type: Tag
tags question: http://stackoverflow.com/q/48063082

http://stackoverflow.com/q/48043228
score: 1
has answer: http://stackoverflow.com/a/48045062
type: Question
has body: I prepared kivy buildozer for using. For installation I used instructions here, process for python 3. After step 3, buildozer.spec file wasn't completed and checked lines (step 4) had next content: requirements = kivy #android.ndk_path = Message about installation after buildozer android debug deploy run: # Unpacking Android NDK # Android NDK installation done. # Check application requirements # Check garden requirements # Compile platform # Command failed: /usr/bin/python -m pythonforandroid.toolchain create --dist_name=myapp --bootstrap=sdl2 --requirements=kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir=/media/sf_ForBuildozer/.buildozer/android/platform/build # # Buildozer failed to execute the last command # If the error is not obvious, please raise the log_level to 2 # and retry the latest command. # In case of a bug report, please add a full log with log_level = 2 What is origin of problems? I added log_level = 2 to section buildozer, New message: # Run '/usr/bin/python -m pythonforandroid.toolchain create --dist_name=myapp --bootstrap=sdl2 --requirements=kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir=/media/sf_ForBuildozer/.buildozer/android/platform/build' # Cwd /media/sf_ForBuildozer/.buildozer/android/platform/python-for-android-new-toolchain [INFO]: Will compile for the following archs: armeabi-v7a [INFO]: Found Android API target in $ANDROIDAPI [INFO]: Available Android APIs are () [WARNING]: Requested API target 19 is not available, install it with the SDK android tool. [WARNING]: Exiting. # Command failed: /usr/bin/python -m pythonforandroid.toolchain create --dist_name=myapp --bootstrap=sdl2 --requirements=kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir=/media/sf_ForBuildozer/.buildozer/android/platform/build # # Buildozer failed to execute the last command # The error might be hidden in the log above this error # Please read the full log, and search for it before # raising an issue with buildozer its…
has comment: http://stackoverflow.com/comment/83057439
answer count: 1
downvote count: 0
tagged with: buildozer
accepted answer: http://stackoverflow.com/a/48045062
tagged with: kivy
favorite count: 0
has comment: http://stackoverflow.com/comment/83059850
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83058774
type: AnsweredQuestion
has title: Kivy: Buildozer.spec file is not completed

http://stackoverflow.com/comment/83298355
has text: Nice, you got it!
type: AnswerComment
comment on: http://stackoverflow.com/a/48159342
type: Comment
score: 0

http://stackoverflow.com/q/48100657
has comment: http://stackoverflow.com/comment/83176697
has body: I have been attempting to install scipy such that I can run it from IDLE. I have installed : the proper numpy wheel via pip the proper scipy wheel via pip the visual C++ redistributable I am using python 3.6.xx 32 bit and windows 10 pro. I have uninstalled and reinstalled everything multiple times. I am unsure how to move forward or where to look, it seems to me that the low level callable library has not installed properly given I am getting the error "Import Error: DLL load failed: the specified module could not be found"
tagged with: python
has comment: http://stackoverflow.com/comment/83182128
answer count: 0
has comment: http://stackoverflow.com/comment/83179921
has title: Scipy: C Callback DLL failing to Load
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83221057
has comment: http://stackoverflow.com/comment/83180932
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/83144669
type: Comment
has text: `localnewbyte` will be a “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256, so what would this be in PHP an array???
comment on: http://stackoverflow.com/q/48083608
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83248428
comment on: http://stackoverflow.com/q/48135593
type: Comment
type: QuestionComment
has text: @Satwik - exactly :-)
score: 1

http://stackoverflow.com/comment/83296208
comment on: http://stackoverflow.com/a/48158354
type: Comment
has text: I saw you change your answer.
score: 1
type: AnswerComment

http://stackoverflow.com/a/48191733
score: 2
downvote count: 0
has body: when doing high performance development,we always choose weapons based on our situation.So it still too broad to answer. But your bigger question is a easier one.only the IO-bound program is suit for Async. what is the purpose of epoll and asynchronous?Avoiding the CPU waiting for IO and doing nothing.CPU waiting for IO blocks,IO blocks because NO DATA TO READ or NO space to write. Buffer is introduced to reduce the system call.When you call read on a stream,you actually read from the buffer.(concepts,not very accurate) Select or epoll are nonblocking busy polling(epoll implement by interruption underlying).it just essentially something like below while true { for i in stream[]{ if i has data read until unavailable } } it's silly,so there is select and epoll. Everytime you read from buffer,there are data waiting for you,it's high speed IO,then epoll/select is your best choice.And when the buffer is always empty,it's a slow stream,IO-bound,async is very suit for this situation. I don't know async very well,for me it's just soft interruption internally and a lot of callback.
upvote count: 2
answers question: http://stackoverflow.com/q/48066225
type: Answer

http://stackoverflow.com/q/48155914
has title: RedirectView.as_view not working at the root
has comment: http://stackoverflow.com/comment/83291316
score: 0
has body: In a django 1.8 project, I am attempting to redirect http://myProject/ads.txt to an external url http://a.location.that.has.the.ads.txt.file and thus serve the ads.txt file without using ftp to simply place the ads.txt in the root. Given this minimal directory structure: django projects myProject myapp urls.py views.py someotherapp yetanotherapp myProject settings.py urls.py (this is the top urls.py) views.py in myProject/myProject/urls.py, (the “top” urls.py) I have as the first entry in the urlpatterns list, the lines: urlpatterns = patterns('', (r'^ads\.txt', RedirectView.as_view(url='http://a.location.that.has.the.ads.txt.file', permanent=False)), followed by many more pattern matching regex’s. This does not work and fails with a 404. What does work is urlpatterns = patterns('', (r'^foo/ads\.txt', RedirectView.as_view(url='http://a.location.that.has.the.ads.txt.file', permanent=False)), and then calling http://myProject/foo/ads.txt Unfortunately, ads.txt files must be placed at the site root. I have tried many different regex’s that test fine in a regex validator, but just don’t work (returns 404). How do I do this without the extra dir “foo”? Any thoughts appreciated. Thank you.
has answer: http://stackoverflow.com/a/48242650
has comment: http://stackoverflow.com/comment/83291545
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48242650
has comment: http://stackoverflow.com/comment/83291849
type: Question
answer count: 1

http://stackoverflow.com/comment/83297867
score: 0
type: QuestionComment
has text: I get the following xpath when I look at the source. It doesn't seem to work. //*[@id="yui-gen2-button"] I have also tried xpath at various levels up.
type: Comment
comment on: http://stackoverflow.com/q/48159055

http://stackoverflow.com/comment/83309759
has text: You remove an element of a `list` while iterating it. Do **not** do that. You remove the first element and when the index moves on, the new second element is the formerly third... find a way to avoid that!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48165235
score: 2

http://stackoverflow.com/comment/83152608
type: AnswerComment
comment on: http://stackoverflow.com/a/48088723
type: Comment
has text: @PAstudilloE are you saying the y column is like {ec,us.. before running this code or after running this code?
score: 0

http://stackoverflow.com/a/48159309
upvote count: 1
has body: I suggest you store the table in a dictionary and use the built-in pickle module to load and save it. Here's the code I used to create a initial table dictionary and "pickle it" for testing (in actual use you might want to initialize it to empty or zero values): import pickle from pprint import pprint import random # Create table table = {} filename = 'table.pkl' height = 4 width = 10 for i in range(height): table[i] = [round(random.random()*100) for _ in range(width)] with open(filename, 'wb') as output: pickle.dump(table, output, pickle.HIGHEST_PROTOCOL) pprint(table) print('table created') Output showing values in table: {0: [75, 68, 51, 27, 3, 99, 50, 33, 99, 63], 1: [92, 79, 79, 66, 41, 18, 57, 9, 45, 75], 2: [34, 75, 67, 92, 38, 93, 28, 76, 75, 38], 3: [20, 10, 43, 48, 39, 16, 34, 75, 80, 16]} table created You can then load the data in the pickled file in the App.__init__() method and use it as shown: class App: def __init__(self, master): frame = Tkinter.Frame(master) self.data_readout = Tkinter.Button(frame, text="Collect Data", bd=10, height=2, width=10, command=lambda: self.dataReadout(self.table_values)) self.data_readout.grid(row=0, column=0, padx=5, pady=5) self.table_values = Tkinter.LabelFrame(frame, text="Values", borderwidth=10, relief=Tkinter.GROOVE, padx=10, pady=10) self.table_values.grid(row=1, column=0, padx=20, pady=20) # Read table. with open('table.pkl', 'rb') as infile: table = pickle.load(infile) # Use table. height = 4 width = 10 for i in range(height): #Rows for j in range(width): #Columns b = Tkinter.Entry(self.table_values, text="", width=5) b.grid(row=i, column=j) b.insert(0, str(table[i][j])) frame.grid(row=0, column=0, padx=20, pady=20) def dataReadout(self, frame): rowArr = [] colArr = [] info = frame.children.values() for children in frame.children.values(): info = children.grid_info() print(info) for i in info: print(i) Screenshot of app running. Note that the values being displayed are the same as those that were printed when t…
answers question: http://stackoverflow.com/q/48158903
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/49101404
has body: The proper way to avoid this problem is to use the @overload decorator to describe the relationship between the function's arguments and its results. The function get() will return a str (actually an Optional[str] since it may also return None) if it is passed a str and it will return a dictionary if it is passed a list. Here's how we describe that using type annotations: from typing import * def read_config() -&gt; Dict[str, str]: return {} def get_multiple(fields: List[str], config_data: Dict[str, str]) -&gt; Dict[str, str]: config_results = {k: v for k, v in config_data.items() if k in fields} return config_results def get_single(field: List[str], config_data: Dict[str, str]) -&gt; Optional[str]: result = config_data.get(field) return result @overload def get(fields: str) -&gt; Optional[str]: ... @overload def get(fields: List[str]) -&gt; Dict[str, str]: ... def get(fields): config_data = read_config() get_data = get_multiple if isinstance(fields, list) else get_single return get_data(fields, config_data) def get_ts_url() -&gt; None: timeout = get('timeout') if TYPE_CHECKING: reveal_type(timeout) If you run mypy on this it will print Revealed type is 'Union[builtins.str, builtins.None]' In the future I also recommend taking a few minutes before posting to simplify your example so that it is reproducible for others.
answers question: http://stackoverflow.com/q/48127642
type: Answer
score: 5
has comment: http://stackoverflow.com/comment/131500933
type: AcceptedAnswer
upvote count: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48127642

http://stackoverflow.com/q/48041557
has comment: http://stackoverflow.com/comment/83057885
has answer: http://stackoverflow.com/a/48043401
tagged with: pyinstaller
tagged with: python
has title: pyinstaller -- script not found.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83058529
has comment: http://stackoverflow.com/comment/83058661
type: Question
has answer: http://stackoverflow.com/a/48041611
has body: I'm trying to learn how to use pyinstaller to make an executable. I wrote a little script in 2.7 as a test. Print 'test" and named it test-print. When I click on the executable in the Build folder a cmd screen flashes, and that all she wrote. I tried adding a x = raw_input('input something: ') hoping that would cause the cmd screen, or some kind of screen to persist, but to no avail. I know this is basic stuff, but a voice of experience would be most helpful. F
has comment: http://stackoverflow.com/comment/83058402
score: 0
answer count: 2

http://stackoverflow.com/q/48055880
type: Question
score: 3
upvote count: 5
has answer: http://stackoverflow.com/a/48056064
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: AttributeError: __exit__ with socketserver on python-3.4.3
tagged with: python
accepted answer: http://stackoverflow.com/a/48056064
type: AnsweredQuestion
downvote count: 2
has body: I have two systems A Mac system running python 3.6.3 A linux (ubuntu 14.04) sytem running python 3.4.3 I've been testing the following code segment on both systems to try and identify the cause of a bug on the ubuntu system. import urllib.request import http.server import socketserver PORT = 8000 def requestHandler(request, client_address,server): # test to print to console when the handler is invoked. print("Request = " + str(request) + " Client Address = " + str(client_address) + " Server = " + str(server)) def startWebServer(): Handler = requestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever() def main(): startWebServer() main() On the Mac this works as expected, invoking the requestHandler and printing information to the console. However, on the ubuntu system I receive the following error. Traceback (most recent call last): File "sockettest.py", line 19, in &lt;module&gt; main() File "sockettest.py", line 17, in main startWebServer() File "sockettest.py", line 12, in startWebServer with socketserver.TCPServer(("", PORT), Handler) as httpd: AttributeError: __exit__ I am suspecting that I have misconfigured the ubuntu python installation. Could you suggest what I might have done wrong?

http://stackoverflow.com/comment/83135144
comment on: http://stackoverflow.com/q/48080480
type: Comment
type: QuestionComment
score: 0
has text: I have added the code from the image. please accept the edit

http://stackoverflow.com/a/55740216
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48131245
has body: following command worked for bokeh 1+ versions bokeh serve --show filename.py --allow-websocket-origin=*:5006

http://stackoverflow.com/a/48159647
downvote count: 0
has body: you may try this: In [378]: (a1[:, None] == a2).argmax(axis=0) Out[378]: array([4, 5, 1, 2, 8], dtype=int64)
accepted answer of: http://stackoverflow.com/q/48159608
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/48159608
score: 6
has comment: http://stackoverflow.com/comment/83301506
type: AcceptedAnswer

http://stackoverflow.com/comment/83297266
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48158824
has text: @RPGillespie: Agreed, but the OP did say, "as short as possible". One must be careful what one asks for.
score: 4

http://stackoverflow.com/comment/83055191
type: Comment
type: QuestionComment
has text: Fantastic, thanks @Divakar! If you want to put it as an answer I'll mark it as solved.
comment on: http://stackoverflow.com/q/48042218
score: 0

http://stackoverflow.com/q/48103119
downvote count: 0
possible better answer: http://stackoverflow.com/a/48103296
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83182727
has answer: http://stackoverflow.com/a/48103585
has body: I have coded an algorithm to carry out the dijkstra's algorithm. This is for a maths revision game I am making as part of my A level coursework. I have this data: Vertices: {'M', 'Y', 'X', 'C', 'F', 'Q'} Edges: defaultdict(&lt;class 'list'&gt;, {'X': ['Y'], 'C': ['M'], 'M': ['C', 'F', 'Y'], 'Q': ['F'], 'Y': ['X', 'M'], 'F': ['M', 'Q']}) Weights: {('M', 'C'): 44, ('Q', 'F'): 27, ('Y', 'X'): 42, ('X', 'Y'): 42, ('Y', 'M'): 6, ('M', 'F'): 9, ('M', 'Y'): 6, ('F', 'Q'): 27, ('F', 'M'): 9, ('C', 'M'): 44} These values are random, so different every time. What can I use to visualise the network to make it more clear, something like with nodes (vertices) and arcs (edges)? Or is there a way I can visualise it using print statements like print("o----o").
tagged with: python
tagged with: prims-algorithm
type: AnsweredQuestion
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/29438968
type: Question
accepted answer: http://stackoverflow.com/a/48103585
tagged with: algorithm
has answer: http://stackoverflow.com/a/48103377
has title: Drawing a network with nodes and edges in Python3
linked to: http://stackoverflow.com/q/28372127
has answer: http://stackoverflow.com/a/48103296
answer count: 3

http://stackoverflow.com/a/48081571
type: Answer
downvote count: 0
has body: SQLite computes results rows on demand, if possible. But this is not always possible, so there is no guarantee. You should never modify any table that you are currently reading in another query. (The database might scan the table in unobvious ways, so even changes to other rows might change the enumeration.) If you intend to do such modifications, you have to read all rows before doing the changes, e.g., for row in c.fetchall(). Alternatively, read the table in single steps that re-search for the place where the last query left, i.e.: SELECT ... FROM MyTable WHERE ID &gt; :LastID ORDER BY ID LIMIT 1;
has comment: http://stackoverflow.com/comment/85187799
score: 3
has comment: http://stackoverflow.com/comment/85191223
accepted answer of: http://stackoverflow.com/q/48081036
has comment: http://stackoverflow.com/comment/85198476
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48081036
upvote count: 3

http://stackoverflow.com/a/48039620
downvote count: 0
upvote count: 2
has body: If you are in control of the calling function, you can hack this to work reasonably well like: Code: import inspect def print_name_and_value(var): lines = inspect.stack()[1][4] var_name = ''.join(lines).strip().split('(')[-1].split(')')[0] print("%s: %d" % (var_name, var)) a = 5 print_name_and_value(a) Results: a: 5 How does this work? The inspect module can be used to inspect the caller, and get the line of code used by the caller. With a bit of string hacking the variable name (assuming it is a simple variable and not a more complex expression) can be gathered from the source code.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48039506
has comment: http://stackoverflow.com/comment/83089154
answers question: http://stackoverflow.com/q/48039506
type: Answer
score: 2

http://stackoverflow.com/a/48043450
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48040691
has body: Usually the mutliple worker approach with multiple queues is recommended but as you pointed out, the low priority queue/worker will be working concurrently next to the high priority worker. This is an interesting setup if you have a lot of small tasks that you want to have executed rather soon, thus you put them in the high priority queue while the longer tasks get pushed to the low priority queue. You could also have a setup where you simply give more resources (or a better machine) to the high priority worker. Since you would like a different solution I am going to suggest the priority parameter for apply_async. You do need a bit of setup for that as pointed out in a different question I answered recently and it only works for certain brokers. (For RabbitMQ it works since version 3.5.0.) After having set the x-max-priority on your queue and the additional settings as pointed out in the referenced answer you can simply put a priority on a task like this: your_task.apply_async(queue="your_queue_that_can_handle_priority", priority=10)
answers question: http://stackoverflow.com/q/48040691
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4

http://stackoverflow.com/q/48037294
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48037921
has comment: http://stackoverflow.com/comment/83045341
tagged with: numpy
has title: numpy map 2D array values
tagged with: arrays
answer count: 1
tagged with: iteration
favorite count: 0
has body: I'm trying to map values of 2D numpy array, i.e. to iterate (efficiently) over rows and append values based on row index. One of approaches I have tried is: source = misc.imread(fname) # Load some image img = np.array(source, dtype=np.float64) / 255 # Cast and normalize values w, h, d = tuple(img.shape) # Get dimensions img = np.reshape(img, (w * h, d)) # Flatten 3D to 2D # The actual problem: # Map (R, G, B) pixels to (R, G, B, X, Y) to preserve position img_data = ((px[0], px[1], px[2], idx % w, int(idx // w)) for idx, px in enumerate(img)) img_data = np.fromiter(img_data, dtype=tuple) # Get back to np.array but the solution raises: ValueError: cannot create object arrays from iterator Can anyone suggest how to perform efficiently this absurdly simple operation in numpy? It's out of my mind how intricate is this library... And why that code consumes a few gigs of memory for 7000x5000 px? Thanks
tagged with: python
tagged with: dictionary
type: UnansweredQuestion
score: 0
upvote count: 1

http://stackoverflow.com/comment/83234392
type: QuestionComment
comment on: http://stackoverflow.com/q/48128500
score: 0
has text: If you use positional arguments, why not just - https://eval.in/931591
type: Comment

http://stackoverflow.com/comment/83079096
comment on: http://stackoverflow.com/q/48053016
has text: Row-wise : `np.bitwise_xor(A,x[:,None])`. Col-wise : `np.bitwise_xor(A,x)`.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/48077115
tagged with: python
tagged with: merge
tagged with: dictionary
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/74848599
has comment: http://stackoverflow.com/comment/83128150
has body: I have below 2 dictionaries that I want to merge. I want to merge on the same keys and I want to keep the values of both the dictionary. I used dict1.update(dict2) but that replaced the values from 2nd to 1st dictionary. u'dict1', {160: {u'na': u'na'}, 162: {u'test_': u'qq', u'wds': u'wew'}, 163: {u'test_env': u'test_env_value', u'env': u'e'}, 159: {u'no' : u'test_no'} u'dict2', {160: {u'naa': u'na'}, 162: {u'envi_specs': u'qq', u'wds': u'wew'}, 163: {u'test_env': u'test_env_value', u'ens': u's'}} What I got? {160: {u'naa': u'na'}, 162: {u'envi_specs': u'qq', u'wds': u'wew'}, 163: {u'test_env': u'test_env_value', u'ens': u's'}} What I need {160: {u'naa': u'na', u'na': u'na'}, 162: {u'envi_specs': u'qq', u'wds': u'wew', u'test_': u'qq'}, 163: {u'test_env': u'test_env_value', u'ens': u's', u'env': u'e'}} I followed merging "several" python dictionaries but I have two different dictionaries that I need to merge. Help please...
has answer: http://stackoverflow.com/a/48077211
accepted answer: http://stackoverflow.com/a/48077211
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/74848599
linked to: http://stackoverflow.com/q/3232943
score: 4
linked to: http://stackoverflow.com/q/9415785
favorite count: 0
has title: merge two dictionary with same key

http://stackoverflow.com/q/48161445
has comment: http://stackoverflow.com/comment/83302563
has comment: http://stackoverflow.com/comment/83414739
has comment: http://stackoverflow.com/comment/83302291
has answer: http://stackoverflow.com/a/48161670
type: Question
score: 14
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83302399
has comment: http://stackoverflow.com/comment/83414980
has body: Current pandas version: 0.22 I have a SparseDataFrame. A = pd.SparseDataFrame( [['a',0,0,'b'], [0,0,0,'c'], [0,0,0,0], [0,0,0,'a']]) A 0 1 2 3 0 a 0 0 b 1 0 0 0 c 2 0 0 0 0 3 0 0 0 a Right now, the fill values are 0. However, I'd like to change the fill_values to np.nan. My first instinct was to call replace: A.replace(0, np.nan) But this gives TypeError: cannot convert int to an sparseblock Which doesn't really help me understand what I'm doing wrong. I know I can do A.to_dense().replace(0, np.nan).to_sparse() But is there a better way? Or is my fundamental understanding of Sparse dataframes flawed?
has comment: http://stackoverflow.com/comment/83423207
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/83302283
has title: Changing the fill_values in a SparseDataFrame - replace throws TypeError
has comment: http://stackoverflow.com/comment/83398730
has comment: http://stackoverflow.com/comment/83382500
downvote count: 1
possible better answer: http://stackoverflow.com/a/48161670
has comment: http://stackoverflow.com/comment/83423448
tagged with: sparse-matrix
favorite count: 0
tagged with: sparse-dataframe
has answer: http://stackoverflow.com/a/48214366
accepted answer: http://stackoverflow.com/a/48214366
has comment: http://stackoverflow.com/comment/83394985
has comment: http://stackoverflow.com/comment/83415027
has comment: http://stackoverflow.com/comment/83423164
tagged with: python
has comment: http://stackoverflow.com/comment/83395120
upvote count: 15

http://stackoverflow.com/comment/83122022
comment on: http://stackoverflow.com/q/48074225
score: 1
has text: have you added rest_framework in the installed_apps of your settings file
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48140571
upvote count: 2
has title: asyncio polling in the background with infinite printing
tagged with: multithreading
type: Question
has answer: http://stackoverflow.com/a/48174680
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-asyncio
type: UnansweredQuestion
has body: I would like to get a basic idea working in Python: Let's say I have a blocking call to a function that reads the current speed of a car (I use python-can for this, and wait for the corresponding message to appear on the bus). On the other hand, I have an infinite loop that prints as precisely as possible the speed of the car. What I would like is the value of the speed to be updated directly, so that the infinite loop can print it as soon as it changes. Right now I had three ideas: Call my get_speed function in the loop, and block. This works, but only if this is the only value I am willing to print (spoiler alert: it's not). If I want to print precisely the RPM too, I have to wait for the speed to be found, possibly missing multiple RPM value before. Create another "thread" (subprocess/multiprocessing/thread, whatever you call it) that updates a global variable. I know this works, but meh, I feel like I could have something smarter From what I saw in javascript, there is a way to ask a function for a result, and keep going until this result is found (this rings some CPU bells right now ahah). I kinda want something like this, which could make me do the following speed = get_speed() rpm = get_rpm() while True: print("RPM: {0} - Speed: {1}".format(rpm, speed)) This would (in my fairy world) actually display something like this: RPM: None - Speed: None # Function haven't returned yet, waiting RPM: None - Speed: None # Same here RPM: None - Speed: None # Same here RPM: 300 - Speed: None # get_rpm has returned RPM: 300 - Speed: None # Nothing happened RPM: 303 - Speed: 0 # get_rpm and get_speed have returned RPM: 303 - Speed: 0 RPM: 312 - Speed: 0 # etc. Right now what I have is something like this, which doesn't work (at all) #!/usr/bin/env python3 import datetime import asyncio import random from time import sleep async def _can_get_speed(): # My long function print ("In can_get_speed") sleep(4) print ("Out can_get_speed") r = random.randint(0, 10) print(r) return r …
has comment: http://stackoverflow.com/comment/83259297
tagged with: python
score: 2

http://stackoverflow.com/q/48125990
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48132252
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 7
has title: db.create_all() not creating tables in Flask-SQLAlchemy
type: Question
possible better answer: http://stackoverflow.com/a/48132252
has body: I am trying to create a database table for a user class model using Flask-SQLAclchemy and Postgres. My model class. from app import db class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(70), index=True, nullable=False) email = db.Column(db.String(70), index=True, unique=True, nullable=False) password = db.Column(db.String(128)) My app initialisation. from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object('app.instance.config.DevelopmentConfig') app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:RandomPass@localhost/BrightEventDb' SQLALCHEMY_TRACK_MODIFICATIONS = True db = SQLAlchemy(app) The following info is logged. 2018-01-06 11:53:09,978 INFO sqlalchemy.engine.base.Engine select version() 2018-01-06 11:53:09,979 INFO sqlalchemy.engine.base.Engine {} 2018-01-06 11:53:09,982 INFO sqlalchemy.engine.base.Engine select current_schema() 2018-01-06 11:53:09,982 INFO sqlalchemy.engine.base.Engine {} 2018-01-06 11:53:09,984 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1 2018-01-06 11:53:09,985 INFO sqlalchemy.engine.base.Engine {} 2018-01-06 11:53:09,986 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1 2018-01-06 11:53:09,987 INFO sqlalchemy.engine.base.Engine {} 2018-01-06 11:53:09,990 INFO sqlalchemy.engine.base.Engine show standard_conforming_strings 2018-01-06 11:53:09,991 INFO sqlalchemy.engine.base.Engine {}
has answer: http://stackoverflow.com/a/61557598
accepted answer: http://stackoverflow.com/a/48134006
tagged with: flask
has answer: http://stackoverflow.com/a/72776197
tagged with: python-2.7
linked to: http://stackoverflow.com/q/20744277
upvote count: 7
downvote count: 0
has answer: http://stackoverflow.com/a/48134006
tagged with: flask-sqlalchemy

http://stackoverflow.com/q/48162287
type: Question
has answer: http://stackoverflow.com/a/48162458
accepted answer: http://stackoverflow.com/a/48162458
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83304089
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83304133
has answer: http://stackoverflow.com/a/48164665
has body: Ok , Ive been searching around the site for solutions and I've found a few , but those cases do not work in my favor, mainly because they are using the 'wb' mode in the csv file , that's my argument as to my question is different as well as im using DictReader and Writer.basically, I want to loop through data in my csv file and if the data matches what is put inside of the delete_entry i want to completely remove that line from the csv file. I've come across the idea of just overwriting the unwanted line with the data already in the csv file, but I'm not sure how to approach that solution. I thought this was a logical solution, but what ends up happening is every line is deleted. import csv def delete_information_method(): #a tkinter entry global delete_entry #opening csv in read with open('employees.csv' , 'r') as emp_read: #creating our dictreader csv_dictreader = csv.DictReader(emp_read) #opening csv file again in write mode with open ('employees.csv' , 'w') as emp_write: #creating our writer csv_writer1 = csv.writer(emp_write) #our loop to check each line inside of our csv file is equal to what is inside the delete entry for line in csv_dictreader: if line['employee id'] == str(delete_entry): del line contents of csv file : first name,last name,email,DOB,adress,position,employee salary,employee id ronald,colyar,N/A,1-1-2029 ,11245 s. plaski,software dev,233333,233
has title: How can i completely get rid of a row in my csv file?
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48164665

http://stackoverflow.com/comment/83062199
score: 0
comment on: http://stackoverflow.com/q/48045371
type: QuestionComment
type: Comment
has text: have a look at [this link](https://stackoverflow.com/questions/45799042/installing-packages-from-a-list-using-pip)

http://stackoverflow.com/comment/83051787
type: Comment
comment on: http://stackoverflow.com/q/48040687
has text: updated my comment, I mistyped the enter instead of shift+enter ^-^
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83084320
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48052848
has text: btw: you can use `10` instead of `100/10`

http://stackoverflow.com/a/48018151
answers question: http://stackoverflow.com/q/48015074
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: Ok, why don't you just send a 'yes or no' flag from your flask app. Since you want to show the success or failure message without page refresh, getting jquery to update the DOM when your flask app returns a result. Something like return message in your flask app might do the trick accompained by success: function(e)({ $('body').append(e);});. Can't produce more code due to word length restriction on my phone, but tweaking your code along mine gets the job done. Cheers!

http://stackoverflow.com/q/48093976
upvote count: 1
has comment: http://stackoverflow.com/comment/83189402
possible better answer: http://stackoverflow.com/a/48106739
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48106739
has comment: http://stackoverflow.com/comment/83162658
has answer: http://stackoverflow.com/a/48094443
has body: I am a newcomer in Flask. Now I am coding methods of routing like this: @app.route("/categories") def categories(): return "" How to create a service and global helper function(class) in Flask to use in each route methods? Should it be class? For example I need to write a common function handleCategories() that should be called in some route methods.
score: 0
has comment: http://stackoverflow.com/comment/83162579
answer count: 2
has title: How to service/helper in Flask?
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/83162587
has comment: http://stackoverflow.com/comment/83162525
accepted answer: http://stackoverflow.com/a/48094443
tagged with: python
has comment: http://stackoverflow.com/comment/83162503
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83162577

http://stackoverflow.com/a/48073386
answers question: http://stackoverflow.com/q/48073161
has body: Note that dictionaries are unordered data structures, hence you can't expect any order in printing the items unless you use their ordered equivalent collections.OrderedDict(). Nevertheless, you can use a generator expression within str.join() method : In [4]: for key, value in A.items(): print(','.join(("{}: {}={}({})".format(key, t1,t2,t3) for t1, (t2, t3) in value.items()))) ...: test1: q0=0.123(0.234),test1: phi0=0.124(0.4325),test1: m=9.42(0.3413) test3: q0=0.343(0.353),test3: phi0=0.2341(0.235),test3: m=0.325(0.325),test3: z0=0.234(0.314) test2: q0=0.343(0.353),test2: phi0=0.2341(0.235) Also note that since we're doing the following inline unpacking it may raise a ValueError if number of the items in lists is more/less than two. for t1, (t2, t3) in value.items() Therefore, make sure that the number of unpacking variables match with the number of items in list.
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/91452830
downvote count: 0
type: Answer

http://stackoverflow.com/q/48134055
has comment: http://stackoverflow.com/comment/83246786
tagged with: python
duplicate of: http://stackoverflow.com/q/17778372
tagged with: recursion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83245378
has answer: http://stackoverflow.com/a/64912897
has comment: http://stackoverflow.com/comment/83245372
has comment: http://stackoverflow.com/comment/83245404
type: Question
answer count: 2
upvote count: 1
linked to: http://stackoverflow.com/q/17778372
has answer: http://stackoverflow.com/a/48134070
has body: I have the variable r of type dict. Variable item holds a list of items, and total_results is an int. As long as the condition is met that the number of items is less than the total amount of items, the function is called recursively. However, if I test whether the items are equal to the total results, the return statement returns None. Changing this elif to if does return the correct value. Could someone point me into the right direction to find out why returning r yields None in the elif or else block? Many thanks !! Relevant code snippet: if len(items) &lt; total_results: params['start_index'] = len(items) self.fetch_company_officers(company_number=company_number, items=items, **params) elif len(items) == total_results: r['items'] = items return r Full code: def fetch_company_officers(self, company_number, items=None, **kwargs): uri = 'company/{}/officers'.format(company_number) params = kwargs r = self.make_request(uri=uri, **params) # Test if items are set if items is None: items = r['items'] else: items.extend(r['items']) # Iterate multiple pages total_results = r['total_results'] if len(items) &lt; total_results: params['start_index'] = len(items) self.fetch_company_officers(company_number=company_number, items=items, **params) elif len(items) == total_results: # TO DO: ?? r['items'] = items return r
has title: Python function returns None in elif or else
favorite count: 0
has comment: http://stackoverflow.com/comment/83245487
tagged with: return
type: UnansweredQuestion

http://stackoverflow.com/comment/83048133
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48034675
has text: @dahrens i think when i deploy my django app to heroku it doesnt include my settings.py that's why even though i set debug=False in deployment it is set to true.

http://stackoverflow.com/comment/83251542
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48131558
has text: try: W = tf.Variable(rng.randn(4,1), name="weight",dtype=tf.float64) pred = tf.matmul(X,W) + b # leave the rest lines unchanged with tf.Session() as sess: ... sess.run(init) ... for epoch in range(training_epochs): ... sess.run(optimizer, feed_dict={X:X_train,Y:Y_train})
type: AnswerComment

http://stackoverflow.com/comment/83241311
has text: # storing data in 2.7 pickled_data = pickle.dumps(scraped_data) local_city.update({'location_name':'Boston'}, {"$set": {"Weather": pickled_data}}) # (attempted) unpickling of data in python 3 db_cursor = local_city.find_one({"location_name": 'Boston'}) unpickled_data = pickle.loads(db_cursor["Weather"], fix_imports=True) # Error msg TypeError: a bytes-like object is required, not 'str'
comment on: http://stackoverflow.com/q/48127261
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48065031
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/83106071
type: Answer
has body: The default quoting behaviour should work fine: In [7]: !cat test.csv A,B,C,D 12,22000,"3,9","8,5" In [8]: pd.read_csv('test.csv', decimal=',', sep=',') Out[8]: A B C D 0 12 22000 3.9 8.5
accepted answer of: http://stackoverflow.com/q/48064446
answers question: http://stackoverflow.com/q/48064446
has comment: http://stackoverflow.com/comment/83106372

http://stackoverflow.com/a/56991722
upvote count: 2
answers question: http://stackoverflow.com/q/48028022
has comment: http://stackoverflow.com/comment/100552136
accepted answer of: http://stackoverflow.com/q/48028022
has comment: http://stackoverflow.com/comment/137621560
has body: from pynput.keyboard import Listener def on_press(key): if str(key) == '&lt;179&gt;': # play pause media key was pressed if str(key) == '&lt;176&gt;': # next key was pressed if str(key) == '&lt;177&gt;': # previous key was pressed def on_release(key): pass listener_thread = Listener(on_press=on_press, on_release=None) # This is a daemon=True thread, use .join() to prevent code from exiting listener_thread.start() pynput~=1.4.5 Don't use the latest version until this issue is fixed
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/137610518
score: 2

http://stackoverflow.com/comment/83113534
type: Comment
comment on: http://stackoverflow.com/a/48055703
has text: Thank you very much I will go ahead and try that ;)
score: 0
type: AnswerComment

http://stackoverflow.com/q/48086131
has answer: http://stackoverflow.com/a/48086177
answer count: 3
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83147241
has answer: http://stackoverflow.com/a/58384479
has comment: http://stackoverflow.com/comment/83147291
has answer: http://stackoverflow.com/a/67586117
favorite count: 0
has title: Regular Expression for Finding Numbers in a Line (Python)
tagged with: python
type: AnsweredQuestion
has body: I'm just learning about regular expressions and I need to read in a text file and find every instance of a number and find the sum of all the numbers. import re sum = 0 list_of_numbers = list() working_file = open("sample.txt", 'r') for line in working_file: line = line.rstrip() working_list = re.findall('[0-9]+', line) if len(working_list) != 1: continue print(working_list) for number in working_list: num = int(number) list_of_numbers.append(num) for number in list_of_numbers: sum += number print(sum) I put the print(working_list) in order to try and debug it and see if all the numbers are getting found correctly and I've seen, by manually scanning the text file, that some numbers are being skipped while others are not. I'm confused as to why as I thought my regular expression guaranteed that any string with any amount of digits will be added to the list. Here is the file.
score: 1
possible better answer: http://stackoverflow.com/a/58384479
type: Question
accepted answer: http://stackoverflow.com/a/48086177

http://stackoverflow.com/comment/83230865
has text: it was not what it was about yet, but I already have a solution. though not perfect :) thanks for your time!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48121353
type: Comment

http://stackoverflow.com/comment/83099903
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48053265
type: Comment
has text: Thanks, Nae. This is exactly the functionality I needed. However, I'll have several audios and it would be great to have a single check_entry function that works for all of them. Do you know how to achieve it?

http://stackoverflow.com/q/48015571
has answer: http://stackoverflow.com/a/48015593
type: Question
accepted answer: http://stackoverflow.com/a/48015593
has comment: http://stackoverflow.com/comment/83000421
possible better answer: http://stackoverflow.com/a/48015578
upvote count: 4
has comment: http://stackoverflow.com/comment/83000435
has body: In the following code that I wrote, n = 4, and so there are five if statements, so if I would like to increase n to be, say 10, then there will be a lot of if's. Therefore my question: how can I replace all the if statements with something more elegant? n, p = 4, .5 # number of trials, probability of each trial s = np.random.binomial(n, p, 100) # result of flipping a coin 10 times, tested 1000 times. d = {"0" : 0, "1" : 0, "2" : 0, "3" : 0, "4" : 0 } for i in s: if i == 0: d["0"] += 1 if i == 1: d["1"] += 1 if i == 2: d["2"] += 1 if i == 3: d["3"] += 1 if i == 4: d["4"] += 1 I tried using nested for loops, for i in s: for j in range(0,5): if i == j: d["j"] += 1 But i get this error: d["j"] += 1 KeyError: 'j'
has answer: http://stackoverflow.com/a/48017078
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48015578
answer count: 4
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48015627
has comment: http://stackoverflow.com/comment/83000420
downvote count: 2
has title: Replacing repeated if statements with nested for loops in python?
tagged with: loops

http://stackoverflow.com/q/48125438
answer count: 2
has comment: http://stackoverflow.com/comment/83227861
has body: So, have a look at the following code: import numpy as np import pandas as pd def answer_one(): energy = pd.read_excel(io = "Energy Indicators.xls", header = 9, parse_cols = "C:F", skip_footer = 38) return energy answer_one() It produces the following output: Now, when I make a little modification to the code, as below, it changes the output completely: def answer_one(): energy = pd.read_excel(io = "Energy Indicators.xls", header = 9, parse_cols = "C:F", skip_footer = 38, skiprows = 8) return energy answer_one() The output that I get is as follows: Depending upon the argument that I give to the "skiprows" parameter, the output changes itself. I am unable to understand why does changing the value of "skiprows" affect the headers of the dataframe, when we are keeping the argument of the "headers"parameter unchanged? Please find the data file (.xlsx file) here Any help please? I use Pandas v0.19.2. Also, please don't tag my question as "duplicate". I lose points man. I tried reasonably well to find an existing question, but could not.
has comment: http://stackoverflow.com/comment/83227643
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48125588
tagged with: pandas
tagged with: python
upvote count: 1
accepted answer: http://stackoverflow.com/a/48125588
has comment: http://stackoverflow.com/comment/83227848
has title: pandas - Why am I unable to skip rows using the "skiprows" parameter of Pandas
type: Question
linked to: http://stackoverflow.com/q/27325652
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48125527
has answer: http://stackoverflow.com/a/48125527

http://stackoverflow.com/a/48146411
has comment: http://stackoverflow.com/comment/83292517
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48145966
accepted answer of: http://stackoverflow.com/q/48145966
has body: I do not really know the module OData. It seems to be deprecated, abandoned or similar as you could see on the Pypi repository (link). Anyways, have you tried retrieving the data using requests? import requests url_test = 'http://services.odata.org/V3/OData/OData.svc/Products?$format=json' r = requests.get(url_test) r_json = r.json() for value in r_json['value']: print(value['ID']) This seems to work for me.
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83304341
has comment: http://stackoverflow.com/comment/106846163

http://stackoverflow.com/comment/83298809
score: 1
has text: @MaxU Thanks! Should've thought of that, heheh.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48159402

http://stackoverflow.com/a/48045300
score: 0
type: Answer
has body: In your case, I think str1.split()[1] might help
answers question: http://stackoverflow.com/q/48045260

http://stackoverflow.com/q/48151935
type: UnansweredQuestion
score: 2
tagged with: pyqt
has title: pyQt GroupBox alignment
downvote count: 0
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/68436074
upvote count: 2
tagged with: pyqt5
answer count: 1
has comment: http://stackoverflow.com/comment/83285722
has body: I've got a real problem in making the alignment of the header of QGroupBox when i change the width of a border. Initially i have something like this: First filter And when I change stylesheet of this groupbox self.filter.setStyleSheet("QGroupBox {border-style: solid; border-width: 1px; border-color: black; text-align: left;}") The header of the filter "goes down" like this: Second one Is there any way to set centered alignment for bold frame of the groupbox?

http://stackoverflow.com/q/48077878
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48080210
has comment: http://stackoverflow.com/comment/83130150
score: 0
has answer: http://stackoverflow.com/a/48080210
has title: Pandas dataframe groupby top N items
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/87646814
type: Question
has comment: http://stackoverflow.com/comment/83129624
has comment: http://stackoverflow.com/comment/83130123
tagged with: group-by
has answer: http://stackoverflow.com/a/48078169
has comment: http://stackoverflow.com/comment/83129781
accepted answer: http://stackoverflow.com/a/48078169
answer count: 2
has body: I have pandas dataframe in the following format: df = pd.DataFrame(data={'item_code': ['Item1', 'Item2', 'Item3', 'Item1', 'Item1', 'Item2', 'Item2', 'Item1', 'Item3'], 'dollar_amount': ['200.25', '350.00', '120.00', '400.50', '1001.25', '700.00', '350.00', '200.25', '240.00'], 'supplier_code': ['Sup1','Sup1','Sup2','Sup1','Sup1','Sup1','Sup1','Sup2','Sup2']}) This is how this dataframe looks: dollar_amount item_code supplier_code 0 200.25 Item1 Sup1 1 350.00 Item2 Sup1 2 120.00 Item3 Sup2 3 400.50 Item1 Sup1 4 1001.25 Item1 Sup1 5 700.00 Item2 Sup1 6 350.00 Item2 Sup1 7 200.25 Item1 Sup2 8 240.00 Item3 Sup2 I can get the top N Items summed up by dollar_amount with this: a = data.groupby('item_code', as_index=False).sum() cnt_srs = a'item_code','dollar_amount'.sort_values(by=['dollar_amount'], ascending=False).head(15) cnt_srs Sample output top-5 items (not of the above data): item_code dollar_amount 173 Item1 8,776,906.5400 442 Item2 2,085,528.8170 367 Item3 2,033,746.0500 25 Item4 1,635,830.4040 537 Item5 1,485,672.4050 Now I want the supplier_codes for these items. I can get the supplier_code and its most frequently supplied item using this: N = 1 df1 = data.groupby(['supplier_code'])['item_code'].value_counts().groupby('supplier_code').head(N) df1 Sample Output: supplier_code item_code Sup1 Item4 9 Sup2 Item2 21 Sup3 Item1 7 Sup4 Item5 173 Sup5 Item3 1 Sup6 Item6 12 I want to get the top N Item and their Supplier where top N items are determined by the sum of their dollar amounts. Expected Output: item_code dollar_amount SupplierCode TopItem1 8,776,906.5400 Sup4 TopItem2 2,085,528.8170 Sup1 TopItem3 2,033,746.0500 Sup3 TopItem4 1,635,830.4040 Sup1 TopItem5 1,485,672.4050 Sup2 I want the top N Items(In terms of dollar_amount) and the corresponding Supplier_codes Thank you so much for all the help up till now.
has comment: http://stackoverflow.com/comment/87646895
favorite count: 0
tagged with: pandas-groupby
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/83240709
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48131742
has text: Here's a pretty good introduction to python formatting: https://pyformat.info/

http://stackoverflow.com/comment/83214147
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48118152
has text: The exact command python is running is: Command task instance [c_Run_Code]: running command [Test_Scrape], with command value [cmd /c "C\Python27\python.exe C\Documents\Python\Test_Scrape.py"]. I'm not sure how to check if the id has appropriate access to the script

http://stackoverflow.com/comment/83019306
type: AnswerComment
has text: It’s doesn’t even display nothing with this
score: 0
comment on: http://stackoverflow.com/a/48024895
type: Comment

http://stackoverflow.com/comment/83062157
comment on: http://stackoverflow.com/q/48045081
has text: Looking into this a little deeper, it looks like when you specify a top level directory and a start directory as a file system path, the loader thinks you are explicitly asking to load tests configured in the start directory's `__init__.py`. I'm guessing that they raise an `ImportError` in this case because there's no reasonable way to determine that the start directory should be treated as a namespace package (because of file system semantics versus package semantics). It definitely seems like the docs could be a little more clear about this.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83162776
score: 0
type: AnswerComment
has text: @Prabu Yes, this answer is what you asked for right? And besides this was the first answer. Please accept this one. Thats why we always ask to show ur effort in solving the problem which gives us the indication of what exactly is that you want. Post another question if you have a follow up
comment on: http://stackoverflow.com/a/48090774
type: Comment

http://stackoverflow.com/q/48162419
type: Question
has comment: http://stackoverflow.com/comment/83304143
tagged with: sorting
upvote count: 2
has answer: http://stackoverflow.com/a/48162482
has answer: http://stackoverflow.com/a/48162538
accepted answer: http://stackoverflow.com/a/48162538
possible better answer: http://stackoverflow.com/a/48162486
favorite count: 0
has answer: http://stackoverflow.com/a/48162511
tagged with: python
has answer: http://stackoverflow.com/a/48162486
answer count: 4
score: 2
type: AnsweredQuestion
downvote count: 0
has body: So I have a list like below: points = [[0, 0], [5, 3], [0, 5], [0, 2], [1, 3], [5, 3]] I have been using points.sort(key=lambda pair: pair[0]) to sort the list. But this only sorts it by first value without looking at the second value. The result of this code is as below: [[0, 0], [0, 5], [0, 2], [1, 3], [5, 3], [5, 3]] However, I want to sort is such that the result is: [[0, 0], [0, 2], [0, 5], [1, 3], [5, 3], [5, 3]] How do I do it? Also, while we are at it, how do i remove the duplicates from this list? The final result should be like: [[0, 0], [0, 2], [0, 5], [1, 3], [5, 3]]
linked to: http://stackoverflow.com/q/20145842
has title: Sorting a list of list

http://stackoverflow.com/q/48080579
score: 2
upvote count: 2
has title: Django - when best to calculate statistics on large amounts of data
tagged with: django
has body: I'm working on a Django application that consists of a scraper that scrapes thousands of store items (price, description, seller info) per day and a django-template frontend that allows the user to access the data and view various statistics. For example: the user is able to click on 'Item A', and gets a detail view that lists various statistics about 'Item A' (Like linegraphs about price over time, a price distribution, etc) The user is also able to click on reports of the individual 'scrapes' and get details about the number of items scraped, average price. Etc. All of these statistics are currently calculated in the view itself. This all works well when working locally, on a small development database with +/100 items. However, when in production this database will eventually consist of 1.000.000+ lines. Which leads me to wonder if calculating the statistics in the view wont lead to massive lag in the future. (Especially as I plan to extend the statistics with more complicated regression-analysis, and perhaps some nearest neighbour ML classification) The advantage of the view based approach is that the graphs are always up to date. I could offcourse also schedule a CRONJOB to make the calculations every few hours (perhaps even on a different server). This would make accessing the information very fast, but would also mean that the information could be a few hours old. I've never really worked with data of this scale before, and was wondering what the best practises are.
linked to: http://stackoverflow.com/q/9300922
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48080725
tagged with: database
has comment: http://stackoverflow.com/comment/83135309
type: Question
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48080725
tagged with: python
has comment: http://stackoverflow.com/comment/120578848

http://stackoverflow.com/q/48015368
tagged with: django
tagged with: python
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/82999997
has body: Take the following as an example: class Manufacturer(models.Model): name = models.CharField(max_length=200, blank=False) slug = models.SlugField(max_length=200, blank=False, unique=True) class Category(models.Model): name = models.CharField(max_length=200, blank=False) slug = models.SlugField(max_length=200, blank=False, unique=True) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') manufacturer = models.ForeignKey(Manufacturer, related_name='products') name = models.CharField(max_length=50, blank=False) slug = models.SlugField(max_length=200, blank=False, unique=True) class CarMixin(models.Model): color = models.CharField(max_length=50, blank=False) num_wheels = models.IntegerField() class CellPhoneMixin(models.Model): screen_size = models.IntegerField() class Car(Product, CarMixin): pass class Food(Product): pass class CellPhone(Product, CellPhoneMixin): pass what I am trying to do is create a 'base' class called Product and apply a variety of 'sub-product-types' using Model Inheritance. The reason I am not using the Django's 'Abstract Model Inheritance' is because I actually want a table in my DB to hold all the products, so I can make a query like Product.objects.all() to get all the products, then type product.car to get all the field values for the related Car object. However, the problem I am running into is that a product can have a relationship with any one of Car, Food or CellPhone. So, I can't do product.car if it has a relationship with Food. There is no way in knowing which 'relationship' a Product object has. Is it related to Car? Food? CellPhone? How should I approach this? Is there a better database schema I should be using?
type: Question
has comment: http://stackoverflow.com/comment/83002257
has comment: http://stackoverflow.com/comment/83001968
has comment: http://stackoverflow.com/comment/83002004
tagged with: inheritance
has comment: http://stackoverflow.com/comment/83002118
downvote count: 0
has comment: http://stackoverflow.com/comment/83000077
has title: Django Model Inheritance - Query parent model for 'unknown' relationship
has comment: http://stackoverflow.com/comment/82999965
has comment: http://stackoverflow.com/comment/83000600
has comment: http://stackoverflow.com/comment/83000025
favorite count: 0
tagged with: model
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83002041

http://stackoverflow.com/a/48017049
has body: You can use tag.attrs to get all the attributes of a tag. from bs4 import BeautifulSoup as bs s = """&lt;div id="vote_text_247231" class="left action_unclicked_show cursor" style="width:97px;margin-left:3px;" data-counttext="191 votes" data-actiontext="VOTE!" onmouseover="user_action_button_mouseover('vote','247231')" onmouseout="user_action_button_mouseout('vote', '247231')" onclick="loginPrompt(&amp;#x27;vote&amp;#x27;);clickTrack(&amp;quot;photo_vote&amp;quot;);"&gt;""" soup = bs(s, "lxml") votes = soup.find("div", {"id": "vote_text_247231"}) votes.attrs output {'class': ['left', 'action_unclicked_show', 'cursor'], 'data-actiontext': 'VOTE!', 'data-counttext': '191 votes', 'id': 'vote_text_247231', 'onclick': 'loginPrompt(\'vote\');clickTrack("photo_vote");', 'onmouseout': "user_action_button_mouseout('vote', '247231')", 'onmouseover': "user_action_button_mouseover('vote','247231')", 'style': 'width:97px;margin-left:3px;'}
type: Answer
answers question: http://stackoverflow.com/q/48016895
score: 0

http://stackoverflow.com/q/48136738
type: Question
tagged with: k-means
tagged with: cluster-analysis
has comment: http://stackoverflow.com/comment/83251201
score: 0
tagged with: python
has body: I have a dataset of an ecommerce store that contains orders made within a month. One customer could have multiple records in the dataset, as expected. When I performed kmeans using python, the resulting clusters were overlapping by the customers that made multiple orders, but to different products. The problem is I want to provide recommendations for each customer, but I cannot determine which cluster to pick for such customers. Thanks in Advance # K-Means Clustering # Importing the libraries import numpy as np np.set_printoptions(threshold=np.inf) import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import LabelEncoder,OneHotEncoder # Importing the dataset dataset = pd.read_csv('FYP.csv') X = dataset.iloc[:, [10]].values Y=dataset.iloc[:, [9]].values Z=dataset.iloc[:,[5]].values #The First Way Using LabelEncoder to change categorical values to numerical ones labelencoder_X = LabelEncoder() X=labelencoder_X.fit_transform(X[:,0]) labelencoder_Y = LabelEncoder() Y=labelencoder_Y.fit_transform(Y[:,0]) done = np.vstack((Y,X)).T done = np.column_stack((Z,Y,X)) #The Second Way onehotencoder_done = OneHotEncoder(categorical_features="all") done = onehotencoder_done.fit_transform(done).toarray() #Then Applying PCA from sklearn.decomposition import PCA pca = PCA(n_components=2) done = pca.fit_transform(done) explained_variance = pca.explained_variance_ratio_ # Using the elbow method to find the optimal number of clusters from sklearn.cluster import KMeans wcss = [] for i in range(1, 11): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 1000, n_init = 10) kmeans.fit(done) wcss.append(kmeans.inertia_) plt.plot(range(1, 11), wcss) plt.title('The Elbow Method') plt.xlabel('Number of clusters') plt.ylabel('WCSS') plt.show() # Fitting K-Means to the dataset kmeans = KMeans(n_clusters = 3, init = 'k-means++', max_iter = 1000, n_init = 10) y_kmeans = kmeans.fit_predict(done) # Visualising the clusters plt.scatter(done[y_kmeans == 0, 0], done[y…
has comment: http://stackoverflow.com/comment/83264291
has comment: http://stackoverflow.com/comment/83251475
answer count: 0
type: UnansweredQuestion
has title: Duplicate Ids in kmeans clustering

http://stackoverflow.com/a/48132072
answers question: http://stackoverflow.com/q/48132038
score: 0
has body: import pandas as pd df = pd.DataFrame({'foo':[x.split('[')[0] for x in ['a','b[b7','c']]}) print(df)
type: Answer

http://stackoverflow.com/comment/83210989
has text: Are you sure you always gets a valid "result" value, in every cycle of your infinite loop? This could be a lead, since if in one of your iterations the results are invalid, so of-course your keys iteration won't fail, but direct-access does.
comment on: http://stackoverflow.com/q/48117272
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83174921
type: AnswerComment
has text: What is your tensorflow version? Works for me in 1.4.1. I also don't see this check in the source code of tensorflow.
comment on: http://stackoverflow.com/a/48099304
type: Comment
score: 0

http://stackoverflow.com/comment/83040315
score: 0
comment on: http://stackoverflow.com/q/48035032
type: Comment
type: QuestionComment
has text: in the case of `my_validator = QRegExpValidator(my_reg_ex, self.ui.lineEdit_test)` you are just passing him a parent.

http://stackoverflow.com/a/48143941
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48143529
answers question: http://stackoverflow.com/q/48143529
type: Answer
has body: To calculate the Standard Error of mean for a certain key, you first need to find the standard deviation for that key: Formula for SEM: e = o/sqrt(n), where s is the SEM, o is the standard deviation, and n is the sample size (1): import statistics #for simple calculation of the standard deviation of a list A=[ {'key1' : 1, 'key2' : 21, 'key3':31, 'key5':51, 'key6':61}, {'key2': 22, 'key3' : 32, 'key5':52, 'key6':62}, {'key1':13, 'key2':23, 'key4':43, 'key5':53}, {'key1':14, 'key3':34, 'key4':44, 'key5':54, 'key6':64}, {'key4':45, 'key5':55, 'key6':65}] full_keys = set([i for b in [c.keys() for c in A] for i in b]) data_listings = {i:list(filter(lambda x:x is not None, map(lambda y:y.get(i), A))) for i in full_keys} error_listing = {a:statistics.stdev(b)/float(len(b)) for a, b in data_listings.items()} Output: {'key5': 0.31622776601683794, 'key1': 2.4113927126900783, 'key3': 0.5091750772173155, 'key4': 0.3333333333333333, 'key6': 0.45643546458763845, 'key2': 0.3333333333333333}
score: 0

http://stackoverflow.com/comment/83218789
type: Comment
type: AnswerComment
has text: Yes, adding padding will allow for more complex movement of the camera if needed in future, Be sure to consider it in the future!
score: 0
comment on: http://stackoverflow.com/a/48043743

http://stackoverflow.com/q/48157312
has comment: http://stackoverflow.com/comment/83294338
score: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83294328
answer count: 0
tagged with: formset
has comment: http://stackoverflow.com/comment/83294283
linked to: http://stackoverflow.com/q/25331500
type: Question
has title: ManagementForm data missing when saving intermediate M2M table
has comment: http://stackoverflow.com/comment/83293984
tagged with: m2m
has body: ManagementForm data missing error while formset validation I get this error when I try to save a parent form with intermediate m2m table child formset. I don't know how to solve because the lack of information about this error in Traceback. Please help! models.py class Material(models.Model): name = models.CharField(max_length=200) familiy = models.ForeignKey(Material_family, on_delete=models.CASCADE, null=True) … class Purchase(models.Model): number = models.IntegerField() date = models.DateField() … class Purchase_detail(models.Model): material = models.ForeignKey(Material, on_delete=models.CASCADE) purchase = models.ForeignKey(Purchase, on_delete=models.CASCADE) quantity = models.IntegerField() unit_value = models.IntegerField(default=0) forms.py class PurchaseModelForm(forms.ModelForm): class Meta: model = Purchase fields = (‘number’,’date’ , ’…’) def __init__(self, *args, **kwargs): super(PurchaseModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.form_id = 'id-purchase-form' self.helper.form_method = 'post' class Purchase_detailModelForm(forms.ModelForm): class Meta: model = Purchase_detail fields = ('material','quantity','unit_value') def __init__(self, *args, **kwargs): super(Purchase_detailModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.form_id = 'id-purchase-form' self.helper.form_method = 'post' self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap3/layout/inline_field.html' DetailFormSet = forms.inlineformset_factory(Purchase, Purchase_detail, form=Purchase_detailModelForm, extra=1) views.py def purchase_new(request, purchase_id=None, *args, **kwargs): template = 'erp/purchase_form.html' if purchase_id: inst = Purchase.objects.get(pk=purchase_id) else: inst = Purchase() if request.method == 'POST': form = PurchaseModelForm(request.POST or None, request.FILES, prefix='purchase', instance=inst) formset = DetailF…

http://stackoverflow.com/comment/83271398
comment on: http://stackoverflow.com/q/48146608
has text: What error are you getting? what is `cave_`? please read [ask] and [mcve]
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83070576
has text: i think ur element is not on the screen viwe mode. First get back the element into the screens center point
comment on: http://stackoverflow.com/a/48048924
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48141407
answer count: 3
has answer: http://stackoverflow.com/a/48143108
tagged with: discord.py
has title: How would I make my Python 3.6.1 Discord bot create a new text channel in a server?
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83260896
accepted answer: http://stackoverflow.com/a/48143108
favorite count: 0
has answer: http://stackoverflow.com/a/76536124
type: Question
has answer: http://stackoverflow.com/a/69678017
tagged with: python
tagged with: discord
has body: I have been reading the documentation. The documentation shows this example: channel = await guild.create_text_channel('cool-channel') I need to figure out what to do with guild so that there is no NameError regarding guild. (Do I have to import guild? etc.) Documentations: http://discordpy.readthedocs.io/en/rewrite/api.html#discord.Guild.create_text_channel http://discordpy.readthedocs.io/en/rewrite/api.html#guild
upvote count: 2
possible better answer: http://stackoverflow.com/a/69678017

http://stackoverflow.com/comment/83228142
comment on: http://stackoverflow.com/a/48125512
has text: Thats actually too specific (Just changing one row) at a time: Just think if I have 100 different names, all of them need to be converted to the APL price when there dates in the row are the same as APL date.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48143394
accepted answer: http://stackoverflow.com/a/48143502
score: 0
answer count: 2
has body: So I play a game in which I have 12 pieces of gear. Each piece of gear (for the purposes of my endeavor) has four buffs I am interested in: power, haste, critical damage, critical rating. I have a formula in which I can enter the total power, haste, CD, and CR and generate the expected damage per second output. However, not every piece of gear has all four buffs. Currently I am interested in two case scenarios: gear that only has one of the four, and gear that has three of the four. In the first scenario, each of the twelve pieces of gear will have a single buff on it that can be any of the four. What I want to do is write a program that finds which arrangement outputs the most damage. So then what I need to do is write a program that tries every possible arrangement in this scenario. If we figure that each of the twelve pieces can have one of four values, that's 4^12 possible arrangements to test - or 16,777,216 - easy-peasy for a machine, right? However I have to loop through all these arrangements, and at the moment I can only imagine 12 nested FOR loops of value 1-4 each, with the formula in the middle. This seems un-pythonic in terms of readability and just duplication of effort. Is there a better, more pythonic way to check to see which my formula likes best (generates max damage), or is 12 nested FOR loops, as excessive as that seems, the best and clearest way?
tagged with: nested
has comment: http://stackoverflow.com/comment/83265100
has comment: http://stackoverflow.com/comment/83264972
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48144205
has comment: http://stackoverflow.com/comment/83264984
has answer: http://stackoverflow.com/a/48143502
tagged with: loops
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/48144205
has title: Python code: Are 12 nested for loops really the best answer?
has comment: http://stackoverflow.com/comment/83264952

http://stackoverflow.com/comment/82999850
has text: Ok, so you have a the distribution of a random variable (let's call it `X`) that is log-normally distributed. You have the log base 10 of the values for the mean and standard deviation of `X`: `log10(mu)` and `log10(sigma)`? Given these, you want to draw more numbers from the same distribution as `X`?
type: Comment
comment on: http://stackoverflow.com/q/48014712
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83337767
has text: I tried. This is not helping. I actually use **bold font** to emphasize what is different from 2 screenshot. Please read the questions again and try this [url](https://www.staples.com/dell-i5567-7526gry-15-6-laptop-computer-intel-i7-256gb-ssd-8gb-ddr4-win-10-intel-hd-graphics-620/product_2677757)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48164705

http://stackoverflow.com/a/48161453
has comment: http://stackoverflow.com/comment/83306477
answers question: http://stackoverflow.com/q/48159415
type: Answer
has body: but when I'm trying to perform such get request using python, it shows no info. What am I doing wrong? The request result shows no info because there is no cookie data in the python HTTP request. If you check the HTTP request in browser debug window, you can see there is cookie along with the request -- the cookie identifies who the client is and tells server "Hi, server, I'm a valid user": With reasonable guess, in this biman-airlines.com case, the server would check the cookie and return result only if the cookie is valid. Thus, you need to add your Cookie header in the python code: # The cookie below is just for example, you would get your own cookie once visiting the website. headers = { 'Cookie': 'chocolateChip=nbixfy44dvziejjdxd2wmzs3; BNI_bg_zapways=0000000000000000000000009301a8c000005000; ASPSESSIONIDSQDCSSDT=PFJPADACFOGBDMONPBHPMFJN' } print(requests.get('https://www.biman-airlines.com/bookings/flight_selection.aspx?TT=RT&amp;SS=&amp;RT=&amp;FL=on&amp;DC=DAC&amp;AC=ZYL&amp;AM=2018-01&amp;AD=09&amp;DC=&amp;AC=&amp;AM=&amp;AD=&amp;DC=&amp;AC=&amp;AM=&amp;AD=&amp;DC=&amp;AC=&amp;AM=&amp;AD=&amp;RM=2018-01&amp;RD=10&amp;PA=1&amp;PT=&amp;PC=&amp;PI=&amp;CC=&amp;NS=&amp;CD=&amp;FS=B4B9631', headers=headers).text)
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83314704
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48159415

http://stackoverflow.com/q/48058080
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83105074
has comment: http://stackoverflow.com/comment/83089348
tagged with: python
downvote count: 2
tagged with: stack-trace
type: Question
has comment: http://stackoverflow.com/comment/83089283
has body: I have a pretty basic doubt here. Please consider the below sample C program being run on an Ubuntu 32 bit little endian machine. #include &lt;string.h&gt; #include &lt;unistd.h&gt; int main (int argc, char **argv) { char buf [8]; strcpy(buf, argv[1]); system("/usr/bin/false"); } Now I understand the security implications of the above code. Let us keep that aside for a while. In the above code buf is a local variable. This means that the space for this buffer would be on the stack. Now we use strcpy() to copy user input onto the buffer. The user input itself is taken on the command line. Now say the program is run with gdb as: gdb program Now if the user input is given to the program, from the gdb prompt, as : run python -c "print 'A'*12 + '\x10\x83\x04\x08' + '\xda\x84\x04\x08' + '\x24\xa0\x04\x08' + '\x62\x81\x04\x08' + '\x10\x83\x04\x08' + '\xda\x84\x04\x08' + '\x25\xa0\x04\x08' + '\xd8\x80\x04\x08' + '\x10\x83\x04\x08' + '\xda\x84\x04\x08' + '\x26\xa0\x04\x08' + '\x13\x85\x04\x08' + '\x20\x83\x04\x08' + 'A'*4 + '\x24\xa0\x04\x08';" the contents of the stack look like: (gdb) x/20wx $esp 0xbffff5b0: 0x41414141 0x41414141 0x41414141 0x08048310 0xbffff5c0: 0x080484da 0x0804a024 0x08048162 0x08048310 0xbffff5d0: 0x080484da 0x0804a025 0x080480d8 0x08048310 0xbffff5e0: 0x080484da 0x0804a026 0x08048513 0x08048300 0xbffff5f0: 0x00000000 0x6fb0e3f2 0x53b687e2 0x00000000 The word on extreme right hand side at the address 0xbffff5e0 is 0x08048300. It should have been 0x08048320 as per the input given. Why is it not as expected ? One thing that strikes me is that the expected address 0x08048320 ends with a 20 which is a space character. Could it be possible that because it's a space character being passed as input to the program, it is considered as end of input by the program and hence it does not copy anything beyond that at all ?
score: -2
has comment: http://stackoverflow.com/comment/83089412
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/83089427
has comment: http://stackoverflow.com/comment/83114419
has comment: http://stackoverflow.com/comment/83089343
has comment: http://stackoverflow.com/comment/83098693
tagged with: gdb
upvote count: 0
answer count: 1
has title: Does user input get copied on the stack beyond the space or null character if user input taken through strcpy()
favorite count: 0
has answer: http://stackoverflow.com/a/48060628
has comment: http://stackoverflow.com/comment/83089369
has comment: http://stackoverflow.com/comment/83088966
tagged with: assembly
has comment: http://stackoverflow.com/comment/83088866

http://stackoverflow.com/a/48054275
answers question: http://stackoverflow.com/q/48054241
accepted answer of: http://stackoverflow.com/q/48054241
score: 0
type: AcceptedAnswer
type: Answer
has body: A string with a number in it is still a valid string - it's a string representing that number as text. If you want to check that the name is not a string composed just of digits, then the following code will work: while True: try: name = input('Insert name: ') if name.isdigit(): raise ValueError

http://stackoverflow.com/q/48039195
tagged with: kibana
tagged with: flask-login
score: 0
has answer: http://stackoverflow.com/a/48039246
type: Question
tagged with: flask
answer count: 2
has title: Flask url handling for port
type: UnansweredQuestion
tagged with: python
has body: I have Kibana (part of elasticsearch stack) running on xx.xxx.xxx.xxx:5601. Since Kibana does not have authentication of its own, I am trying to wrap it under my flask login setup. In other words, if someone tries to visit xx.xxx.xxx.xxx:5601, I need the page to be redirected to my flask login page. I can use the @login_required decorator on the URL to achieve this...but I don't know how to setup the flask route URL to handle the port 5601 since it needs to begin with a leading slash. @app.route("/") @login_required Any suggestions? EDIT @senaps: App 1 is flask that runs on 0.0.0.0, port 9500, App 2 is node.js based Kibana that I can choose to either run on localhost port 5601 and then expose via nginx, or i can directly make public on IP:5601. Either way, it is running as a "service" on startup and listening on 5601 at all times. Problem statement - App 2 to be wrapped under App 1 login. I do not want to use nginx for authentication of App 2 but rather the App 1 flask login setup. I'm currently using gunicorn to serve flask app and have nginx reverse proxy setup to route to flask app. Guide followed is digitalocean Option 1 - Node.js Kibana application exposed to public on IP:5601. server { listen 80; server_name example.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/myproject/myproject.sock; }} If I visit IP, it goes to my flask app, great. I'm unable to figure out how to handle flask view URL if someone visits IP:5601. Instead of taking them to Kibana, it should redirect to my flask app for authentication. I tried adding another server block to listen at 5601 and proxy_pass to the flask sock file, I get a nginx error that says it cannot bind to 5601 and asks me to kill the listener at 5601. But I need Kibana running at 5601 at all times (unless I can figure out a way to launch this service via python flask). Option 2 - Kibana application runs on localhost port 5601 mounted at "/kibana" in order to not conflict with "/" needed for flas…
has answer: http://stackoverflow.com/a/48040759

http://stackoverflow.com/q/48081320
accepted answer: http://stackoverflow.com/a/48192313
has comment: http://stackoverflow.com/comment/83172366
has answer: http://stackoverflow.com/a/48081602
has comment: http://stackoverflow.com/comment/83140015
tagged with: web-scraping
tagged with: python-requests
tagged with: https
type: Question
possible better answer: http://stackoverflow.com/a/48081602
answer count: 2
downvote count: 0
has body: When I try to follow the guide here: https://automatetheboringstuff.com/chapter11/ my script fails: import requests res = requests.get('https://automatetheboringstuff.com/files/rj.txt') type(res) res.raise_for_status() requests is installed. I am given the following error messages after a very long wait, which only appear when using HTTPS URLs; the same thing occurs on two Windows 10 64bit machines with Python 3.6.3 64bit and Python 3.6.4 64bit: "C:\Program Files\Python36\python.exe" "C:/Users/user.name/Google Drive/Automation/RoHSWebScraper/main.py" Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\urllib3\contrib\pyopenssl.py", line 441, in wrap_socket cnx.do_handshake() File "C:\Program Files\Python36\lib\site-packages\OpenSSL\SSL.py", line 1716, in do_handshake self._raise_ssl_error(self._ssl, result) File "C:\Program Files\Python36\lib\site-packages\OpenSSL\SSL.py", line 1449, in _raise_ssl_error raise SysCallError(-1, "Unexpected EOF") OpenSSL.SSL.SysCallError: (-1, 'Unexpected EOF') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen chunked=chunked) File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 346, in _make_request self._validate_conn(conn) File "C:\Program Files\Python36\lib\site-packages\urllib3\connectionpool.py", line 850, in _validate_conn conn.connect() File "C:\Program Files\Python36\lib\site-packages\urllib3\connection.py", line 326, in connect ssl_context=context) File "C:\Program Files\Python36\lib\site-packages\urllib3\util\ssl_.py", line 329, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "C:\Program Files\Python36\lib\site-packages\urllib3\contrib\pyopenssl.py", line 448, in wrap_socket raise ssl.SSLError('bad handshake: %r' % e) ssl.SSLError: ("bad handshake: SysCallError(-1, 'Unexpe…
has comment: http://stackoverflow.com/comment/83137223
has answer: http://stackoverflow.com/a/48192313
has comment: http://stackoverflow.com/comment/83142680
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83137000
upvote count: 2
has comment: http://stackoverflow.com/comment/83143746
has comment: http://stackoverflow.com/comment/83143301
tagged with: python
linked to: http://stackoverflow.com/q/41597294
type: AnsweredQuestion
score: 2
has title: Unable To Get HTTPS URLs (requests package)

http://stackoverflow.com/q/48022124
tagged with: qtableview
accepted answer: http://stackoverflow.com/a/48022713
type: AnsweredQuestion
has body: I would like to modify any cell (except header) within given QTableView. Here below is my original code that does not allow for any changes: import sys import csv from datetime import datetime, timedelta import calendar from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import sqlite3 from pandas import DataFrame class TBWindow(QMainWindow): def __init__(self, parent=None): super(TBWindow, self).__init__(parent) sql = "select * from stock" args = [] conn = sqlite3.connect('DataBase.db') c = conn.cursor() c.execute(sql,args) data = c.fetchall() names = list(map(lambda x: x[0], c.description)) c.close() conn.close() data = DataFrame(data, columns = names) MenuBar = self.menuBar() saveFile = QAction("&amp;Save File", self) saveFile.setShortcut("Ctrl+S") saveFile.setStatusTip('Save File') saveFile.triggered.connect(self.file_save) MenuBar.addAction(saveFile) self.setWindowTitle('Aplikace Princezna Pampeliska') self.centralwidget = QWidget(self) self.lineEdit = QLineEdit(self.centralwidget) self.view = QTableView(self.centralwidget) self.comboBox = QComboBox(self.centralwidget) self.label = QLabel(self.centralwidget) self.gridLayout = QGridLayout(self.centralwidget) self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1) self.gridLayout.addWidget(self.view, 1, 0, 1, 3) self.gridLayout.addWidget(self.comboBox, 0, 2, 1, 1) self.gridLayout.addWidget(self.label, 0, 0, 1, 1) self.setCentralWidget(self.centralwidget) self.label.setText("Filter") self.model = PandasModel(data) self.proxy = QSortFilterProxyModel(self) self.proxy.setSourceModel(self.model) self.view.setModel(self.proxy) for column in range(self.view.horizontalHeader().count()): self.view.resizeColumnToContents(column) for i in (0,1,3): self.view.horizontalHeader().setSectionResizeMode(i, QHeaderView.Stretch) self.comboBox.addItems(list(data.columns.values)) self.lineEdit.textChanged.connect(self.on_lineEdit_textChanged) self.comboBox.currentIndexChanged.connect(self.on_comboBox_curren…
upvote count: 5
tagged with: pyqt5
type: Question
linked to: http://stackoverflow.com/q/44603119
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48022713
favorite count: 0
tagged with: python-3.x
has title: Modify cells in QTableView PYQT5
score: 5
tagged with: python

http://stackoverflow.com/q/48123440
answer count: 0
has title: "AttributeError: 'psycopg2' has no attribute '__version__'" when switching from sqlite to postgres with Django - Vagrant
upvote count: 3
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/83233127
type: Question
has comment: http://stackoverflow.com/comment/83224875
score: 3
tagged with: vagrant
tagged with: vagrantfile
downvote count: 0
has comment: http://stackoverflow.com/comment/83233535
has comment: http://stackoverflow.com/comment/83225023
favorite count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/83232891
has comment: http://stackoverflow.com/comment/83232572
has body: I'm a newbie in Django/Python. I just setup Django successfully with vagrant on my computer. But I want to change the default database from sqlite to postgresql. To do so, I just changed the database section on the setting.py file to : # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.path.join(BASE_DIR, 'db.postgresql'), } } Now whenever I run the command python manage.py runserver 0.0.0.0:8080 (which used to work well), I get the following error : Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7fb91ed95ea0&gt; Traceback (most recent call last): File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ubuntu/.virtualenvs/meshine_api/local/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(model…
tagged with: python

http://stackoverflow.com/comment/83137915
type: Comment
type: QuestionComment
score: 1
has text: How are you selecting `p`? Is it an integer or a string? It it is a string, does it contain any whitespace?
comment on: http://stackoverflow.com/q/48081801

http://stackoverflow.com/comment/83083226
type: Comment
has text: Thank you for your answer. Yes i have performed on a smaller function but now, I have a symbolic matrix (K_P) and two vectors (X and f) such that K_P*X=f . I would like to find all the variables in matrix K_P so as to minimize the error function (K_P*X-f). Here X and f are completely known vector. I will add these matrix K_P and vector X to the above question shortly. I will also look creating the equality constraint equation using lambdify.
score: 0
comment on: http://stackoverflow.com/q/48054194
type: QuestionComment

http://stackoverflow.com/comment/83164832
has text: What did you actually try after following the docs on [rendering the fields manually](https://docs.djangoproject.com/en/2.0/topics/forms/#rendering-fields-manually)? `{{ form.field }}` isn't going to work because you don't have any fields name `field`. You need `{{ field.cliente }}`, `{{ field.prestazione1 }}` and so on.
comment on: http://stackoverflow.com/q/48094733
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48068643
score: 0
has body: On Mac, you can use a tabbed terminal app like iTerm2 on macOS. You can also use AppleScript to launch terminal windows and run specific scripts. The specific implementation will depend on your operating system. For example, this AppleScript opens a new tab in Terminal: osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' Another option is to use the Node.js package ttab, available on NPM. Example 1: ttab 'npm run script_name' Example 2: ttab 'python -m SimpleHTTPServer 8888'
answers question: http://stackoverflow.com/q/48068563
type: Answer

http://stackoverflow.com/comment/83077091
has text: Wouldn't overfitting result in an almost perfect match on the training data? This is actually going the opposite direction. Also I get this result for all models I tried so far (simple and complex ones)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48050810
type: Comment

http://stackoverflow.com/comment/83017901
type: QuestionComment
has text: You will need to investigate this further on your side. Did you try with `pip3` as I suggested?
comment on: http://stackoverflow.com/q/48023955
score: 0
type: Comment

http://stackoverflow.com/comment/83101843
comment on: http://stackoverflow.com/a/48064085
score: 0
has text: Thanks, really works. My bad, wasn\`t attentive when checked implemetation and I thought `verbose_name` changes callable name of ForeignKey field, but that was `related_name` instead
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83066673
type: QuestionComment
has text: and pyrebase is developed for python3 env
comment on: http://stackoverflow.com/q/48047495
score: 0
type: Comment

http://stackoverflow.com/q/48015450
answer count: 1
tagged with: jupyter
tagged with: python
accepted answer: http://stackoverflow.com/a/48052652
has title: Issue installing Jupyter on Arch
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/43406257
type: Question
has comment: http://stackoverflow.com/comment/83035388
has comment: http://stackoverflow.com/comment/83048248
linked to: http://stackoverflow.com/q/46189532
has answer: http://stackoverflow.com/a/48052652
score: 0
has body: I am trying to get a Jupyter notebook up and running on Arch. I have tried installying the jupyter package. I also tried following the Arch wiki and installed jupyter-notebook and jupyter-nbconvert and python-ipywidgets. Lastly, I tried using the pip instructions. All three of which fail and give: ➜ ~ jupyter notebook Traceback (most recent call last): File "/usr/sbin/jupyter-notebook", line 11, in &lt;module&gt; sys.exit(main()) File "/usr/lib/python3.6/site-packages/jupyter_core/application.py", line 266, in launch_instance return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs) File "/usr/lib/python3.6/site-packages/traitlets/config/application.py", line 657, in launch_instance app.initialize(argv) File "&lt;decorator-gen-7&gt;", line 2, in initialize File "/usr/lib/python3.6/site-packages/traitlets/config/application.py", line 87, in catch_config_error return method(app, *args, **kwargs) File "/usr/lib/python3.6/site-packages/notebook/notebookapp.py", line 1368, in initialize self.init_webapp() File "/usr/lib/python3.6/site-packages/notebook/notebookapp.py", line 1188, in init_webapp self.http_server.listen(port, self.ip) File "/usr/lib/python3.6/site-packages/tornado/tcpserver.py", line 142, in listen sockets = bind_sockets(port, address=address) File "/usr/lib/python3.6/site-packages/tornado/netutil.py", line 197, in bind_sockets sock.bind(sockaddr) OSError: [Errno 22] Invalid argument It seems that the other reports related to this involve a different error with sock.bind. I am not sure if the issue is related or not. Any guidance on the matter would be appreciated.

http://stackoverflow.com/q/48052150
type: Question
tagged with: jwt
upvote count: 5
tagged with: flask-restful
has body: I have a flask app with 2 blueprints. auth blueprint and events blueprint. This is how they are structured `app/ auth_blueprint/ init.py views.py model.py events_blueprint/ init.py model.py views.py ` auth_blueprint handles user events. login,registration etc. My question is, how do I access a token generated from auth_blueprint upon login and use it in the events_blueprint to secure the other endpoints? in views under auth_blueprint the authentication code is @authenticate.verify_password def verify_password(username_or_token, password): # first try to authenticate by token user = models.User.verify_auth_token(username_or_token) if not user: # try to authenticate with username/password user = models.User.query.filter_by(username = username_or_token).first() if not user or not user.verify_password(password): return False g.user = user import pdb; pdb.set_trace() #debugger return True #login user @auth.route('/api/v1/auth/login') @authenticate.login_required def login(): token = g.user.generate_auth_token() return jsonify({ 'token': token.decode('ascii') }) #return jsonify({'Welcome':'Login Okay'}),200 When I try to access g in views under events_blueprint i get an error g has no attribute user @events.route('/api/v1/user') def getloggeduser(): print(g) import pdb; pdb.set_trace() return g PS: that is for testing purpose. I am only interested in getting user object stored in g and later on retrieve a userid from there. I am using jwt for token based authentication. Let me know if anything needs clarification. Thank you
score: 5
has title: How to access flask auth token from a different blueprint
downvote count: 0
favorite count: 0
tagged with: python
tagged with: flask-login
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48101545
has answer: http://stackoverflow.com/a/48104040
type: Question
has body: I am trying to merge two csv's without having to pick the value from _x or _y. MetaData1 Sample_name TITLE Cody Chicken Pox Claudia Chicken Pox Alex Chicken Pox Steven Chicken Pox Mom Chicken Pox Dad MetaData2 Sample_name TITLE Geo_Loc DESCRIPTION Dad Chicken Pox Earth people Me Chicken Pox Earth people Roger Chicken Pox Earth people Ben Chicken Pox Earth people Merge together to look like this: Merged Metadata Sample_name TITLE Geo_Loc DESCRIPTION Cody Chicken Pox Missing:Not Applicable Missing:Not Applicable Claudia Chicken Pox Missing:Not Applicable Missing:Not Applicable Alex Chicken Pox Missing:Not Applicable Missing:Not Applicable Steven Chicken Pox Missing:Not Applicable Missing:Not Applicable Mom Chicken Pox Missing:Not Applicable Missing:Not Applicable Dad Chicken Pox Earth people Me Chicken Pox Earth people Roger Chicken Pox Earth people Ben Chicken Pox Earth people The code I have so far is Below, #Merging two or more csv files using pandas #Duplicate line for more than one csv file File_one = panda.read_csv('/Users/c1carpenter/Desktop/Test.txt', sep='\t', header=0, dtype=str) File_two = panda.read_csv('/Users/c1carpenter/Desktop/Test2.txt', sep='\t', header=0, dtype=str) Merge_File = panda.merge(File_one, File_two, how='outer', on='Sample_name') however if I have a hundred columns, of which 50 end up being duplicates.How do I merge them without losing the data. and having to type out each title individually? Like below. # Cleanup to merge duplicate non-index column mm['TITLE'] = mm'TITLE_x', 'TITLE_y'.fillna('').sum(axis=1) mm.drop(['TITLE_x','TITLE_y'], axis=1, inplace=True)
score: 0
has comment: http://stackoverflow.com/comment/83319784
answer count: 1
tagged with: multiple-columns
has title: How do I merge more than one column for csv's in pandas without picking_x or _y but instead picking the one that has the information
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: merge

http://stackoverflow.com/a/48016724
type: Answer
has comment: http://stackoverflow.com/comment/83002837
upvote count: 1
answers question: http://stackoverflow.com/q/48016665
score: 1
downvote count: 0
has body: The code below accomplishes what you want. You can set class variables in the combined class to represent output_letter and wait_time. Then inside of the combined class you have access to all attributes and functions of the other classes. import time class output_letter(): def output_a(self): print('a') def output_b(self): print('b') def output_c(self): print('c') class wait_time(): def sleep_2(self): time.sleep(2) class combined(): ol = output_letter() wt = wait_time() def output_a(self): self.wt.sleep_2() self.ol.output_a() def main(): c=combined() c.output_a() if __name__ == '__main__': main()

http://stackoverflow.com/comment/83153009
type: Comment
has text: What about `os.chdir`?
comment on: http://stackoverflow.com/a/48089203
score: 0
type: AnswerComment

http://stackoverflow.com/a/72871217
type: Answer
has body: # define hcf # pass two arguments x,y # solving using set comprehensions def hcf(x,y): x1 = {i for i in range(1,x+1) if x % i == 0} x2 = {j for j in range(1,y+1) if y % j == 0} y2 = x1.intersection(x2) print(max(y2)) hcf(54,24) Best answer I came up with to solve HCF
score: 0
answers question: http://stackoverflow.com/q/48031361

http://stackoverflow.com/q/48153891
has title: Running python script from perl, with argument to stdin and saving stdout output
answer count: 4
favorite count: 0
has body: My perl script is at path: a/perl/perlScript.pl my python script is at path: a/python/pythonScript.py pythonScript.py gets an argument from stdin, and returns result to stdout. From perlScript.pl , I want to run pythonScript.py with the argument hi to stdin, and save the results in some variable. That's what I tried: my $ret = `../python/pythonScript.py &lt; hi`; but I got the following error: The system cannot find the path specified. Can you explain the path can't be found?
has answer: http://stackoverflow.com/a/48156086
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/17544307
has answer: http://stackoverflow.com/a/48154208
type: Question
accepted answer: http://stackoverflow.com/a/48156086
tagged with: perl
has answer: http://stackoverflow.com/a/48155847
downvote count: 0
possible better answer: http://stackoverflow.com/a/48155505
has answer: http://stackoverflow.com/a/48155505

http://stackoverflow.com/q/48030280
tagged with: python
score: 1
upvote count: 1
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48030303
has title: python assignment in array vs scalar
tagged with: copy-assignment
tagged with: numpy
answer count: 1
tagged with: arrays
downvote count: 0
has body: I have a 2D array A of shape (4,3), and a 1D array a of shape (4,). I want to swap the first two rows of A, as well as the first two elements in a. I did the following: A[0,:],A[1,:] = A[1,:],A[0,:] a[0],a[1] = a[1],a[0] Apparently, it works for a, but fails for A. Now, the second row becomes the first row, but the first row remains unchanged. If I do the following: first_row_copy = A[0,:].copy() A[0,:] = A[1,:] A[1,:] = first_row_copy Then, it seems to work. Why the first method doesn't work? (but works for a) Also, what's the difference between A_copy = A[0,:].copy() and A_copy = A[0,:]?
favorite count: 0
has answer: http://stackoverflow.com/a/48030303
tagged with: variable-assignment

http://stackoverflow.com/comment/83225203
has text: Hey @zipa, thanks but this does not filter out each driver's own pitlaps. For eg, vettel has pitstops on lap 18 and 36, but because hamilton has a pitlap on lap 20, lap 20 is removed from vettel's data too.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48111335

http://stackoverflow.com/comment/83096512
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48061769
score: 0
has text: I can work with both np and pd.

http://stackoverflow.com/q/48082590
has comment: http://stackoverflow.com/comment/83149343
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/83148988
type: Question
tagged with: numpy
has body: I often come across the situation where I have some 3d numpy array: data = np.random.rand(10, 10, 5), i.e. we have 5 10x10 images stacked in the z direction. Now I would like to use ax.scatter3d() which requires that I have xdata, ydata, zdata and cdata. In this case cdata is the color data corresponding to the values in the data array. What is the pythonic way to go from data to xdata, ydata, zdata and cdata?
has title: How to extract data from 3d numpy array for 3d plot?
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83145360
tagged with: python
has comment: http://stackoverflow.com/comment/83141245

http://stackoverflow.com/comment/83210361
comment on: http://stackoverflow.com/a/48104963
score: 0
type: AnswerComment
type: Comment
has text: @PabloCastaño I updated the answer to reflect your input. The only difference is where you define `x1` and passing it into `update` as an argument.

http://stackoverflow.com/q/48163269
has comment: http://stackoverflow.com/comment/83306261
type: Question
has comment: http://stackoverflow.com/comment/83343341
has comment: http://stackoverflow.com/comment/83316475
linked to: http://stackoverflow.com/q/47472142
score: -1
has answer: http://stackoverflow.com/a/48163334
downvote count: 1
has answer: http://stackoverflow.com/a/48168119
has comment: http://stackoverflow.com/comment/83343354
has comment: http://stackoverflow.com/comment/83307419
favorite count: 0
type: UnansweredQuestion
has title: Python + Selenium -- How to click the search button
tagged with: python
has body: I am trying to click the button using Python + Selenium: Please let me know how can I use it with WebDriver? I tried XPath, by value but none worked.
answer count: 4
has comment: http://stackoverflow.com/comment/83327497
has comment: http://stackoverflow.com/comment/83315352
tagged with: xpath
has answer: http://stackoverflow.com/a/48163921
upvote count: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/48164339

http://stackoverflow.com/q/48095879
has comment: http://stackoverflow.com/comment/83167981
score: 0
has title: Failing to establish connection using requests
has body: I'm trying to use requests to get the text off a website, but it is not working and I'm not sure why. Here is my code: import requests print(requests.get("https://projecteuler.net/project/resources/p079_keylog.txt").text) which gives me the following error: HTTPSConnectionPool(host='projecteuler.net', port=443): Max retries exceeded with url: /project/resources/p079_keylog.txt (Caused by NewConnectionError('&lt;requests.packages.urllib3.connection.VerifiedHTTPSConnectio n object at 0x000002701CC15128&gt;: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)) So it seems a connection cannot be made. The website is valid and works. Is there anything simple I'm doing wrong that may be causing this?
tagged with: python
type: UnansweredQuestion
tagged with: python-requests
has answer: http://stackoverflow.com/a/48096095
type: Question
answer count: 1

http://stackoverflow.com/comment/83322137
type: QuestionComment
comment on: http://stackoverflow.com/q/48171256
has text: @Wen - no problem.
score: 0
type: Comment

http://stackoverflow.com/comment/83170976
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48095388
has text: parse live score webpage to get daily alerts (by email) on the matches i am interested in :), not a big deal.

http://stackoverflow.com/q/48118831
upvote count: 0
has comment: http://stackoverflow.com/comment/83214215
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83214102
tagged with: python
has comment: http://stackoverflow.com/comment/83214136
has comment: http://stackoverflow.com/comment/83214237
has comment: http://stackoverflow.com/comment/83214556
downvote count: 2
has comment: http://stackoverflow.com/comment/83214639
type: Question
has comment: http://stackoverflow.com/comment/83214497
score: -2
has body: My input file looks like this car dog Rock My output file that im trying to edit looks like this. my whole aim here to to remove all of the lines that contain the word car cat car sky rat car cloud Here's my initial code, the problem here is it only removes the line only when it literally only the word which is "car" in this case from __future__ import print_function import linecache import fileinput must_delete = linecache.getline('Test.txt', 1) for line in fileinput.input('output.txt', inplace=True): if line != must_delete: print(line, end='')
tagged with: arrays
has title: Removing lines in a file that contain a certain word in python
has answer: http://stackoverflow.com/a/48119045
tagged with: sorting
has comment: http://stackoverflow.com/comment/83214368
has comment: http://stackoverflow.com/comment/83214076
has comment: http://stackoverflow.com/comment/83214500
tagged with: python-2.7

http://stackoverflow.com/q/48067261
answer count: 0
upvote count: 2
type: UnansweredQuestion
score: 1
has title: Upload tempfile in Django
downvote count: 1
type: Question
tagged with: temporary-files
has comment: http://stackoverflow.com/comment/83108307
has body: I have a form where a user submits a text file ('example.txt'). I want to parse some data from that text file ('example.txt') and convert it into another text file ('modified.txt') and store it elsewhere. I've created a model with a FileField that has a upload_to='converted/ I've created a tempfile and I am trying to save it into that model. Upon saving the instance of that model, I am receiving this error message: AttributeError: '_io.BufferedRandom' object has no attribute '_committed' Here is what my code looks like: my_data = parse_data(example_file) temp_file = tempfile.TemporaryFile() json_text = json.dumps(my_data) json_byte = str.encode(json_text) temp_file.write(json_byte) temp_file.name = example_file.name file_instance = MyFileModel(file=temp_file) file_instance.save() temp_file.close()
tagged with: upload
has comment: http://stackoverflow.com/comment/83108400
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83109322

http://stackoverflow.com/comment/83327035
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48101576
has text: The easiest way might be to create a tfrecords file where each record contains 64 frames and randomly sample records.
score: 0

http://stackoverflow.com/a/48115284
has body: The difference arises because dot computes the dot product whereas * computes the element-wise product. Try using K *= 1.5 - 0.5 * K * K instead. Addition Unfortunately, that does not yet solve the memory problems. I would recommend using cython to compute the desired function without allocating extra memory. # This cython function must be compiled def evaluate_function_inplace(double[:] values): cdef int i for i in range(values.shape[0]): values[i] *= 1.5 - 0.5 * values[i] * values[i] Subsequently, you can use the function like so. K = ... evaluate_function_inplace(K.ravel()) The K.ravel() call will flatten the array but will not allocate new memory. Of course, you can also use the above approach without resorting to cython but the performance overhead of iterating over the elements of such a large array in python are very large.
has comment: http://stackoverflow.com/comment/83207599
has comment: http://stackoverflow.com/comment/83210182
has comment: http://stackoverflow.com/comment/83207145
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48115074
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48115074

http://stackoverflow.com/a/53954750
answers question: http://stackoverflow.com/q/48124257
has body: In Python, due to the Global Interpreter Lock (GIL), a process can only execute one python bytecode at a time, regardless of how many threads it has. This means inserting/updating/reading a key to a dictionary is thread-safe, which is what people usually mean by saying a dictionary's get/put are "atomic".&dagger; But this means that, exactly as you suspected, multiple threads trying to update different keys to the same dictionary will not be concurrent. Java, of course, doesn't have the GIL issue so multiple threads can update different keys in the ConcurrentHashMap at the same time. This doesn't always happen; it's just possible. The ConcurrentHashMap implementation shards the set of keys and locks each shard. Each shard can be read concurrently but only one thread can write at a time. &dagger;: Sometimes it's pointed out objects with a __hash__ method written in Python will require multiple Python bytecodes, so then puts and gets are not atomic per se; however simple puts and gets will still be thread-safe in the sense that they will not cause crashes or garbage values, although you can still have race-conditions.
downvote count: 0
type: Answer
score: 14
upvote count: 14

http://stackoverflow.com/comment/84955731
comment on: http://stackoverflow.com/a/48080592
type: Comment
has text: On step 2, I get this message: `fatal: Remote branch p4a_numpy_fix not found in upstream origin`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83122051
comment on: http://stackoverflow.com/a/48074242
type: Comment
has text: It won't list the version number for packages installed directly from github, as the OP has done.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/83175126
score: 1
has text: Yes. It evaluates the truthiness, and checks if the expression after the `if` is `True`. Note that `or` also evaluates truthiness.
comment on: http://stackoverflow.com/q/48100058
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48105741
has comment: http://stackoverflow.com/comment/83217537
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83188869
answers question: http://stackoverflow.com/q/48104401
has comment: http://stackoverflow.com/comment/83224417
score: 1
has comment: http://stackoverflow.com/comment/83223368
has comment: http://stackoverflow.com/comment/83218051
has comment: http://stackoverflow.com/comment/83212707
downvote count: 0
has comment: http://stackoverflow.com/comment/83224959
has body: You can accomplish this with numpy, using np.roll(), np.where(), and np.unique(). The idea is to append to each entry its four neighbors, and then to pull out the unique members of those lists of five (the entry and its four neighbors). Here is an implementation that should clarify: # make a 3d array with the matrix entry and its four neighbors neighbor_array = np.array([regions, np.roll(regions,+1,axis=0), np.roll(regions,-1,axis=0), np.roll(regions,+1,axis=1), np.roll(regions,-1,axis=1), ]) # if you want neighbors to include wraparounds, use above; if not, prune neighbor_array_pruned = neighbor_array[:,1:-1,1:-1] # reshape to a 2d array entries x neighbors neighbor_list = np.reshape(neighbor_array_pruned,[5,-1]).T # get uniques into a dictionary neighbor_dict = {} for num in np.unique(regions): neighbor_dict[num] = np.unique(neighbor_list[np.where(neighbor_list[:,0]==num)]) This produces neighbor_dict: {1: array([1, 2, 7]), 2: array([1, 2, 5, 6, 7, 8]), 3: array([3, 6, 8]), 4: array([4, 7, 8]), 5: array([2, 5, 6]), 6: array([2, 3, 5, 6, 8]), 7: array([1, 2, 4, 7, 8]), 8: array([2, 3, 4, 6, 7, 8])} Note I pruned the edges; if you want to include wraparound neighbors or do something more nuanced, you can elaborate that pruning line.
has comment: http://stackoverflow.com/comment/83188295

http://stackoverflow.com/a/48139178
downvote count: 0
has comment: http://stackoverflow.com/comment/83256678
upvote count: 2
has body: Use grid() instead of pack() to create columns and rows. If you use pack() then create Frame using pack() and then inside Frame you can use grid(). import tkinter as tk root = tk.Tk() frame = tk.Frame(root) frame.pack() labels = {} for row_number in range(5): for col_number in range(2): value = 1 + row_number*2 + col_number labels[value] = tk.Label(frame, text='Label ' + str(value)) labels[value].grid(row=row_number, column=col_number) root.mainloop()
type: Answer
has comment: http://stackoverflow.com/comment/83257005
score: 2
answers question: http://stackoverflow.com/q/48138390
accepted answer of: http://stackoverflow.com/q/48138390
type: AcceptedAnswer

http://stackoverflow.com/q/48166922
has title: Seaborn: add counts to countplot?
duplicate of: http://stackoverflow.com/q/33179122
upvote count: 1
type: Question
downvote count: 0
favorite count: 0
tagged with: seaborn
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/33179122
has body: Is there a way to add the actual count number to the Seaborn's countplot? Something similar to annot=True in its heatmap? I've been looking for it in the documentation, but it seems as it doesn't support it..
answer count: 0
score: 1

http://stackoverflow.com/a/53746966
accepted answer of: http://stackoverflow.com/q/48086812
score: 5
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48086812
type: Answer
has body: I have modified your code to get the top voted answer like this. for quest in questions['items']: if 'title' not in quest or quest['is_answered'] == False: continue title = quest['title'] print('Question :- {0}'.format(title)) question_id = quest['question_id'] print('Question ID :- {0}'.format(question_id)) top_answer = SITE.fetch('questions/' + str(question_id) + '/answers', order = 'desc', sort='votes') print(top_answer) If you want to get the accepted answer for the question you can get it this way:- accepted_answer_id = quest['accepted_answer_id'] print('Accepted Answer ID :- {0}'.format(accepted_answer_id)) Stackoverflow uses this id as example below to genarate the url to that answer like this:- answer = "https://stackoverflow.com/a/" + str(accepted_answer_id) print(answer) Hope this helps you !
upvote count: 5

http://stackoverflow.com/comment/83065726
score: 0
comment on: http://stackoverflow.com/q/48047079
type: Comment
has text: So why can't you just apply `str()` to whatever you want to return?
type: QuestionComment

http://stackoverflow.com/a/48057951
type: Answer
has body: Few words about current solution. for x in coro(*args, **kwargs): try: yield from pause() yield x except ... You won't be able to catch exceptions this way: exception raises outside of for-loop generator is exhausted (not usable) after first exception anyway . @asyncio.coroutine def test(): yield from asyncio.sleep(1) raise RuntimeError() yield from asyncio.sleep(1) print('ok') @asyncio.coroutine def main(): coro = test() try: for x in coro: try: yield x except Exception: print('Exception is NOT here.') except Exception: print('Exception is here.') try: next(coro) except StopIteration: print('And after first exception generator is exhausted.') if __name__ == '__main__': loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) finally: loop.close() Output: Exception is here. And after first exception generator is exhausted. Even if it was possible to resume, consider what will happen if coroutine already did some cleanup operations due to exception. Given all above, if some coroutine raised exception only option you have is to suppress this exception (if you want) and re-run this coroutine. You can rerun it after some event if you want. Something like this: def restart(ready_to_restart): def wrapper(func): @asyncio.coroutine def wrapped(*args, **kwargs): while True: try: return (yield from func(*args, **kwargs)) except (ConnectionClosed, aiohttp.ClientError, websockets.WebSocketProtocolError, ConnectionClosed, # bunch of other network errors ) as ex: yield from ready_to_restart.wait() ready_to_restart = asyncio.Event() # set it when you sure network is fine # and you're ready to restart Upd However, how would I make the coroutine continue where it was interrupted now? Just to make things clear: @asyncio.coroutine def test(): with aiohttp.ClientSession() as client: yield from client.request_1() # STEP 1: # Let's say line above raises error # STEP 2: # Imagine you you somehow maged to return to this place # after exception above to resume execution. # But w…
answers question: http://stackoverflow.com/q/48055157
accepted answer of: http://stackoverflow.com/q/48055157
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83101051

http://stackoverflow.com/a/64758011
has comment: http://stackoverflow.com/comment/114499158
has body: Pycairo now has Wheels. So simple pip install pycairo will work for Windows.
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/48131876
upvote count: 2
has comment: http://stackoverflow.com/comment/114508885
type: Answer

http://stackoverflow.com/comment/83122206
score: 0
type: AnswerComment
has text: These methods only give serial version number, but do not give information about flags used during the build. Is there maybe a way to see what binary file does python link to?
comment on: http://stackoverflow.com/a/48074269
type: Comment

http://stackoverflow.com/q/48020593
linked to: http://stackoverflow.com/q/27435284
has comment: http://stackoverflow.com/comment/83012217
upvote count: 64
type: UnansweredQuestion
tagged with: multithreading
has body: I've had a hard time trying to understand how and why async functionality works in python and I am still not sure I understand everything correctly (especially the 'why' part). Please correct me if I am wrong. The purpose of both async methods and threads is to make it possible to process several tasks concurrently. Threads approach looks simple and intuitive. If python program processes several tasks concurrently we have a thread (may be with sub-threads) for each task, the stack of each thread reflects the current stage of processing of corresponding task. Everything is straightforward, there are easy-to-use mechanisms to start a new thread and wait for results from it. As I understand the only problem with this approach is that threads are expensive. Another approach is using async coroutines. I can see several inconveniences with this approach. I'll name couple of them only. We have now two types of methods: usual methods and async methods. 90% of the time the only difference is that you need to remember that this method is async and do not forget to use await keyword when calling this method. And yes, you can't call async method from normal ones. And all this async - await syntactic garbage all around the program is only to indicate that this method is able to yield control to message loop. Threads approach is free of all these inconveniences. But async - await approach allows to process much more concurrent tasks than threads approach does. How is that possible? For each concurrent task we still have a call stack, only now it is a coroutine call stack. I am not quite sure, but looks like this is the key difference: usual stacks are operating-system stacks, they are expensive, coroutine stacks are just a python structures, they are much cheaper. Is this my understanding correct? If this is correct, wouldn't it be better to decouple python threads/call stacks from OS threads/call stacks to make python threads cheaper? Sorry if this question is stupid. I am sure …
tagged with: python
has comment: http://stackoverflow.com/comment/83012883
tagged with: async-await
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48021834
answer count: 2
score: 61
has comment: http://stackoverflow.com/comment/137181657
has comment: http://stackoverflow.com/comment/137178392
has title: Python: what are the advantages of async over threads?
has comment: http://stackoverflow.com/comment/137180081
has answer: http://stackoverflow.com/a/48022433
has comment: http://stackoverflow.com/comment/103660540
tagged with: python-asyncio
tagged with: asynchronous
favorite count: 0

http://stackoverflow.com/comment/83029094
comment on: http://stackoverflow.com/q/48025540
has text: Can you reproduce the fault by unplugging the Ethernet wire from your computer for 30 seconds, and then plugging it back in? (my suspicion is that you may be seeing TCP respond to a temporary network outage by dialing back the resend-rate and the window size to extremely small values)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48078267
upvote count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1
has body: i'm trying to define a callable sum-of-exponentials function with a variable number of terms, in a condensed code. the concept i'm looking for should be applicable to any sort mathematical function with repetitive terms. the individual functions should look like this: from numpy import exp, zeros def ExpDec1(x,y0,t0,A,a1,tau): y = zeros(len(x)) for k,l in enumerate(x): if l &gt;= t0: y[k] = (A/a1)*(a1*exp(-l/tau) return y def ExpDec2(x,y0,t0,A,a1,a2,tau1,tau2): y = zeros(len(x)) for k,l in enumerate(x): if l &gt;= t0: y[k] = (A/(a1+a2))*(a1*exp(-l/tau1) + a2*exp(-l/tau2)) return y ... some searching directed me to use classes, but i'm not very familiar with classes. my class attempt looks like this: class ExpDec(object): from numpy import exp, zeros def __init__(self,n,x,y0,t0,A,a,tau): self.n = n self.x = x self.y0 = y0 self.t0 = t0 self.A = A self.a = [a1,a2,a3,a4,a5] self.tau = [tau1,tau2,tau3,tau4,tau5] def ExpDec(self):#n,x,y0,t0,A,a,tau): y = zeros(len(x)) norm_fac = a[0] exponant = exp(-l/tau[0]) for i in range(n-1): norm_fac += a[i+1] exponant += exp(-l/tau[i+1]) for k,l in enumerate(x): if l &gt;= t0: y[k] = y0 + ((A/norm_fact)*exponant) return y and i was calling it with: x = np.linspace(-10,100,1101) y = ExpDec.ExpDec(n=1,x=x,y0=0,t0=0,A=1,a=1,tau=15) print(y) with an error: TypeError Traceback (most recent call last) &lt;ipython-input-20-5f7bab6f83a6&gt; in &lt;module&gt;() 1 x = np.linspace(-10,100,1101) 2 #y = ExpDec.ExpDec() ----&gt; 2 y = ExpDec.ExpDec(n=1,x=x,y0=0,t0=0,A=1,a=1,tau=15) 3 4 print(y) TypeError: ExpDec() got an unexpected keyword argument 'n' any help would be appreciated! thank you.
type: Question
tagged with: numpy
has title: concise definition of variable Multi-exponential function(s) within a loop (or in a class)
tagged with: class

http://stackoverflow.com/comment/83134718
type: Comment
type: QuestionComment
has text: Have you tried `df['target_name'] = list(map(mapTarget,df['target']))`
comment on: http://stackoverflow.com/q/48080304
score: 0

http://stackoverflow.com/q/48061672
has comment: http://stackoverflow.com/comment/83096620
has comment: http://stackoverflow.com/comment/83095847
has body: I have a REST url like: url='http://xx.xx.xx.xx/server/rest/line/125' I can get correct return json by command curl, like this: curl -i http://xx.xx.xx.xx/server/rest/line/125 But when i use Python3 requests, it allways return 404, Python code: import requests resp = requests.get(r'http://xx.xx.xx.xx/server/rest/line/125') print(resp.status_code) Anyone can tell me the problem? Is the server block the request?
score: 0
tagged with: rest
has comment: http://stackoverflow.com/comment/83096421
has comment: http://stackoverflow.com/comment/83097766
has comment: http://stackoverflow.com/comment/83096812
has comment: http://stackoverflow.com/comment/83098340
tagged with: curl
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83095784
tagged with: python
tagged with: python-requests
has title: python request get a REST and return 404
type: Question
has comment: http://stackoverflow.com/comment/83096992
linked to: http://stackoverflow.com/q/866946
has answer: http://stackoverflow.com/a/54599596
answer count: 1
linked to: http://stackoverflow.com/q/10588644

http://stackoverflow.com/comment/83364734
type: AnswerComment
score: 0
type: Comment
has text: Yes, I have also used that but it doesn't strikes me ':) thatnks for reminding
comment on: http://stackoverflow.com/a/48129700

http://stackoverflow.com/comment/83195583
comment on: http://stackoverflow.com/a/48108895
score: 0
type: AnswerComment
has text: What did you mean by 'one by one' in your title?
type: Comment

http://stackoverflow.com/comment/83270614
has text: Aside, `if ctx.channel.is_nsfw() = True:` will not work, you need `==` to test for equality.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48146233
score: 1

http://stackoverflow.com/q/48029300
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48029449
type: Question
tagged with: indexing
tagged with: dataframe
score: 0
answer count: 2
has body: I have a time-sorted dataset indexed by dates looking like: result 2009-09-08 Positive 2009-08-24 Negative 2009-06-01 Positive 2009-04-23 Positive 2008-12-06 Positive ... ... I would like to find a date, for example, 2009-08-24 plus the two rows below the date, i.e. 2009-08-24 Negative 2009-06-01 Positive 2009-04-23 Positive My problem is that finding a specific date requires loc (df.loc['2009-08-24']), but finding that date and two rows below requires numerical position (iloc). In matlab, I would first find the numerical row number 'n' of '2009-08-24' (the second row in this case) and then select rows 'n' to 'n + 2'. But I am not sure if there is an easier way in python. Thansk!
has answer: http://stackoverflow.com/a/48029449
has answer: http://stackoverflow.com/a/48029397
accepted answer: http://stackoverflow.com/a/48029397
tagged with: pandas
has title: How to select indices using a combination of loc and iloc

http://stackoverflow.com/comment/89209284
type: QuestionComment
has text: Thank you, felixblade! I'm glad to hear it was reproducible for someone else.
score: 0
comment on: http://stackoverflow.com/q/48085420
type: Comment

http://stackoverflow.com/comment/83058529
score: 0
type: Comment
has text: Now when I run the executable, a cmd console opens and asks my dumb raw_input question. When I type something, the characters are printed by my print statement and the cmd console instantly disappears. Is there a way to cause the cmd screen to persists? I tried an infinite loop but that didn't help. I was kind of thinking the .exe would open in a window and not the cmd console? here's my code: import time x = str(raw_input('input something: ')) print x while True: time.sleep(5)
type: QuestionComment
comment on: http://stackoverflow.com/q/48041557

http://stackoverflow.com/comment/83166764
type: Comment
comment on: http://stackoverflow.com/a/48093402
type: AnswerComment
has text: And another improvement, `x,y,z` are columns in one DataFrame? And need loop each row in this df, generate `x,y,z` and compare?
score: 0

http://stackoverflow.com/comment/83283582
type: Comment
comment on: http://stackoverflow.com/a/48117713
type: AnswerComment
has text: Thanks a lot ! what about writing the results in Pandas ? do you think this is feasable ? or I need to save the JSON format then Elasticsearch and finally Hive ? Thanks
score: 0

http://stackoverflow.com/q/48134780
downvote count: 0
has comment: http://stackoverflow.com/comment/83266328
favorite count: 0
has comment: http://stackoverflow.com/comment/83247197
has comment: http://stackoverflow.com/comment/83302891
tagged with: python
has body: I am newbie in case of python, i am using python 3.6 and mysql connecter from mysql website pip install --allow-external mysql-connector-python mysql-connector-python Everything was going good. I tried 3 examples from mysql website Create DB and table , insert, select. But after 2nd example it stops working and giving a error Traceback (most recent call last): File "select.py", line 3, in &lt;module&gt; import mysql.connector File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\ mysql\connector\__init__.py", line 37, in &lt;module&gt; from .connection import MySQLConnection File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\ mysql\connector\connection.py", line 45, in &lt;module&gt; from .network import MySQLUnixSocket, MySQLTCPSocket File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\site-packages\ mysql\connector\network.py", line 28, in &lt;module&gt; import socket File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\socket.py", li ne 52, in &lt;module&gt; import os, sys, io, selectors File "C:\Users\preet\AppData\Local\Programs\Python\Python36\lib\selectors.py", line 11, in &lt;module&gt; import select File "C:\Users\preet\Desktop\ptyhon-newspaper\select.py", line 7, in &lt;module&gt; cnx = mysql.connector.connect(user='root', password='Jinqm21k', AttributeError: module 'mysql' has no attribute 'connector' Example code from __future__ import print_function from datetime import date, datetime, timedelta import mysql.connector cnx = mysql.connector.connect(user='root', password='****', host='localhost', database='worpress') cursor = cnx.cursor() query = ("SELECT first_name, last_name, hire_date FROM employees " "WHERE hire_date BETWEEN %s AND %s") hire_start = datetime.date(1999, 1, 1) hire_end = datetime.date(1999, 12, 31) cursor.execute(query, (hire_start, hire_end)) for (first_name, last_name, hire_date) in cursor: print("{}, {} was hired on {:%d %b %Y}".format( last_name, first_name, h…
has answer: http://stackoverflow.com/a/48135619
has title: Python - AttributeError: module 'mysql' has no attribute 'connector'
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: mysql
tagged with: mysql-connector
type: Question
has comment: http://stackoverflow.com/comment/83246993
tagged with: database
tagged with: python-3.6
answer count: 1

http://stackoverflow.com/comment/83325122
has text: Thanks, that was helpful. I've added that to my answer if you want it.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48172529

http://stackoverflow.com/q/48120611
has title: Python Pandas filtering; TypeError: cannot convert the series to <class 'int'>
tagged with: pandas
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48120817
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/19798153
type: Question
has comment: http://stackoverflow.com/comment/83218265
accepted answer: http://stackoverflow.com/a/48120817
tagged with: dataframe
has body: I have a DataFrame looking like this: ID Instrument Units Price Status 165 WTICO_USD -1 60.264 OPEN 169 WTICO_USD -1 60.274 OPEN 173 WTICO_USD 1 54.284 OPEN 185 BCO_USD 1 60.124 OPEN If I write the following, I get what I expect: DF[(DF.Instrument=='WTICO_USD')] And same with this: DF[(DF.Instrument=='WTICO_USD')&amp;(DF.ID==165)] However, if I try to filter further, as in this, I get no rows: DF[(DF.Instrument=='WTICO_USD')&amp;(DF['Units']==-1)] Same with DF[(DF.Instrument=='WTICO_USD')&amp;(DF.Units=='-1')] However, this gives an error: DF[(DF.Instrument=='WTICO_USD')&amp;(DF['Units']&gt;-1)] TypeError: cannot convert the series to class 'int' So, I try this and get another error: DF.Units.applymap(int) 'Series' object has no attribute 'applymap' So, since I select all values in the unit column, I get a series that I cannot convert. But why do I also get so when I try this? DF[(DF.Instrument=='WTICO_USD')&amp;(int(DF['Units'])&gt;-1)] cannot convert the series to class 'int' How can I filter on all rows that are Instrument == WTICO_USD and have a Units &lt; 0 ?

http://stackoverflow.com/q/48065982
type: UnansweredQuestion
has body: Let us supposed the there are the modules A, B, C: A.py import C # do stuff B.py import C # do stuff C.py print( "I am the C module and I am being imported by " + get_importer_name() ) Then when running A.py or B.py the output would be: I am the C module and I am being imported by A I am the C module and I am being imported by B Does exists something like the get_importer_name() function, which gets the name of the module which imported me (supposing I am a module)?
type: Question
has title: How to get the name of the file which imported me?
tagged with: import
upvote count: 2
tagged with: python-import
duplicate of: http://stackoverflow.com/q/7150998
favorite count: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/7871319
score: 2
downvote count: 0
linked to: http://stackoverflow.com/q/7871319
answer count: 0

pyspark
tags question: http://stackoverflow.com/q/48065453
tags question: http://stackoverflow.com/q/48148256
tags question: http://stackoverflow.com/q/48165947
tags question: http://stackoverflow.com/q/48165234
tags question: http://stackoverflow.com/q/48106284
tags question: http://stackoverflow.com/q/48083401
tags question: http://stackoverflow.com/q/48075002
tags question: http://stackoverflow.com/q/48156939
tags question: http://stackoverflow.com/q/48024983
tags question: http://stackoverflow.com/q/48148881
tags question: http://stackoverflow.com/q/48145215
tags question: http://stackoverflow.com/q/48019524
type: Tag
tags question: http://stackoverflow.com/q/48147185
tags question: http://stackoverflow.com/q/48140510
tags question: http://stackoverflow.com/q/48150911
tags question: http://stackoverflow.com/q/48094534
tags question: http://stackoverflow.com/q/48102234
tags question: http://stackoverflow.com/q/48172675
tags question: http://stackoverflow.com/q/48058008
tags question: http://stackoverflow.com/q/48131816
tags question: http://stackoverflow.com/q/48121354
tags question: http://stackoverflow.com/q/48167290
tags question: http://stackoverflow.com/q/48164206
tags question: http://stackoverflow.com/q/48061384
tags question: http://stackoverflow.com/q/48026111
tags question: http://stackoverflow.com/q/48161253
tags question: http://stackoverflow.com/q/48131718
tags question: http://stackoverflow.com/q/48169520
tags question: http://stackoverflow.com/q/48148840
tags question: http://stackoverflow.com/q/48093364
tags question: http://stackoverflow.com/q/48104138
tags question: http://stackoverflow.com/q/48074642
tags question: http://stackoverflow.com/q/48158760
tags question: http://stackoverflow.com/q/48062671
tags question: http://stackoverflow.com/q/48124389
tags question: http://stackoverflow.com/q/48162739
tags question: http://stackoverflow.com/q/48139940
tags question: http://stackoverflow.com/q/48059406
tag name: pyspark
tags question: http://stackoverflow.com/q/48112315
tags question: http://stackoverflow.com/q/48145877
tags question: http://stackoverflow.com/q/48142859

file
tags question: http://stackoverflow.com/q/48172139
type: Tag
tags question: http://stackoverflow.com/q/48057299
tags question: http://stackoverflow.com/q/48072137
tags question: http://stackoverflow.com/q/48064607
tags question: http://stackoverflow.com/q/48116820
tags question: http://stackoverflow.com/q/48122080
tags question: http://stackoverflow.com/q/48123819
tag name: file
tags question: http://stackoverflow.com/q/48120682
tags question: http://stackoverflow.com/q/48119882
tags question: http://stackoverflow.com/q/48085211
tags question: http://stackoverflow.com/q/48138966
tags question: http://stackoverflow.com/q/48030583
tags question: http://stackoverflow.com/q/48025105
tags question: http://stackoverflow.com/q/48076745
tags question: http://stackoverflow.com/q/48080899
tags question: http://stackoverflow.com/q/48161562
tags question: http://stackoverflow.com/q/48057691
tags question: http://stackoverflow.com/q/48085752
tags question: http://stackoverflow.com/q/48045316
tags question: http://stackoverflow.com/q/48144487
tags question: http://stackoverflow.com/q/48165302
tags question: http://stackoverflow.com/q/48172808
tags question: http://stackoverflow.com/q/48055409
tags question: http://stackoverflow.com/q/48085644
tags question: http://stackoverflow.com/q/48047055
tags question: http://stackoverflow.com/q/48140781
tags question: http://stackoverflow.com/q/48159149
tags question: http://stackoverflow.com/q/48079374

http://stackoverflow.com/q/48116406
has comment: http://stackoverflow.com/comment/83214426
tagged with: python
has comment: http://stackoverflow.com/comment/83243611
answer count: 0
tagged with: ffmpeg
type: UnansweredQuestion
has body: Of late I have been trying different ways of telling my Raspberry Pi to send video to YouTube live stream. One of the things I wanted to be able to do is boot the Pi up, and it automatically starts the live stream on its own. The advantages to this are huge (won't have to tote around keyboard/mouse to start the stream, or have to ssh into the Pi to start the stream). Now what I did to accomplish this was to make a Python program that pipes the stream from my encoder(FFmpeg) directly to the stream. My goal was to make the program work, and then, set it to run automatically. But every time I run the file in my terminal this is my result: Traceback (most recent call last): File "stream.py", line 22, in &lt;module&gt; stream.stdin.close() NameError: name 'stream' is not defined [h264 @ 0x19ed450] Could not find codec parameters for stream 0 (Video: h264, none): unspecified size Consider increasing the value for the 'analyzeduration' and 'probesize' options pi@raspberrypi:~ $ Input #0, h264, from 'pipe:': Duration: N/A, bitrate: N/A Stream #0:0: Video: h264, none, 25 tbr, 1200k tbn, 50 tbc Unknown input format: 'alsa' Now I think I can fix I can fix some of those errors, but the biggest thing that worries me there is: the fact that "alsa" is unknown. I installed "libsasound" which is supposed to make Alsa usable, but that clearly did not help. I am using Python 3. This is my syntax for this program: import subprocess import picamera import time YOUTUBE="rtmp://a.rtmp.youtube.com/live2/" KEY = ("MY PERSONAL ENCODER KEY") stream_cmd = 'ffmpeg -f h264 -r 25 -i - -itsoffset 5.5 -fflags nobuffer -f alsa -ac 1 -i hw:1,0 -vcodec copy -acodec aac -ac 1 -ar 8000 -ab 32k -map 0:0 -map 1:0 -strict experimental -f flv ' + YOUTUBE + KEY stream_pipe = subprocess.Popen(stream_cmd, shell=True, stdin=subprocess.PIPE) camera = picamera.PiCamera(resolution=(640, 480), framerate=25) try: now = time.strftime("%Y-%m-%d-%H:%M:%S") camera.framerate = 25 camera.vflip = True camera.hflip = True c…
tagged with: live-streaming
tagged with: youtube
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83370421
has title: FFmpeg stream giving me "Alsa" errors

http://stackoverflow.com/comment/83108742
type: Comment
comment on: http://stackoverflow.com/a/48067035
type: AnswerComment
score: 0
has text: We dont really need to iterate line-by-line, since we looking for target keywords and not sentences. Yes we do iterate line-by-line and look for keywords but that add up few more lines in above code but i would like to keep the code intact. Yes, we don't need the optional parameter `access =mmap.ACCESS_READ` but wouldn't that be better than the default value for `access` `mmap.ACCESS_WRITE` which is not relevant to the problem we have here?

http://stackoverflow.com/q/48045978
possible better answer: http://stackoverflow.com/a/48047456
favorite count: 0
has title: How to log to single file with multiprocessing.Pool.apply_async
tagged with: python
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/69589205
has answer: http://stackoverflow.com/a/48047674
tagged with: logging
accepted answer: http://stackoverflow.com/a/48047674
tagged with: multiprocessing
type: AnsweredQuestion
has body: I can't get logging to a single file working with multprocess.Pool.apply_async. I'm trying to adapt this example from the Logging Cookbook, but it only works for multiprocessing.Process. Passing the logging queue into apply_async doesn't seem to have effect. I would like to use a Pool so that I can easily manage the number of simultaneous threads. The following adapted example with multiprocessing.Process works ok for me, except I am not getting log messages from the main process, and I don't think it will work well when I have 100 large jobs. import logging import logging.handlers import numpy as np import time import multiprocessing import pandas as pd log_file = 'PATH_TO_FILE/log_file.log' def listener_configurer(): root = logging.getLogger() h = logging.FileHandler(log_file) f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s') h.setFormatter(f) root.addHandler(h) # This is the listener process top-level loop: wait for logging events # (LogRecords)on the queue and handle them, quit when you get a None for a # LogRecord. def listener_process(queue, configurer): configurer() while True: try: record = queue.get() if record is None: # We send this as a sentinel to tell the listener to quit. break logger = logging.getLogger(record.name) logger.handle(record) # No level or filter logic applied - just do it! except Exception: import sys, traceback print('Whoops! Problem:', file=sys.stderr) traceback.print_exc(file=sys.stderr) def worker_configurer(queue): h = logging.handlers.QueueHandler(queue) # Just the one handler needed root = logging.getLogger() root.addHandler(h) # send all messages, for demo; no other level or filter logic applied. root.setLevel(logging.DEBUG) # This is the worker process top-level loop, which just logs ten events with # random intervening delays before terminating. # The print messages are just so you know it's doing something! def worker_function(sleep_time, name, queue, configurer): configurer(queue) st…
linked to: http://stackoverflow.com/q/20332359
has comment: http://stackoverflow.com/comment/83079714
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48047456
answer count: 3

http://stackoverflow.com/q/48078567
tagged with: bz2
answer count: 3
tagged with: wikidata
tagged with: python
possible better answer: http://stackoverflow.com/a/54796673
has answer: http://stackoverflow.com/a/69618053
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54796673
score: 6
has body: I want to look at entities and relationships using Wikidata. I downloaded the Wikidata JSON dump (from here .bz2 file, size ~ 18 GB). However, I cannot open the file, it's just too big for my computer. Is there a way to look into the file without extracting the full .bz2 file. Especially using Python, I know that there is a PHP dump reader (here), but I can't use it.
has title: How to parse Wikidata JSON (.bz2) file using Python?
type: Question
accepted answer: http://stackoverflow.com/a/48078800
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/48078800
upvote count: 7
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/51952657
upvote count: 1
has body: With wkhtmltopdf, you can do something like this from command line: wkhtmltopdf --cookie-jar cookies.txt https://example.com/loginform.html --post 'user_id' 'my_id' --post 'user_pass' 'my_pass --post 'submit_btn' 'submit' throw_away.pdf wkhtmltopdf --cookie-jar cookies.txt https://example.com/securepage.html keep_this_one.pdf
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48135938

http://stackoverflow.com/comment/82999520
has text: so essentially no way to make this happen?
comment on: http://stackoverflow.com/a/48015166
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/a/48068944
answers question: http://stackoverflow.com/q/48068694
type: Answer
has body: Instances are not passed between processes, because instances are per Python VM process. Values passed between processes are pickled. Unpickling normally restores instances by measures other than calling __init__; As far as I can tell it directly sets attribute values to resurrect an instance, and resolves references to/from other instances. Provided that you run identical code in either process (and with multiprocessing, you do), it restores a reference to a correct instance method inside a restored chain of instances. This means that if an __init__ in the chain of objects does something side-effectful, it will not have been done on the receiving side, that is, in a subprocess. Do such initialization explicitly. All in all, it's easiest to share (effectively) immutable objects between parallel processes, and reconcile results after join()ing all of them.
has comment: http://stackoverflow.com/comment/83119925
upvote count: 3
has comment: http://stackoverflow.com/comment/83150768
score: 3
downvote count: 0

http://stackoverflow.com/q/48169391
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83319109
answer count: 0
has comment: http://stackoverflow.com/comment/83319066
type: UnansweredQuestion
score: 0
linked to: http://stackoverflow.com/q/42766654
upvote count: 1
downvote count: 1
duplicate of: http://stackoverflow.com/q/42766654
type: Question
has comment: http://stackoverflow.com/comment/83318099
has title: Create Field with the result of aggregated value
has body: I have this df dataframe : df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'three','two', 'two', 'one', 'three'], 'C' : [1,2,8,2,3,4,8,7], 'D' : np.random.randn(8)}) A B C D 0 foo one 1 1.701138 1 bar one 2 0.771723 2 foo two 8 0.624447 3 bar three 2 1.725457 4 foo two 3 0.742048 5 bar two 4 0.166653 6 foo one 8 -0.605956 7 foo three 7 0.160273 And would like to had the result of this statement : df.groupby('A')['C'].sum() : A bar 8 foo 27 Name: C, dtype: int64 This statement : df['Sum'] = df.groupby('A')['C'].sum() generates NaN A B C D Sum 0 foo one 1 1.701138 NaN 1 bar one 2 0.771723 NaN 2 foo two 8 0.624447 NaN 3 bar three 2 1.725457 NaN 4 foo two 3 0.742048 NaN 5 bar two 4 0.166653 NaN 6 foo one 8 -0.605956 NaN 7 foo three 7 0.160273 NaN How can I get this A B C D Sum 0 foo one 1 1.701138 27 1 bar one 2 0.771723 8 2 foo two 8 0.624447 27 3 bar three 2 1.725457 8 4 foo two 3 0.742048 27 5 bar two 4 0.166653 8 6 foo one 8 -0.605956 27 7 foo three 7 0.160273 27
tagged with: pandas

http://stackoverflow.com/comment/83296016
type: QuestionComment
has text: `HKEY_CLASSES_ROOT\Excel.Application.11` Each excel has it's own app object. `HKEY_CLASSES_ROOT\Excel.Application` has a `CurVer` key under it pointing it to a specific excel app.If using `GetObject` you can specify which class to use as the second parameter.
score: 0
comment on: http://stackoverflow.com/q/48157639
type: Comment

cox
tags question: http://stackoverflow.com/q/48076384
tag name: cox
type: Tag

http://stackoverflow.com/comment/83028519
has text: Try evaluating `sfactorr(2)` by hand, step by step.
comment on: http://stackoverflow.com/q/48029204
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/83151776
type: QuestionComment
comment on: http://stackoverflow.com/q/48088206
has text: The point of preparing a MCVE is that often doing that work means the answer will present itself to you. With the JSON data laid out in human readable form the need for the nesting call that @johnll so wisely pointed out becomes so much clearer. All tricks of the debugging trade :).
score: 0
type: Comment

http://stackoverflow.com/a/48116463
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83410852
has body: I think the problem is here in this part of your code. val = tf.transpose(val, [1, 0, 2]) last = tf.gather(val, int(val.get_shape()[0]) - 1) The output of the RNN is (timestep, batch_index, data) and you are transposing to (batch_index, timestep, data). Then you do gather with indices = shape[0] - 1 on axis 0 (that's the default). So you are taking the last element of batch. You probably want to specify to axis 1. Another way to do it, that would keep the code cleaner is: last = val[:, -1, :] I'm guessing you are only doing one time step in your test so that should explain the 1. I don't see any other bug right now so I would guess your input_size is 3 and when you do the matrix multiplication you get the [1, 3]. Check that the weight has a shape like (x, 100). If your batch size is 100 fixing those two should give a result that has the right shape.
has comment: http://stackoverflow.com/comment/83350140
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/83217618
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48115671
has comment: http://stackoverflow.com/comment/83271892
answers question: http://stackoverflow.com/q/48115671

http://stackoverflow.com/comment/83006053
comment on: http://stackoverflow.com/a/48018575
has text: `set(map(sum, product(*lists)))` based on Op's requirements.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48116380
has comment: http://stackoverflow.com/comment/83216236
has body: I am creating a program to manipulate my MTG card collection (Geek, I know) in which I am uploading a csv file of my collection and attempting to make an object of the individual sets with objects of the individual cards inside those sets. All of the cards will have different attributes, as they will contain the amount of each card I own, however there are a lot of cards with the same name, but not in the same set. I'm trying to understand what is the easiest way to perform this task and if I make an instance of a card in one set, will it be erased/overwritten if I create an instance with the same name for a different set. Or would it just be easier (make more sense) to create and object of the sets and make a list of dictionaries for the individual cards. Here's what I have so far: import csv class CardSet: def __init__(self, set_name): self.set_name = set_name def get_set(self): return self.set_name def add_card(card_name, card_num, amount, numb_foil, signed): cards = [] card_name = Card(card_name, card_num, amount, numb_foil, signed) cards.append(card_name) return cards class Card: def __init__(self, card_name, card_num, amount, numb_foil, signed): self.card_name = card_name self.card_num = card_num self.amount = amount self.numb_foil = numb_foil self.signed = signed def csv_reader(): # upload csv file cards = csv.reader(open('Collection.csv', 'rt', encoding='utf8')) list_sets = [] # keeps a tally of set names, as to not duplicate set objects list_obj_sets = [] # list of set objects to search through # Make a list of individual sets in collection, then make an instance of that card set # row[2] = Card Name, row[4] = card number, row[0] = amount owned, row[6] = foil owned, row[7] = signed for row in cards: # if set object does not exist, create object and add card to set if row[3] not in list_sets: # row[3] contains set name list_sets.append(row[3]) row[3] = CardSet(row[3]) # create set object list_obj_sets.append(row[3]) row[3].add_card(row[2], row[4], row[0], ro…
type: Question
has comment: http://stackoverflow.com/comment/83216884
tagged with: class
has title: Instances with the same name
score: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/83216383
has comment: http://stackoverflow.com/comment/83216887
has comment: http://stackoverflow.com/comment/83230608
type: UnansweredQuestion
tagged with: python
tagged with: oop
answer count: 0

http://stackoverflow.com/q/48090119
possible better answer: http://stackoverflow.com/a/51749538
downvote count: 0
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/49131619
tagged with: python
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/60100634
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48484697
upvote count: 31
has body: I recently installed jupyter notebooks on my macbook pro. When I create a new notebook, I see the following exception coming continuously on the terminal where I started the notebook. Monideeps-MacBook-Pro:PythonNotebooks monideepde$ jupyter-notebook [I 12:18:43.675 NotebookApp] Serving notebooks from local directory: /Users/monideepde/Documents/PythonNotebooks [I 12:18:43.675 NotebookApp] 0 active kernels [I 12:18:43.676 NotebookApp] The Jupyter Notebook is running at: [I 12:18:43.676 NotebookApp] http://localhost:8888/?token=dcb1990694d91ded77f4287a588886ea567b5907ac8aeafa [I 12:18:43.676 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [C 12:18:43.677 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=dcb1990694d91ded77f4287a588886ea567b5907ac8aeafa [I 12:18:43.896 NotebookApp] Accepting one-time-token-authenticated connection from ::1 [W 12:18:44.778 NotebookApp] 404 GET /static/components/moment/locale/en-gb.js?v=20180104121843 (::1) 21.10ms referer=http://localhost:8888/tree [I 12:18:54.840 NotebookApp] Creating new notebook in [W 12:18:55.716 NotebookApp] 404 GET /static/components/moment/locale/en-gb.js?v=20180104121843 (::1) 3.06ms referer=http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2 [I 12:18:55.920 NotebookApp] Kernel started: 5e16fa4b-3e35-4265-89b0-ab36bb0573f5 [W 12:18:55.941 NotebookApp] 404 GET /nbextensions/widgets/notebook/js/extension.js?v=20180104121843 (::1) 5.57ms referer=http://localhost:8888/notebooks/Untitled.ipynb?kernel_name=python2 [I 12:18:56.998 NotebookApp] Adapting to protocol v5.1 for kernel 5e16fa4b-3e35-4265-89b0-ab36bb0573f5 [E 12:18:57.001 NotebookApp] Uncaught exception in /api/kernels/5e16fa4b-3e35-4265-89b0-ab36bb0573f5/channels Traceback (most recent call last): File "/Library/Python/2.7/site-packages/tornado-5.0a1-py2.7-macosx-10.13-intel.egg/tornado/websocket.py"…
has comment: http://stackoverflow.com/comment/83181519
type: Question
score: 31
has comment: http://stackoverflow.com/comment/87397753
has comment: http://stackoverflow.com/comment/83154907
has answer: http://stackoverflow.com/a/51749538
has title: Jupyter notebook: TypeError: __init__() got an unexpected keyword argument 'io_loop'
has answer: http://stackoverflow.com/a/78233333
has answer: http://stackoverflow.com/a/48484697

http://stackoverflow.com/comment/83260363
has text: You're asking how to implement backoff/retry for the HTTP POST to the 3rd-party API, right? (not via boto3 to SQS) There are NPM modules that do this, for example: https://github.com/FGRibreau/node-request-retry
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48138094

http://stackoverflow.com/a/48075387
upvote count: 12
has comment: http://stackoverflow.com/comment/97478871
type: Answer
score: 11
has body: The user models in Airflow are currently simplistic and (as of at least 1.9.0) there is no way via the UI to set passwords. The approach I use is the following python script: #!/usr/bin/env python import argparse import getpass import sys def create_user(opts): from airflow.contrib.auth.backends.password_auth import PasswordUser from airflow import models, settings u = PasswordUser(models.User()) u.username = opts['username'] u.email = opts['email'] u.password = opts['password'] s = settings.Session() s.add(u) s.commit() s.close() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('email') parser.add_argument('username', nargs='?', help="Defaults to local part of email") args = parser.parse_args() if not args.username: # Default username is the local part of the email address args.username = args.email[:args.email.index('@')] args.password = getpass.getpass(prompt="Enter new user password: ") confirm = getpass.getpass(prompt="Confirm: ") if args.password != confirm: sys.stderr.write("Passwords don't match\n") sys.exit(1) create_user(vars(args)) This versoin doesn't support changing passwords as we haven't needed it yet
has comment: http://stackoverflow.com/comment/92038087
has comment: http://stackoverflow.com/comment/91935977
answers question: http://stackoverflow.com/q/48072563
has comment: http://stackoverflow.com/comment/91531792
downvote count: 1
has comment: http://stackoverflow.com/comment/92055242

http://stackoverflow.com/comment/83076664
comment on: http://stackoverflow.com/q/48051769
score: 0
type: Comment
type: QuestionComment
has text: Thank you. Now I get better results. Is there a way I can get the words seperately like say AROMA in an image and CAFE in an image and so on ?

http://stackoverflow.com/a/48086680
type: Answer
has body: You could use list comprehension: def multdimensional_list(i): link = 'https://hooks.com/catch/123' return [[n,link] for n in range(1, i+1)] multidimensional_list(3) returns: [[1, 'https://hooks.com/catch/123'], [2, 'https://hooks.com/catch/123'], [3, 'https://hooks.com/catch/123']]
score: 0
answers question: http://stackoverflow.com/q/48086602

http://stackoverflow.com/comment/83114870
comment on: http://stackoverflow.com/q/48070420
has text: @Blurp no error happens but now nothing is shown in browser.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48055157
type: AnsweredQuestion
score: 1
tagged with: concurrency
type: Question
has answer: http://stackoverflow.com/a/48057951
tagged with: python-asyncio
downvote count: 0
answer count: 1
tagged with: asynchronous
favorite count: 0
tagged with: python-3.x
has title: Pausing Python asyncio coroutines
accepted answer: http://stackoverflow.com/a/48057951
upvote count: 1
tagged with: python
has body: As my project heavily relies on asynchronous network I/O, I always have to expect some weird network error to occur: whether it is the service I'm connecting to having an API outage, or my own server having a network issue, or something else. Issues like that appear, and there's no real way around it. So, I eventually ended up trying to figure out a way to effectively "pause" a coroutine's execution from outside whenever such a network issue occured, until the connection has been reestablished. My approach is writing a decorator pausable that takes an argument pause which is a coroutine function that will be yielded from / awaited like this: def pausable(pause, resume_check=None, delay_start=None): if not asyncio.iscoroutinefunction(pause): raise TypeError("pause must be a coroutine function") if not (delay_start is None or asyncio.iscoroutinefunction(delay_start)): raise TypeError("delay_start must be a coroutine function") def wrapper(coro): @asyncio.coroutine def wrapped(*args, **kwargs): if delay_start is not None: yield from delay_start() for x in coro(*args, **kwargs): try: yield from pause() yield x # catch exceptions the regular discord.py user might not catch except (asyncio.CancelledError, aiohttp.ClientError, websockets.WebSocketProtocolError, ConnectionClosed, # bunch of other network errors ) as ex: if any((resume_check() if resume_check is not None else False and isinstance(ex, asyncio.CancelledError), # clean disconnect isinstance(ex, ConnectionClosed) and ex.code == 1000, # connection issue not isinstance(ex, ConnectionClosed))): yield from pause() yield x else: raise return wrapped return wrapper Pay special attention to this bit: for x in coro(*args, **kwargs): yield from pause() yield x Example usage (ready is an asyncio.Event): @pausable(ready.wait, resume_check=restarting_enabled, delay_start=ready.wait) @asyncio.coroutine def send_test_every_minute(): while True: yield from client.send("Test") yield from asyncio.sleep(60) However, this does not…

http://stackoverflow.com/a/48052374
upvote count: 3
score: 3
downvote count: 0
has body: Try to add your string 'a' to your list in a list iteration after you create your range. For instance: column_names = range(3) column_names = ['a'+str(i) for i in x] you can then use this list as your columns argument when you define your dataframe.
answers question: http://stackoverflow.com/q/48052336
type: Answer

http://stackoverflow.com/q/48064225
accepted answer: http://stackoverflow.com/a/48084031
answer count: 1
downvote count: 0
favorite count: 0
tagged with: protocol-buffers
has body: If you have a module object corresponding to a module_name_pb2.py file, or access to the .proto file itself, is there a way to print the spec itself in a pretty way? JSON? I want to show the fields and the types. I am not looking to print an instance e.g., Print human friendly Protobuf message Given some protobuf message format (Defined in a .proto file) like: message XYData { float x = 1; float y = 2; } I am looking for something like: { "name" : "XYData", "fields" : [ {"name" : "x", "type" : "float"}, {"name" : "y", "type" : "float"} ] } It would also be nice to be able to list all the messages defined in the .proto file. EDIT: maybe something like this but in Python: https://github.com/devongovett/protobuf-jsonschema
tagged with: python
linked to: http://stackoverflow.com/q/33557965
has answer: http://stackoverflow.com/a/48084031
type: AnsweredQuestion
upvote count: 3
has title: Python: print protobuf spec (fields, types)
type: Question
score: 3

http://stackoverflow.com/q/48151494
has title: How can this for-loop with range be explained
tagged with: range
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83281334
accepted answer: http://stackoverflow.com/a/48151829
has comment: http://stackoverflow.com/comment/83281799
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/83281332
downvote count: 5
type: Question
has comment: http://stackoverflow.com/comment/83281327
tagged with: for-loop
upvote count: 0
answer count: 1
has body: Can someone please help me how to understand this code: j = 0 for i in range(1, 8, 2): j += i print (j) The output is: 1 4 9 16 But I just cannot understand why. I get the concept of for-loops and range. But the involvement of the variable and the += operand makes me confused. Can someone explain this step by step, so that I can understand why the output is what it is?
has answer: http://stackoverflow.com/a/48151829

http://stackoverflow.com/comment/83296466
type: QuestionComment
comment on: http://stackoverflow.com/q/48158330
score: 1
has text: So use `classes = div.get('class', [])` and `print u' '.join(classes)` to print all classes on a div.
type: Comment

web-scraping
tags question: http://stackoverflow.com/q/48051158
tags question: http://stackoverflow.com/q/48018096
tags question: http://stackoverflow.com/q/48014693
tags question: http://stackoverflow.com/q/48127226
tags question: http://stackoverflow.com/q/48042281
tags question: http://stackoverflow.com/q/48015404
tags question: http://stackoverflow.com/q/48016567
tags question: http://stackoverflow.com/q/48161575
tags question: http://stackoverflow.com/q/48032574
tags question: http://stackoverflow.com/q/48136266
tags question: http://stackoverflow.com/q/48135461
tags question: http://stackoverflow.com/q/48028782
tags question: http://stackoverflow.com/q/48026031
tags question: http://stackoverflow.com/q/48030528
tags question: http://stackoverflow.com/q/48037685
tags question: http://stackoverflow.com/q/48058150
tags question: http://stackoverflow.com/q/48043629
tags question: http://stackoverflow.com/q/48088582
tags question: http://stackoverflow.com/q/48065020
tags question: http://stackoverflow.com/q/48155877
tags question: http://stackoverflow.com/q/48124970
tags question: http://stackoverflow.com/q/48046391
tags question: http://stackoverflow.com/q/48051766
tags question: http://stackoverflow.com/q/48043726
tags question: http://stackoverflow.com/q/48076329
tags question: http://stackoverflow.com/q/48060113
tags question: http://stackoverflow.com/q/48040836
tags question: http://stackoverflow.com/q/48051371
tags question: http://stackoverflow.com/q/48022598
tags question: http://stackoverflow.com/q/48165357
tags question: http://stackoverflow.com/q/48118464
tags question: http://stackoverflow.com/q/48170490
tags question: http://stackoverflow.com/q/48081320
tags question: http://stackoverflow.com/q/48145958
tags question: http://stackoverflow.com/q/48129522
tags question: http://stackoverflow.com/q/48028041
tags question: http://stackoverflow.com/q/48125300
tags question: http://stackoverflow.com/q/48024364
tags question: http://stackoverflow.com/q/48125006
tags question: http://stackoverflow.com/q/48113622
tags question: http://stackoverflow.com/q/48133252
tags question: http://stackoverflow.com/q/48114098
tags question: http://stackoverflow.com/q/48065012
tags question: http://stackoverflow.com/q/48160554
tags question: http://stackoverflow.com/q/48015149
tags question: http://stackoverflow.com/q/48065361
tags question: http://stackoverflow.com/q/48047024
tags question: http://stackoverflow.com/q/48154085
tags question: http://stackoverflow.com/q/48023860
tag name: web-scraping
tags question: http://stackoverflow.com/q/48031314
tags question: http://stackoverflow.com/q/48134390
tags question: http://stackoverflow.com/q/48075312
tags question: http://stackoverflow.com/q/48054343
tags question: http://stackoverflow.com/q/48057647
tags question: http://stackoverflow.com/q/48033398
type: Tag
tags question: http://stackoverflow.com/q/48074730
tags question: http://stackoverflow.com/q/48063165
tags question: http://stackoverflow.com/q/48158451
tags question: http://stackoverflow.com/q/48049289
tags question: http://stackoverflow.com/q/48139454
tags question: http://stackoverflow.com/q/48172972
tags question: http://stackoverflow.com/q/48052647
tags question: http://stackoverflow.com/q/48114722
tags question: http://stackoverflow.com/q/48036369
tags question: http://stackoverflow.com/q/48047719
tags question: http://stackoverflow.com/q/48081655
tags question: http://stackoverflow.com/q/48158028
tags question: http://stackoverflow.com/q/48057732

http://stackoverflow.com/a/48134908
has body: Your issue is in the line: 2.50 += health This says that you are trying to assign 2.50 + health, to a literal. You cannot assign a value to a literal. What you are trying to do is increment health by 2.50, which can be done by reversing the order of your arguments. Change the line 2.50 += health, to health += 2.50 and your code will work.
score: 2
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48134890

http://stackoverflow.com/a/48039246
has comment: http://stackoverflow.com/comment/83115548
has comment: http://stackoverflow.com/comment/83065145
answers question: http://stackoverflow.com/q/48039195
has comment: http://stackoverflow.com/comment/83119187
has comment: http://stackoverflow.com/comment/83117324
has comment: http://stackoverflow.com/comment/83118933
has body: One approach is to proxy all traffic to the Kibana server through the Flask application. You can use a catch-all route to handle forwarding of the different paths. You would disallow access to Kibana from sources other than from the Flask application. import requests # may require `pip install requests` kibana_server_baseurl = 'https://xxx.xxx.xxx.xxx:5601/' @app.route('/', defaults={'path': ''}) @app.route('/&lt;path:path&gt;') @login_required def proxy_kibana_requests(path): # ref http://flask.pocoo.org/snippets/118/ url = kibana_server_baseurl + path req = requests.get(url, stream = True) return Response(stream_with_context(req.iter_content()), content_type = req.headers['content-type']) Another options is to use Nginx as a reverse proxy and use Nginx to handle authentication. The simplest, if it meets your needs, is to use basic auth. https://www.nginx.com/resources/admin-guide/restricting-access-auth-basic/. Alternatively you could check for a custom header in the Nginx config on access to the Kibana application and redirect to the Flask application if it were missing. Another option is to use an existing Kibana authentication proxy. A commercial option, Elastic x-pack is a popular option. Another OSS option is https://github.com/fangli/kibana-authentication-proxy. I have not personally used either.
has comment: http://stackoverflow.com/comment/83118507
has comment: http://stackoverflow.com/comment/83065288
has comment: http://stackoverflow.com/comment/83117555
has comment: http://stackoverflow.com/comment/83049863
score: 0
type: Answer

http://stackoverflow.com/comment/83164649
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48094895
type: Comment
has text: @erhesto and completely correct, yet I wrote new names for variables.

http://stackoverflow.com/q/48020408
answer count: 0
type: UnansweredQuestion
tagged with: python
has title: Animation is not happening in python
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/83014456
has comment: http://stackoverflow.com/comment/83011697
upvote count: 1
has body: I m trying to make an animation plot in python using matplotlib.animation and the package is present. But when I execute the program it is not showing any error but also no animation is there. %matplotlib notebook import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np n=100 x= np.random.randn(n) def update(curr): if curr == n: a.event_source.stop() plt.cla() bins = np.arrange(-4,4,0.5) plt.hist(x[:curr],bins=bins) plt.axis([-4,4,0,30]) plt.gca().set_title('Sampling the normal distribution') plt.gca().set_xlabel('Value') plt.gca().set_ylabel('Frequency') plt.annotate('n={}'.format(curr),[3,27]) fig = plt.figure() a = animation.FuncAnimation(fig,update,interval =100) Looking forward to a solution. Thank you.
favorite count: 0

http://stackoverflow.com/comment/139738004
type: Comment
has text: You also need to override the add_fieldsets parameter in your custom UserAdmin class for this to work, otherwise the added fields won't show!
comment on: http://stackoverflow.com/a/48051451
type: AnswerComment
score: 0

http://stackoverflow.com/a/48087886
has comment: http://stackoverflow.com/comment/83184427
has comment: http://stackoverflow.com/comment/83185674
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48087525
has comment: http://stackoverflow.com/comment/83184172
answers question: http://stackoverflow.com/q/48087525
upvote count: 1
has body: They are not random characters. 0xFF 0xFE is the byte order mark for UTF16 encoded data. The presence of these bytes indicates the encoding and endianess of the file/stream, in this case it is little endian UTF16. The additional "spaces" between the characters is also a hint: these are actually NUL characters (0x00) that have been rendered as spaces in the error message. The solution is to re-encode the SQL script file to UTF8, ASCII or other supported encoding. You could do that to the file itself using a conversion tool such as iconv or open the file in an editor and save it back as UTF8. Alternatively you can handle the encoding in your code. The nature of the problem suggests that you are using Python 2: import codecs def sql_reader_single(qry_file, encoding='utf16', server_name, database): server = db.connect(str('DRIVER={SQL Server}; SERVER='+server_name+'; DATABASE='+database+';')) with codecs.open(qry_file, encoding=encoding) as qf: data = pd.read_sql(qf.read(), server)
has comment: http://stackoverflow.com/comment/83182240
score: 1

http://stackoverflow.com/a/48126606
downvote count: 0
type: Answer
upvote count: 1
has body: You can set the path from the current cmd window using the PATH = command. That will only add it for the current cmd instance. if you want to add it permanently, you should add it to system variables. Computer &gt; Advanced System Settings &gt; Environment Variables You would goto your cmd instance, and put in: PATH = C:/Python3/ Check the folder name for Python in you C drive and edit the above appropriately.
score: 1
answers question: http://stackoverflow.com/q/48126563

http://stackoverflow.com/comment/83061028
comment on: http://stackoverflow.com/a/48044246
has text: Even if I read the documentation I'm not sure i would have understood it that easily. Thanks again, that's perfect!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48053635
score: 8
upvote count: 9
has comment: http://stackoverflow.com/comment/83080897
accepted answer of: http://stackoverflow.com/q/48053207
type: Answer
has comment: http://stackoverflow.com/comment/83080957
answers question: http://stackoverflow.com/q/48053207
type: AcceptedAnswer
has body: It's hard to tell what might be going wrong without seeing the rest of the code. I've developed some test data and logic that works; you can adapt it to fit your needs. Please try this: import pandas as pd early_inventions = ['wheel', 'fire', 'bronze'] later_inventions = ['automobile', 'computer', 'rocket'] early_names = ['a', 'b', 'c'] later_names = ['z', 'y', 'x'] early_dates = ['2000-01-01', '2001-10-01', '2002-03-10'] later_dates = ['2010-01-28', '2011-10-10', '2012-12-31'] early_data = {'Invention': early_inventions, 'Inventor': early_names, 'Date': early_dates} later_data = {'Invention': later_inventions, 'Inventor': later_names, 'Date': later_dates} datasets = [early_data, later_data] columns = ['Invention', 'Inventor', 'Date'] header = True for dataset in datasets: df = pd.DataFrame(dataset) df = df[columns] mode = 'w' if header else 'a' df.to_csv('./new.csv', encoding='utf-8', mode=mode, header=header, index=False) header = False Alternatively, you can concatenate all of the data in the loop and write out the dataframe at the end: df = pd.DataFrame(columns=columns) for dataset in datasets: df = pd.concat([df, pd.DataFrame(dataset)]) df = df[columns] df.to_csv('./new.csv', encoding='utf-8', index=False) If your code cannot be made to conform to this API, you can forego writing the header in to_csv altogether. You can detect whether the output file exists and write the header to it first if it does not: import os fn = './new.csv' if not os.path.exists(fn): with open(fn, mode='w', encoding='utf-8') as f: f.write(','.join(columns) + '\n') # Now append the dataframe without a header df.to_csv(fn, encoding='utf-8', mode='a', header=False, index=False)
has comment: http://stackoverflow.com/comment/83080755
downvote count: 1

http://stackoverflow.com/a/74791808
has comment: http://stackoverflow.com/comment/132065478
has body: it's probably not related but if you are using vs-code on windows and you got this error just try to run from cmd, not from vs-code
score: 0
answers question: http://stackoverflow.com/q/48075864
type: Answer

http://stackoverflow.com/comment/83263872
type: AnswerComment
comment on: http://stackoverflow.com/a/48142651
has text: @Kermit I need a feedback to help you
type: Comment
score: 0

http://stackoverflow.com/q/48112886
tagged with: python
has comment: http://stackoverflow.com/comment/83204648
answer count: 0
tagged with: screenshot
type: UnansweredQuestion
has title: How to include a made screenshot to json/html report
has comment: http://stackoverflow.com/comment/105279265
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/83203464
tagged with: python-behave
linked to: http://stackoverflow.com/q/3715493
has comment: http://stackoverflow.com/comment/83201767
type: Question
has body: I use Bahave and there is a next condition for after_scenario in environment.py def after_scenario(context, scenario): if scenario.status == "failed": time_now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") context.browser.save_screenshot("failed_scenarios_screenshots/%s_%s_failed.png" % (scenario.name, time_now)) How can I add a made screenshot into json or html report?
score: 0

http://stackoverflow.com/q/48025999
has comment: http://stackoverflow.com/comment/83021735
has title: pyqtgraph for plotting multiple data lists
type: Question
has comment: http://stackoverflow.com/comment/83021825
tagged with: performance
has answer: http://stackoverflow.com/a/57280036
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/57280036
has comment: http://stackoverflow.com/comment/83022259
has comment: http://stackoverflow.com/comment/83021653
has answer: http://stackoverflow.com/a/48027058
has comment: http://stackoverflow.com/comment/83022188
has comment: http://stackoverflow.com/comment/83023434
tagged with: python
tagged with: pyqtgraph
has body: At the moment I am using matplotlib to plot multiple numpy arrays (or lists) of data. These correspond to approximately 3000 plots. The plots are time series. My problem is that when these lists become too large with a lot of data, matplotlib is very slow. I read that pyqtgraph can plot really fast, but my question is: Can you use pyqtgraph to plot data without spawning that pyqt window and instead directly save them to files? Matplotlib had an option to change backend so it does not spawn the window but instead just create the file, is there something similar for pyqtgraph? Also do you think that, for my problem, pyqtgraph is the correct way to go? I see it a lot for plotting streaming data live, but what I want to do does not involve live stream data. Should I use something else to create plots for all my data?
tagged with: plot
accepted answer: http://stackoverflow.com/a/48027058
type: AnsweredQuestion

http://stackoverflow.com/comment/83323248
comment on: http://stackoverflow.com/q/48171679
score: 0
type: Comment
type: QuestionComment
has text: In the documentation of REST API for this Server , It is mentioned that it requires a valid username and password. It uses JSON format. One more thing when i run this hard coded token in my script , it works . i got this code from Postman

http://stackoverflow.com/a/48108895
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/83194762
answers question: http://stackoverflow.com/q/48108403
has body: One can use easily understandable for loop and work over each row: newvals = [] for i in range(len(df.index)): ROW = df.iloc[i,:] if ROW.D2&gt;ROW.I2: ROW.I3=ROW.I2+ROW.I3 ROW.D3=ROW.D2+ROW.D3 ROW.I2=ROW.D2=0 if ROW.D3&gt;ROW.I3: ROW.I2=ROW.I2+ROW.I3 ROW.D2=ROW.D2+ROW.D3 ROW.I3=ROW.D3=0 newvals.append(list(ROW)) newdf = pd.DataFrame(data=newvals, columns=df.columns) print(newdf) Output: Date Factory I1 D1 I2 D2 I3 D3 0 1701 West 0 0 0 0 10 0 1 1701 East 39 0 86 30 0 0 2 1701 West 0 0 0 0 15 10
has comment: http://stackoverflow.com/comment/83193123
has comment: http://stackoverflow.com/comment/83195583

http://stackoverflow.com/comment/83181170
has text: @Kris tl;dr is you want `itertools.product()`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48086273

http://stackoverflow.com/comment/83302165
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48135635
type: Comment
has text: `gmpy2` also has a very fast factorial function. On my computer `str(math.factorial(100000))` requires ~2.5 seconds. `str(gmpy2.fac(100000))` only requires ~0.03 seconds. And `str(gmpy2.fac(1000000))` requires ~0.7 seconds.

http://stackoverflow.com/comment/83229668
has text: Also, there are many situations where you cannot choose, but if you can, choosing Python 2 is the wrong choice now.
score: 0
comment on: http://stackoverflow.com/q/48125882
type: Comment
type: QuestionComment

strip
tags question: http://stackoverflow.com/q/48157533
tag name: strip
tags question: http://stackoverflow.com/q/48090213
type: Tag

http://stackoverflow.com/a/48018575
has comment: http://stackoverflow.com/comment/83006053
has comment: http://stackoverflow.com/comment/83006117
has comment: http://stackoverflow.com/comment/83006135
has body: map(sum, product(*lists)) Demo: &gt;&gt;&gt; from itertools import product &gt;&gt;&gt; lists = [11, 22], [33, 44, 55, 66], [77, 88, 99] &gt;&gt;&gt; map(sum, product(*lists)) [121, 132, 143, 132, 143, 154, 143, 154, 165, 154, 165, 176, 132, 143, 154, 143, 154, 165, 154, 165, 176, 165, 176, 187]
type: Answer
upvote count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/83006088
has comment: http://stackoverflow.com/comment/83006176
score: 1
answers question: http://stackoverflow.com/q/48018439
has comment: http://stackoverflow.com/comment/83006439

http://stackoverflow.com/a/48094892
type: Answer
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/48094725
has body: There's nothing wrong with your code. You could shorten it by constructing a generator and calling next on it. &gt;&gt;&gt; demo = {1:2, 3:4, 5:6} &gt;&gt;&gt; next(demo[k] for k in (6,3,5) if k in demo) 4 This also allows for a default value: &gt;&gt;&gt; next((demo[k] for k in (0,-1,-2) if k in demo), 'default') 'default'

http://stackoverflow.com/q/48029070
has comment: http://stackoverflow.com/comment/83028707
tagged with: python
has title: How to iterate through groups without sorting?
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has body: I have a carefully sorted dataframe like this: x = pd.DataFrame({'col1':['b', 'e','e', 'g','g', 'f','f'], 'col2':['f', 'g','f', 'f','e', 'g','e'], 'col3':[ 1 , 7 , 2 , 6 , 7 , 20, 5 ]}) I want to summarize the groups to one row each, preserving the order names, totals, fs = zip(* list( (name, total(group), f(group)) for name, group in x.groupby('col1')) ) out = pd.DataFrame({'lang':names, 'total':totals, 'partners':tails}) But in out rows are sorted by col1. While x.groupby('col1').heads() yields everything in correct order, iterating as in [name for name, _ in x.groupby('col1')] returns ['b', 'e', 'f', 'g'] when 'f' should stay behind 'g' How can I loop through groups without sorting?
tagged with: dataframe
tagged with: pandas-groupby
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83028894
has answer: http://stackoverflow.com/a/48029435
accepted answer: http://stackoverflow.com/a/48029435

http://stackoverflow.com/q/48095978
has comment: http://stackoverflow.com/comment/83170666
score: 0
tagged with: time-complexity
has body: I have two ranges and want to check if they overlap in Python (v3.5). These are some solutions. 1a: use set intersection with range: def overlap_intersection_set(range1, range2): return bool(set(range1).intersection(range2)) 1b: use set intersection with two sets: def overlap_intersection_two_sets(range1, range2): return bool(set(range1).intersection(set(range2))) 2: use any and range in: def overlap_any(range1, range2): return any([i1 in range2 for i1 in range1]) I've been trying to compute the cost for these approaches, mostly in terms of time, but space complexity might also be considerable. The Python Wiki page "Time Complexity" lists for the set intersections (average case): Intersection s&amp;t (average case): O(min(len(s), len(t)) (replace "min" with "max" if t is not a set) For solution 1b, I hence assume O(min(len(range1), len(range2)), plus two times a set creation from a range. I consider the bool function very cheap. For solution 1a: O(max(len(range1), len(range2)), plus once a set creation from a range. For solution 2 (any): I have not found much documentation regarding complexities, neither for any nor for range in. For the latter, I assume that a range behaves like a list, which would mean O(n) for each in call, hence resulting in O(n*m) with n=len(range1) and m=len(range2). At the same time, any should lead to a shortcut as soon as a match is found and the set creation can be spared. My questions thus involve algorithmic complexities as well as their Python-specific implementations: How expensive is it to convert a range to a set? How expensive is the bool() function really? Does in for a range really behave as in a list (O(n))? What other implementation details are relevant apart from algorithmic complexity? Ultimately, considering these questions: what is the most efficient way to check for an overlap between two ranges? This is not easy to evaluate empirically as the actual computation time depends a lot on the properties of the ranges, i.e. how e…
answer count: 1
has comment: http://stackoverflow.com/comment/83176782
has comment: http://stackoverflow.com/comment/83166654
has comment: http://stackoverflow.com/comment/83170229
tagged with: python
type: AnsweredQuestion
has title: Python: complexity of check for overlapping ranges
accepted answer: http://stackoverflow.com/a/48100266
type: Question
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83175985
has answer: http://stackoverflow.com/a/48100266

http://stackoverflow.com/q/48151637
type: UnansweredQuestion
score: 26
has answer: http://stackoverflow.com/a/53910933
upvote count: 26
type: Question
has title: Pytorch: Create an boolean tensor (type: torch.ByteTensor)?
has answer: http://stackoverflow.com/a/78051144
downvote count: 0
has answer: http://stackoverflow.com/a/48151653
has body: I want to create a tensor only containing boolean values. In Matlab that would be a = false(10,1)
answer count: 3
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/106192006
tagged with: pytorch

http://stackoverflow.com/comment/83085101
comment on: http://stackoverflow.com/q/48056360
has text: And your expected output?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48167290
tagged with: apache-spark-sql
tagged with: pyspark
score: 0
answer count: 2
has body: Here is my two PySpark Dataframe a = sc.parallelize([['2017-05-14', 'foo' , 24 , 'abc'], ['2017-05-16', 'user1', 26, 'mno'], ['2017-05-17', 'user2', 26, 'mno'], ['2017-05-19', 'user2', 27, 'mno'], ['2017-05-19', 'user3', 28, 'mno']]) .toDF(['A_Date', 'user', 'id','info']) b = sc.parallelize([['2017-05-15', 'foo', 24, 'def'], ['2017-05-22', 'user2', 27, 'mno'], ['2017-05-20', 'user3', 28, 'mno']]) .toDF(['B_Date', 'user', 'id','info']) and i want to join two dataframe compairing some dataframe and date of dataframe in a joined data should be just less than dataframe b as shown below. c = sc.parallelize([['2017-05-15', 'foo', 24, 'def', '2017-05-14'], ['2017-05-22', 'user2', 27, 'mno', '2017-05-19'], ['2017-05-20', 'user3', 28,'mno','2017-05-19']]) .toDF(['B_Date', 'user', 'id','info', 'A_Date'])
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48174639
has answer: http://stackoverflow.com/a/48169168
has title: INNER join two PySpark dataframe on the user defined functions [next Date]
tagged with: inner-join
type: Question

http://stackoverflow.com/comment/83101249
type: QuestionComment
has text: import pyglet window = pyglet.window.Window(width=320, height=200,caption='window') #label = pyglet.text.Label('Hello, world') pyglet.app.run() This works without the commented line. When I uncomment the line, same problem
comment on: http://stackoverflow.com/q/48063402
score: 0
type: Comment

http://stackoverflow.com/q/48040102
has answer: http://stackoverflow.com/a/48040506
downvote count: 2
has answer: http://stackoverflow.com/a/48040172
has comment: http://stackoverflow.com/comment/83051085
has comment: http://stackoverflow.com/comment/83050683
linked to: http://stackoverflow.com/q/5690269
has title: I deleted a css static file but my website still reads it?
has answer: http://stackoverflow.com/a/48040128
upvote count: 5
accepted answer: http://stackoverflow.com/a/48040172
has comment: http://stackoverflow.com/comment/83051193
has comment: http://stackoverflow.com/comment/83083819
has body: I have a static css file called blog.css, and I load it in my base.html template like this: {% load static %} &lt;link rel="stylesheet" type="text/css" href="{% static 'css/blog.css' %}"&gt; But when I wanted to change something in that css, the changes doesn't appear. Due to my confusion, I tried to test some things. renaming blog.css to blog2.css The weird part is, when I make changes to blog2.css, and called it in the base.html, my changes work, such as changing the background color, and etc. but when I make changes to blog.css, nothing happens. So, I tried to DELETE blog.css, but still called it in the base.html. everything still works when I first made that file. I'm supposed to be expecting a broken designed HTML page and a 404 in the console because the blog.css in the static folder cannot be found. It's like the blog.css is a ghost or something that is still here in my folder somewhere.. or am I missing something? I also tried restarting the runserver command, refreshing the page countless times, and even restarting my computer. I'm quite new to Django and I'm trying my best to understand it, and any help given is appreciated. Thank you very much!
has answer: http://stackoverflow.com/a/65821860
answer count: 4
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/83063009
tagged with: django-staticfiles
favorite count: 0
has comment: http://stackoverflow.com/comment/83050706
type: Question
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83057298
possible better answer: http://stackoverflow.com/a/48040506

http://stackoverflow.com/q/48061022
favorite count: 0
has title: Python: Get datetime (with timezone info) from number (epoch time) and convert it to string of specific date format
tagged with: python-3.x
downvote count: 2
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/83097427
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83094508
upvote count: 3
score: 1
has answer: http://stackoverflow.com/a/48061077
has body: While scraping data from the internet, I am getting a number as a response instead of the date-time string. Below are few example: 1508486400 -- instead of "2017, 20 Oct 10:00:00" 1510974000 -- instead of "2017, 18 Nov 4:00:00" 1388664000 -- instead of "2014, 02 Jan 13:00:00" I want to convert these number to the corresponding date in the format "dd/mm/yyyy". Though preserving the timezone is not a mandate, but it is good if I could get the string based on the timezone to which my dates belong. The dates I am trying to extract from the number belongs to "CAT+2:00:00" timezone.
type: Question
possible better answer: http://stackoverflow.com/a/48061119
has answer: http://stackoverflow.com/a/48061119
answer count: 3
has answer: http://stackoverflow.com/a/48061205
duplicate of: http://stackoverflow.com/q/12400256
accepted answer: http://stackoverflow.com/a/48061077
has comment: http://stackoverflow.com/comment/83097510
duplicate of: http://stackoverflow.com/q/12978391

http://stackoverflow.com/comment/83128491
has text: In Text editor I see it in numbers but in Excel I see this as dates how can I stop this from automatically converting
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48077263
score: 0

http://stackoverflow.com/q/48111034
has comment: http://stackoverflow.com/comment/83738976
has comment: http://stackoverflow.com/comment/89032764
linked to: http://stackoverflow.com/q/37703634
score: 9
type: Question
answer count: 2
upvote count: 9
has body: I'm trying to load a large CSV (~5GB) into pandas from S3 bucket. Following is the code I tried for a small CSV of 1.4 kb : client = boto3.client('s3') obj = client.get_object(Bucket='grocery', Key='stores.csv') body = obj['Body'] csv_string = body.read().decode('utf-8') df = pd.read_csv(StringIO(csv_string)) This works well for a small CSV, but my requirement of loading a 5GB csv to pandas dataframe cannot be achieved through this (probably due to memory constraints when loading the csv by StringIO). I also tried below code s3 = boto3.client('s3') obj = s3.get_object(Bucket='bucket', Key='key') df = pd.read_csv(obj['Body']) but this gives below error. ValueError: Invalid file path or buffer object type: &lt;class 'botocore.response.StreamingBody'&gt; Any help to resolve this error is much appreciated.
linked to: http://stackoverflow.com/q/48264656
tagged with: amazon-sagemaker
has answer: http://stackoverflow.com/a/65206714
downvote count: 0
has answer: http://stackoverflow.com/a/50642406
favorite count: 0
has title: Reading a large csv from a S3 bucket using python pandas in AWS Sagemaker
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: amazon-s3

http://stackoverflow.com/a/48103263
upvote count: 1
downvote count: 0
has body: You can use multiprocessing python package that simplify threading (among others) to speed up your code. Here you can see a good post where is talking about and some videos.
type: Answer
score: 1
answers question: http://stackoverflow.com/q/48103157

http://stackoverflow.com/a/48098949
has comment: http://stackoverflow.com/comment/83174672
has comment: http://stackoverflow.com/comment/84345093
type: AcceptedAnswer
upvote count: 12
accepted answer of: http://stackoverflow.com/q/48088582
type: Answer
has comment: http://stackoverflow.com/comment/83189141
answers question: http://stackoverflow.com/q/48088582
downvote count: 0
has body: The simplest way to do this is to run them all from the command line. For example: $ scrapy list | xargs -P 4 -n 1 scrapy crawl Will run all your spiders, with up to 4 running in parallel at any time. You can then send a notification in a script once this command has completed. A more robust option is to use scrapyd. This comes with an API, a minimal web interface, etc. It will also queue the crawls and only run a certain (configurable) number at once. You can interact with it via the API to start your spiders and send notifications once they are all complete. Scrapy Cloud is a perfect fit for this [disclaimer: I work for Scrapinghub]. It will allow you only to run a certain number at once and has a queue of pending jobs (which you can modify, browse online, prioritize, etc.) and a more complete API than scrapyd. You shouldn't run all your spiders in a single process. It will probably be slower, can introduce unforeseen bugs, and you may hit resource limits (like you did). If you run them separately using any of the options above, just run enough to max out your hardware resources (usually CPU/network). If you still get problems with file descriptors at that point you should increase the limit.
has comment: http://stackoverflow.com/comment/84215899
has comment: http://stackoverflow.com/comment/83176104
score: 12
has comment: http://stackoverflow.com/comment/83225373
has comment: http://stackoverflow.com/comment/83225481

http://stackoverflow.com/comment/83210178
comment on: http://stackoverflow.com/a/48116132
type: AnswerComment
score: 0
has text: It is problem, because groupby aggregate data. So in output is different number row as original df. Only solution is aggregate all columns like id.
type: Comment

timer
tag name: timer
tags question: http://stackoverflow.com/q/48051627
type: Tag
tags question: http://stackoverflow.com/q/48103435
tags question: http://stackoverflow.com/q/48100714
tags question: http://stackoverflow.com/q/48049861
tags question: http://stackoverflow.com/q/48031274

http://stackoverflow.com/comment/83205626
has text: I don't understand why it is telling that there is an error with "array1.remove([7,2,3,5])" when [7,2,3,5] is a real value in the list despite it telling me its not?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48114794
score: 0

http://stackoverflow.com/a/48106482
has body: There was a portion of my code that I thought was irrelevant to the problem; however, as it turns out it is what was causing the problem: In the code below, I am assigning an element from a dataframe (Opt_report) to the variable opt_neighbors. I thought this assignment would create a scalar value, however, it is a pandas Series that consists of an index number (135) and the integer value (19). When I pass this variable to the n_neighbors argument in the KNeighborsClassifier function, it is understood as the Series 135 19.0 as shown in Out [3] line 2, n_neighbors = 135 19.0. My KNeighborsClassifier was poorly executed, which led to the .fit method of the KNeighborsClassifier not working properly. In [1]: opt_neighbors = Opt_report['Optimal_Neighbors'] Out [1]: 135 19.0 Name: Optimal_Neighbors, dtype: float64 In [2]: type(opt_neighbors) Out [2]: pandas.core.series.Series In [3]: knn = KNeighborsClassifier(n_neighbors=opt_neighbors,weights='distance',metric='hamming') knn Out [3]: KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='hamming', metric_params=None, n_jobs=1, n_neighbors=135 19.0 Name: Optimal_Neighbors, dtype: float64,p=2, weights='distance') Updating the code as shown below fixes this problem. In [4]: opt_neighbors = int(Opt_report['Optimal_Neighbors']) Out [4]: 19
upvote count: 1
answers question: http://stackoverflow.com/q/48098537
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/48068230
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 2
tagged with: selenium
type: Question
has answer: http://stackoverflow.com/a/48068363
tagged with: oop
has title: Adding time delay to selenium
score: 2
answer count: 1
downvote count: 0
has body: I want to wrap webdriver to cause it to wait after every operation. I have the following function, which I thought might work (I'm testing with the print function): def sleep_driver(function): def wrapper(*args, **kwargs): print("sleeping") return function(*args, **kwargs) return wrapper However when I run: from selenium import webdriver as wd webdriver = sleep_driver(wd) options = webdriver.ChromeOptions() I get: File "myfile.py", line 204, in &lt;module&gt; options = webdriver.ChromeOptions() AttributeError: 'function' object has no attribute 'ChromeOptions' What am I doing wrong?
linked to: http://stackoverflow.com/q/8951787
accepted answer: http://stackoverflow.com/a/48068363

http://stackoverflow.com/q/48097973
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/48117726
has comment: http://stackoverflow.com/comment/83171017
has comment: http://stackoverflow.com/comment/83171055
has comment: http://stackoverflow.com/comment/83171457
upvote count: 1
has body: I'm translating an algorithm from R to C, I need to obtain the pseudoinverse of a matrix but the result I get in C has some differences with the one I get in R. These differences change the behaviour of the algorithm. The code I used to get the pseudoinverse in C is this. I did some reading and there are different ways to get the pseudoinverse, the method used in C is Moore-Penrose. The function used in R is from the library corpcor. Both use "Singular Value Decomposition". This is the matrix from which I want to get the pseudoinverse 1 0.920980394593472 0.996160973582776 0.996772980609752 0.997372221594439 0.999972797627027 0.920980394593472 1 0.885601439824631 0.88878682654952 0.892173764646865 0.923738536637407 0.996160973582776 0.885601439824631 1 0.999973383442349 0.999885329646229 0.99549326808266 0.996772980609752 0.88878682654952 0.999973383442349 1 0.999969202115456 0.996158288591094 0.997372221594439 0.892173764646865 0.999885329646229 0.999969202115456 1 0.996814694067663 0.999972797627027 0.923738536637407 0.99549326808266 0.996158288591094 0.996814694067663 1 The results I get from the function pseudoinverse() in R is: 1398676681.0709 79599.9582612864 -9585774352.21759 28302547195.6681 -19807136596.5434 -305910496.668656 79591.4731051894 3401.1232804516 52529359.4133139 -126479191.665267 76425077.4778451 -2563699.8428373 -9585920775.52777 52529288.3510008 1003916837759.99 -2454016116733.34 1501977763514.61 -42460326831.3218 28302900052.1238 -126478989.043282 -2454015575342.32 6017016899314.95 -3692050079960.62 101159202486.608 -19807349974.7679 76424938.7106429 1501977155911.81 -3692049404688.94 2270196092100.53 -60571139669.4392 -305903527.744471 -2563701.10409161 -42460406960.0488 101159421351.019 -60571285357.0572 2184863920.31107 The result I get in C is: 1398795243.74255 79184.33844201 -9594022229.12525 28322858223.2099 -19819644215.1338 -305583186.690388 79166.91917247 3402.48426033 52556628.829717 -126546466.939768 76466567.769084 -2564764.387753…
has comment: http://stackoverflow.com/comment/83171942
has comment: http://stackoverflow.com/comment/83202478
answer count: 1
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/83172174
has comment: http://stackoverflow.com/comment/83172844
has answer: http://stackoverflow.com/a/48117726
has comment: http://stackoverflow.com/comment/83171413
tagged with: numpy
has comment: http://stackoverflow.com/comment/83173078
type: AnsweredQuestion
downvote count: 0
score: 1
has title: Pseudoinverse different results in R, C and Python

http://stackoverflow.com/comment/123180190
has text: OP is asking for the console solution, not command line
comment on: http://stackoverflow.com/a/48170476
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48133520
type: Question
upvote count: 1
has body: I have been trying to make multiple buttons according to the number of files in a directory. And when each button pressed it should start to launch a different video file. I have for samples so far i can create 4 buttons but when i pressed it always triggers the last buttons on_release function. I have tried the make an array of buttons and they would have different instances but didn't succeed. Tried to get the id of the buttons but when i tried returning widget.id in a different function it returned the all the 4 buttons id's. Is there any clear way to handle this kind of stuff. I would prefer to work with kivy file but i couldn't figure it out how to create buttons in a for loop. I can share the full code and kivy files also but it would be so messy. Let me know if you need more info. Thanks in advance. def createMultipleButton(self, dt): root = Widget() size_y=150; size_x=150; for i in range(1): folderList = os.listdir(picture_path) if len(folderList)==0: time.sleep(1) break fileList = os.listdir(picture_path) print fileList for file in fileList: x = (picture_path+"/"+file) button = Button(id=str(file),text="" + str(file),size_hint=(None, None),height=size_y,width=size_x, pos_hint={'x': 0, 'y': 1},background_normal=x) button.bind(on_release=lambda btn:self.VideoContainer(str(file)) print file self.scrollview.content_layout.add_widget(button) def VideoContainer(self,name): mylist=name.split('.') video = VideoPlayer(source="/home/linux/kivyFiles/kivyLogin/videoAssets/"+mylist[0]+".mp4", play=True) video.allow_stretch=True video.size=(500,500) video.pos=(400,400) self.add_widget(video)
answer count: 1
tagged with: button
has title: Kivy- different attributes for for loop generated buttons
favorite count: 0
tagged with: kivy
tagged with: kivy-language
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48136967
score: 1
accepted answer: http://stackoverflow.com/a/48136967

http://stackoverflow.com/comment/83172539
type: Comment
has text: Are the numbers unique?
type: QuestionComment
comment on: http://stackoverflow.com/q/48098250
score: 0

http://stackoverflow.com/a/48136768
has comment: http://stackoverflow.com/comment/83911154
accepted answer of: http://stackoverflow.com/q/48065567
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48065567
has body: One way you can do it is in the spirit of this SO answer which uses proxies for each member of a LineCollection in the legend. You can get the LineCollection by using the step-by-step graph drawing functions, drawing the nodes and edges separately (e.g. draw_networkx_nodes doc.) import matplotlib.pyplot as plt import networkx as nx from matplotlib.lines import Line2D # make a test graph n = 7 # nodes m = 5 # edges G = nx.gnm_random_graph(n, m) # and define some color strings (you'll get this array from the dataframe) _c = 'rgbcmky' * m # way too many colors, trim after clrs = [c for c in _c[:m]] plt.ion() plt.figure(figsize = (9, 7), num=1); plt.clf() # draw the graph in several steps pos = nx.spring_layout(G) h1 = nx.draw_networkx_nodes(G, pos=pos, node_color = 'black', alpha = 0.9, node_size = 300, linewidths=6) # we need the LineCollection of the edges to produce the legend (h2) h2 = nx.draw_networkx_edges(G, pos=pos, width=6, edge_color=clrs) # and just show the node labels to check the labels are right! h3 = nx.draw_networkx_labels(G, pos=pos, font_size=20, font_color='c') #https://stackoverflow.com/questions/19877666/add-legends-to-linecollection-plot - uses plotted data to define the color but here we already have colors defined, so just need a Line2D object. def make_proxy(clr, mappable, **kwargs): return Line2D([0, 1], [0, 1], color=clr, **kwargs) # generate proxies with the above function proxies = [make_proxy(clr, h2, lw=5) for clr in clrs] # and some text for the legend -- you should use something from df. labels = ["{}-&gt;{}".format(fr, to) for (fr, to) in G.edges()] plt.legend(proxies, labels) plt.show() This produces something like:
score: 8
upvote count: 8
type: Answer

http://stackoverflow.com/comment/83216824
type: QuestionComment
type: Comment
has text: `[(1, 's'), (2, 'e'), (2, 's'), (2, 'e')]`?
comment on: http://stackoverflow.com/q/48120106
score: 0

http://stackoverflow.com/comment/83250432
type: Comment
comment on: http://stackoverflow.com/a/48136506
score: 0
type: AnswerComment
has text: Great! Let me know if you have other questions. Also, please mark answers as accepted if they answer your question.

http://stackoverflow.com/comment/83135305
has text: @Prune yes, i can pwd as myself on shell and python script is running as myself
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48067735
type: QuestionComment

http://stackoverflow.com/a/48102958
has comment: http://stackoverflow.com/comment/83181878
score: 1
has body: It's a messy solution but you could use unittest.mock something like import unittest.mock with mock.patch('pdb.set_trace') as mock: #run tests
answers question: http://stackoverflow.com/q/48102831
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/a/48138599
upvote count: 91
has comment: http://stackoverflow.com/comment/137393416
has body: We will start with an example in the documentation. &gt;&gt;&gt; np.unravel_index([22, 41, 37], (7,6)) (array([3, 6, 6]), array([4, 5, 1])) First, (7,6) specifies the dimension of target array that we want to turn the indices back into. Second, [22, 41, 37] are some indices on this array if the array is flattened. If a 7 by 6 array is flattened, its indices will look like [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, *22*, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, *37*, 38, 39, 40, *41*] If we unflatten these indices back to their original positions in a dim (7, 6) array, it would be [[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, *22*, 23], &lt;- (3, 4) [24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35], [36, *37*, 38, 39, 40, *41*]] (6, 1) (6,5) The return values of the unravel_index function tell you what should have been the indices of [22, 41, 37] if the array is not flattened. These indices should have been [(3, 4), (6, 5), (6,1)] if the array is not flattened. In other words, the function transfers the indices in a flatten array back to its unflatten version. https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.unravel_index.html
downvote count: 0
score: 91
type: Answer
has comment: http://stackoverflow.com/comment/116212081
answers question: http://stackoverflow.com/q/48135736

http://stackoverflow.com/a/48122082
answers question: http://stackoverflow.com/q/48121487
score: 2
downvote count: 0
has body: The startup time depends on the device and can be much faster than that on some newer ones, but the general issue is fundamental to the way python-for-android currently works. That said, the first run of the app will take longer (sometimes several seconds longer) due to unpacking some files. This is only done once, so subsequent starts are faster. The time taken for this again depends on the device, and in particular depends on the speed of the filesystem. Regarding buildozer vs python-for-android, buildozer is a wrapper to python-for-android that handles some dependencies which aren't managed by python-for-android itself. Buildozer also allows building for ios using the same unified config.
type: Answer
upvote count: 2

http://stackoverflow.com/a/48098405
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48083857
type: Answer
score: 1
upvote count: 1
has body: I have the solution. https://github.com/alexdu/piggyphoto/issues/2 s=self.cam.capture_preview() s.save('/tmp/preview.jpg') s.clean()
accepted answer of: http://stackoverflow.com/q/48083857

http://stackoverflow.com/q/48088461
type: UnansweredQuestion
score: 1
favorite count: 0
has body: I have trained the model using 4 CPU machines.For restoring it do I need to save the model on every machine? And how do I get the saved state from each CPU on the chief node so that it can be restored? Currently, if I try to restore the model error I am facing is tensorflow.python.framework.errors_impl.NotFoundError: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ./newsvr.ckpt
type: Question
tagged with: machine-learning
tagged with: python
has title: How to restore a model in distributed tensorflow?
upvote count: 1
tagged with: tensorflow
tagged with: distributed
answer count: 0
downvote count: 0

http://stackoverflow.com/q/48031622
has title: dtype of ndarray containing string in python
upvote count: 1
type: Question
tagged with: numpy
answer count: 1
tagged with: arrays
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48031981
tagged with: python
type: UnansweredQuestion
score: 1
has body: I know that in case of ndarray containing strings, dtype returned will be of the form dtype(S#) where # denotes the length of the string. As shown in figure the array 'a' which is generated from a list [1,'2','3']. Once the array is created all the elements become string type. Array 'b' is created from a list ['1',2,'3']. a.dtype gives S21 while b.dtype gives S1. Length of elements in both a and b is 1. Why the length of elements in first array is taken as 21 even though all the elements have length 1? It is found that dtype will continue to be 'S21' even if 1 is replaced with 9223372036854775807. Once we use 9223372036854775808, dtype becomes 'S20'. How does this happen Somebody please explain

http://stackoverflow.com/comment/83146293
type: Comment
type: QuestionComment
has text: I really hope this is for some homework thing, because storing passwords like that is a very, very, VERY bad idea
comment on: http://stackoverflow.com/q/48085644
score: 2

http://stackoverflow.com/q/48030937
type: UnansweredQuestion
tagged with: python
has title: Marking points that are above limit with marker at ylimit (matplotlib plot_date)
tagged with: plot
answer count: 0
has comment: http://stackoverflow.com/comment/83032561
has body: I'm making a graph that gets redrawn every minute with all of the measurements so far during the night. I'm plotting by an amount of loss of magnitude so the y axis is plotted reverse, with zero at top and whatever you want at the bottom. Occasionally we'll get points larger than my bottom ylim of 1.4 while it's not really important that they're larger (because looking for detail between limits), it is important to mark that there was a measurement taken and that it was off of the scale. Is there an easy way in matplot lib that takes points beyond the ylimit and just points them at/on the ylimit line? What suggestions might you have? ax.set_ylim(bottom=1.4,top=0,emit=True,auto=False) ax.plot_date(x, y, 'black', marker='o', fillstyle='full', ms=7 , ls='none', zorder=10) Thanks for the help!
type: Question
tagged with: matplotlib
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83032725
favorite count: 0
upvote count: 2

parameter-passing
tags question: http://stackoverflow.com/q/48032488
tags question: http://stackoverflow.com/q/48080264
tags question: http://stackoverflow.com/q/48026545
tag name: parameter-passing
type: Tag

http://stackoverflow.com/comment/83092865
has text: In addition to "Adityapur", "no" is also duplicated, so is "2". Should each of these duplicates also be removed? If not how do you differentiate between them? Also, which instance of the duplicate should be removed? Finally, what if there is more than 2 instances of the same word?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48059420

http://stackoverflow.com/a/48062047
type: Answer
has comment: http://stackoverflow.com/comment/83097947
has comment: http://stackoverflow.com/comment/83097874
has body: To automate the downloading of a PDF file to a specified folder you can use the following code block : newpath = "PATH_TO_FOLDER_WITHIN_DIRECTORY" if not os.path.exists(newpath): os.makedirs(newpath) profile = webdriver.FirefoxProfile("/Users/USERNAME/Library/Application Support/Firefox/Profiles/NAME") profile.set_preference("browser.download.dir",newpath); profile.set_preference("browser.download.folderList",2); profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain,application/octet-stream,application/pdf,application/x-pdf,application/vnd.pdf"); profile.set_preference("browser.download.manager.showWhenStarting",False); profile.set_preference("browser.helperApps.neverAsk.openFile","text/plain,application/octet-stream,application/pdf,application/x-pdf,application/vnd.pdf"); profile.set_preference("browser.helperApps.alwaysAsk.force", False); profile.set_preference("browser.download.manager.useWindow", False); profile.set_preference("browser.download.manager.focusWhenStarting", False); profile.set_preference("browser.helperApps.neverAsk.openFile", ""); profile.set_preference("browser.download.manager.alertOnEXEOpen", False); profile.set_preference("browser.download.manager.showAlertOnComplete", False); profile.set_preference("browser.download.manager.closeWhenDone", True); profile.set_preference("pdfjs.disabled", True); browser = webdriver.Firefox(profile) browser.get('Provide_URL_here')
has comment: http://stackoverflow.com/comment/83097611
score: 0
has comment: http://stackoverflow.com/comment/83101062
has comment: http://stackoverflow.com/comment/83097678
has comment: http://stackoverflow.com/comment/83097898
answers question: http://stackoverflow.com/q/48061088
has comment: http://stackoverflow.com/comment/83116697

http://stackoverflow.com/a/48164079
has body: I installed an older build. It doesn't cause this error. http://ci.tensorflow.org/view/Nightly/job/nightly-pi/78/artifact/output-artifacts/tensorflow-1.3.0-cp27-none-any.whl
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48135310

http://stackoverflow.com/comment/83322640
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48167216
type: QuestionComment
has text: @BenjaminW. It gulps the first part ("field") of the command in affected lines (probably parsing its as group).

http://stackoverflow.com/comment/112538887
type: Comment
has text: `map` is *not* a generator, but it is an iterator.
comment on: http://stackoverflow.com/a/48080400
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83100991
has text: @EdwinVanMierlo because it is clunky and inelegant. It's using a trick that won't be obvious if I read this a month later. It is long, and hard to read, IMO
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/48063922
type: Comment

http://stackoverflow.com/q/48043799
score: 2
type: AnsweredQuestion
type: Question
has title: python3 sched: schedule events after run()
downvote count: 0
answer count: 2
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48068720
upvote count: 2
possible better answer: http://stackoverflow.com/a/64250589
has body: When scheduling events using scheduler.enter after calling scheduler.run these events are fired not until at least one event that was entered before running the scheduler was fired. Is this intended? import sched import threading import time now = time.time() scheduler = sched.scheduler(time.time, time.sleep) def fire(name): print('EVENT:', name, time.time() - now) def start(): t = threading.Thread(target=scheduler.run) t.start() ################################### # when scheduling all before start() everything works as expected. # scheduler.enter(4, 1, fire, ('D',)) # scheduler.enter(3, 1, fire, ('C',)) # scheduler.enter(2, 1, fire, ('B',)) # scheduler.enter(1, 1, fire, ('A',)) # start() # # EVENT: A 1.0 # EVENT: B 2.0 # EVENT: C 3.0 # EVENT: D 4.0 ################################### # here I'd expect event 'A' to fire after one second. But it is # not fired until at least one of the events scheduled before run() # is fired. # scheduler.enter(2, 1, fire, ('B',)) # scheduler.enter(4, 1, fire, ('D',)) # start() # scheduler.enter(1, 1, fire, ('A',)) # scheduler.enter(3, 1, fire, ('C',)) # # EVENT: A 2.005021572113037 # EVENT: B 2.005021572113037 # EVENT: C 3.0050315856933594 # EVENT: D 4.0050413608551025 ################################### # starting before any event is scheduled is not possible, # because run() returns directly. # # start() # scheduler.enter(3, 1, fire, ('C',)) # scheduler.enter(2, 1, fire, ('B',)) # scheduler.enter(1, 1, fire, ('A',)) # # -- no events fired.
tagged with: python
has answer: http://stackoverflow.com/a/64250589
accepted answer: http://stackoverflow.com/a/48068720

http://stackoverflow.com/comment/83307249
score: 0
has text: this is simple iteration over elements, you can't make it faster. it might seem slow because of IO overhead
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48163837

http://stackoverflow.com/a/53276825
score: 7
upvote count: 8
answers question: http://stackoverflow.com/q/48067514
downvote count: 1
has body: If someone works on Turkish data, then I suggest this line: df = pd.read_csv("text.txt",encoding='windows-1254')
type: Answer

http://stackoverflow.com/comment/83146065
type: QuestionComment
comment on: http://stackoverflow.com/q/48085512
has text: it looks like what you want to do is remove a list element. What elements did you mean you want to "join?"
score: 0
type: Comment

http://stackoverflow.com/q/48112022
has comment: http://stackoverflow.com/comment/83199768
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/83199653
has title: How to return multiple values in Python map?
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48112146
score: 4
has body: I have a list of dicts: &gt;&gt;&gt; adict = {'name': 'John Doe', 'age': 18} &gt;&gt;&gt; bdict = {'name': 'Jane Doe', 'age': 20} &gt;&gt;&gt; l = [] &gt;&gt;&gt; l.append(adict) &gt;&gt;&gt; l.append(bdict) &gt;&gt;&gt; l [{'age': 18, 'name': 'John Doe'}, {'age': 20, 'name': 'Jane Doe'}] Now I want to split up the values of each dict per key. Currently, this is how I do that: &gt;&gt;&gt; for i in l: ... name_vals.append(i['name']) ... age_vals.append(i['age']) ... &gt;&gt;&gt; name_vals ['John Doe', 'Jane Doe'] &gt;&gt;&gt; age_vals [18, 20] Is it possible to achieve this via map? So that I don't have to call map multiple times, but just once? name_vals, age_vals = map(lambda ....)
tagged with: functional-programming
has answer: http://stackoverflow.com/a/48112201
favorite count: 0
possible better answer: http://stackoverflow.com/a/48112201
accepted answer: http://stackoverflow.com/a/48112146
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/83088487
type: Comment
type: QuestionComment
has text: Without any code or clues as to what you are actually doing it's impossible to answer this question. Normally I'd mark it as "close to to lack of code"
score: 0
comment on: http://stackoverflow.com/q/48040994

http://stackoverflow.com/comment/83151849
comment on: http://stackoverflow.com/a/48049201
has text: @Jan Done the same. Much thanks for your valuable insight, and your guidance regarding regex. I will start soon. Will also learn about dictionary comprehension.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83289886
has text: That's not exactly what [mcve] means.
comment on: http://stackoverflow.com/q/48155246
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83048084
score: 0
comment on: http://stackoverflow.com/a/48038764
type: Comment
has text: @PaulThomas Theoretically, it should be possible to use the objective function as an inequality constraint. But when I tried this it failed to find a solution. Sometimes a better initial guess can help. Would you be able to provide one that has at least a nonnegative function value?
type: AnswerComment

http://stackoverflow.com/comment/83207115
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48112466
has text: I don't know... list?
score: 0

tcp
tags question: http://stackoverflow.com/q/48121620
type: Tag
tags question: http://stackoverflow.com/q/48024720
tags question: http://stackoverflow.com/q/48089780
tags question: http://stackoverflow.com/q/48126560
tags question: http://stackoverflow.com/q/48083138
tags question: http://stackoverflow.com/q/48121053
tags question: http://stackoverflow.com/q/48082439
tag name: tcp

http://stackoverflow.com/q/48140425
has comment: http://stackoverflow.com/comment/83258568
answer count: 1
has answer: http://stackoverflow.com/a/48140434
accepted answer: http://stackoverflow.com/a/48140434
tagged with: python
has title: python if else not working after refactoring
type: AnsweredQuestion
has body: def binary(val): return str(val) if val&lt;=1 else binary(val&gt;&gt;1) + str(val&amp;1) how can I rewrite this code i Have tried: if (val&lt;=1) : return str(val) else binary(val&gt;&gt;1) + str(val) but it does not work
duplicate of: http://stackoverflow.com/q/17778372
type: Question
linked to: http://stackoverflow.com/q/17778372
score: 0

http://stackoverflow.com/q/48045438
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/83062121
type: UnansweredQuestion
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83062180
has comment: http://stackoverflow.com/comment/83062085
has body: So I have object instances in the model and I would like to allow users to filter through them based on certain characteristics. I setup a form and added some code to handle it in the view. When the form is submitted it returns the same template but with the object filters they set. However it is not working... I was wondering why/how I should go about doing this. From: class PropertySearchForm(forms.Form): beds = forms.CharField(widget=forms.Select(attrs={'class':'form-control mb-3'}, choices=BED_CHOICES)) baths = forms.CharField(widget=forms.Select(attrs={'class':'form-control mb-3'}, choices=BATH_CHOICES)) View: def UniversityHomePageView(request,name_initials): university = get_object_or_404(University,name_initials=name_initials) listings = Listing.objects.filter(l_university=university) form = PropertySearchForm(request.GET or None) company = Company.objects.filter(c_university=university) context = { 'listings':listings, 'university':university, 'company':company, 'form':form, } if form.is_valid(): beds = int(form.cleaned_data.get('beds')) baths = int(form.cleaned_data.get('baths')) listings = Listing.objects.filter(l_university=university,beds=beds,baths=baths) return render(request,'listings/university_homepage.html',context) return render(request,'listings/university_homepage.html',context)
has comment: http://stackoverflow.com/comment/83062296
upvote count: 2
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83063441
has comment: http://stackoverflow.com/comment/83062761
has comment: http://stackoverflow.com/comment/83062053
has title: Django letting user filter objects with form
has comment: http://stackoverflow.com/comment/83062735

http://stackoverflow.com/comment/83106959
type: AnswerComment
score: 0
has text: Right , the pow() function is being called in the second area variable in the else: statement. " area = 3.14*(radius**2)" I ma being hacked so my internets slow.Also mind hacked by DOD/CIA as described in "Project Soul Catcher" by Robert Duncan. Here is a the pow() documentation. https://docs.python.org/2/library/functions.html#pow It says there that it is the equivalent of using **
type: Comment
comment on: http://stackoverflow.com/a/48046710

http://stackoverflow.com/comment/83028186
type: Comment
comment on: http://stackoverflow.com/a/48028535
has text: Finally someone who explains it well XD I thank you very much for your help, but above all for your enormous patience.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83223445
type: Comment
comment on: http://stackoverflow.com/a/48122691
has text: You don't need to multiply or divide at all. `round` takes two arguments, where the second is the number of digits to round to, so you could just do `b = round(a, 1)`, which directly rounds to a single digit after the decimal in a single step.
score: 2
type: AnswerComment

http://stackoverflow.com/comment/83260276
comment on: http://stackoverflow.com/a/48140472
score: 3
has text: 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.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83140595
comment on: http://stackoverflow.com/a/48082117
score: 1
has text: Good thinking on the padding. You could do `padded = numpy.pad(data, 1, 'edge')` in place of your concatenation
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48148123
has answer: http://stackoverflow.com/a/48152534
tagged with: python
has body: I am building a Kivy application which will serve as a SmartMirror. The mirror is supposed to go into the main menu, which I already programmed, if a certain event fired, otherwise the screen should remain black. This means on that event I need to load all the body.kv file and after a certain timeout the body should be unloaded. Builder.load_file('smartmirror.kv') Builder.load_file('headerspace.kv') Builder.load_file('bodyspace.kv') Builder.load_file('footerspace.kv') if __name__ == '__main__': app = SmartMirrorApp() app.run() How do I do this the best way?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48152534
type: Question
score: 0
answer count: 1
tagged with: kivy
has title: Python Kivy conditional Layout

http://stackoverflow.com/q/48074091
linked to: http://stackoverflow.com/q/11585377
has comment: http://stackoverflow.com/comment/83121816
has comment: http://stackoverflow.com/comment/83123800
upvote count: 1
has comment: http://stackoverflow.com/comment/83123601
has comment: http://stackoverflow.com/comment/83123770
type: AnsweredQuestion
score: 1
has body: I have create an ec2 instance which has default python 2.7 installed. I have installed python 3.5.1 and I can see both directories /usr/bin/python3 and /usr/bin/python . I have created a virtualenv using virtualenv -p python3 .env . But when I execute pip install -r requirements.txt for python3, it displays this error message. Failed to establish a new connection: [Errno 101] Network is unreachable',)' How can I fix it? Also, if I execute : sudo python3 -m pip install Flask I get - /usr/bin/python3: No module named pip
has answer: http://stackoverflow.com/a/48075155
type: Question
downvote count: 0
tagged with: amazon-ec2
has comment: http://stackoverflow.com/comment/83123581
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/83121886
accepted answer: http://stackoverflow.com/a/48075155
answer count: 1
has title: pip install in ec2 : Failed to establish a new connection: [Errno 101] Network is unreachable',)
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83123534

http://stackoverflow.com/comment/83098273
has text: Thanks for the answer. Your solution works but I can select only one accepted answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48062705
type: Comment

http://stackoverflow.com/q/48027527
linked to: http://stackoverflow.com/q/10235956
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48027566
tagged with: django-views
has answer: http://stackoverflow.com/a/76591258
downvote count: 0
has answer: http://stackoverflow.com/a/48027566
score: 7
has answer: http://stackoverflow.com/a/48028119
accepted answer: http://stackoverflow.com/a/48028119
type: Question
has body: I'm building an application in Django which allows the end-user to retrieve information which is sensitive to the time of day (12 am to 12 am) on a given day. I store this information in my database as an integer representing the seconds since midnight in 30-minute increments. I was looking at Django's timezone documentation: https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/ and found myself confused on whether or Django automatically uses the end-users time, or if I must collect this information and account for it in my views. Any information would be helpful! Thanks.
answer count: 3
upvote count: 7
favorite count: 0
has title: Does Django automatically detect the end user's timezone?
tagged with: timezone
tagged with: datetime
tagged with: django
tagged with: python

http://stackoverflow.com/q/48056360
score: 0
has comment: http://stackoverflow.com/comment/83085101
has comment: http://stackoverflow.com/comment/83085509
has comment: http://stackoverflow.com/comment/83085629
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83085375
has comment: http://stackoverflow.com/comment/83085310
has comment: http://stackoverflow.com/comment/83085363
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83085789
has comment: http://stackoverflow.com/comment/83085270
type: Question
has answer: http://stackoverflow.com/a/48056788
has body: I'm trying to create a python script to extract some informations from a webmail. I wanna follow a redirection. My code : br1 = mechanize.Browser() br1.set_handle_robots(False) br1.set_cookiejar(cj) br1.open("LOGIN URL") br1.select_form(nr=0) br1.form['username'] = mail_site br1.form['password'] = pw_site res1 = br1.submit() html = res1.read() print html Result is not what i expect. It contains only a redirection script. I've seen that i have to extract the information from this script to follow this redirection. So, in my case,i've to extract jsessionid into a script. The script is : &lt;script&gt; function redir(){ window.self.location.replace('/webmail/en_EN/continue.html;jsessionid=1D5QS4DA6C148DC4C14QS4CS5.1FDS5F4DSV1A64DA5DA?MESSAGE=NO_COOKIE&amp;DT=1&amp;URL_VALID=welcome.html'); return true; } &lt;/script&gt; If i'm not wrong, i've to build one regex. I've tried many things but no results. Anyone have an idea ?
answer count: 1
has comment: http://stackoverflow.com/comment/83085676
has title: Extract string from - BeautifulSoup python
has comment: http://stackoverflow.com/comment/83085571
tagged with: beautifulsoup

http://stackoverflow.com/q/48053283
has body: I'm using Python 3.5.4 with Django 2.0.0 final 0. I'm trying create a Django blog web application. I received error after I had created Django view and template. Here's my error: Internal Server Error: /blog Traceback (most recent call last): File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_request(request) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/middleware/common.py", line 60, in process_request if self.should_redirect_with_slash(request): File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/middleware/common.py", line 79, in should_redirect_with_slash is_valid_path('%s/' % request.path_info, urlconf) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/base.py", line 155, in is_valid_path resolve(path, urlconf) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/base.py", line 24, in resolve return get_resolver(urlconf).resolve(path) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 496, in resolve sub_match = pattern.resolve(new_path) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 496, in resolve sub_match = pattern.resolve(new_path) File "/home/pecan/PycharmProjects/autisticstory/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 345, in resolve kwargs.update(self.default_args) ValueError: dictionary update sequence element #0 has length 1; 2 is required [01/Jan/2018 21:12:43] "GET /blog HTTP/1.1" 500 88570 Here's autisticstory/urls.py file: """autisticstory URL Configuration The `urlpattern…
accepted answer: http://stackoverflow.com/a/50163657
type: AnsweredQuestion
has title: Dictionary update sequence element #0 has length 1; 2 is required in Django
has comment: http://stackoverflow.com/comment/83080828
type: Question
tagged with: django
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/83080761
score: 0
has answer: http://stackoverflow.com/a/50163657

http://stackoverflow.com/comment/83004629
type: QuestionComment
comment on: http://stackoverflow.com/q/48017570
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162139/discussion-between-whoisearth-and-exprator).
score: 0
type: Comment

http://stackoverflow.com/comment/83164881
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ **This question was marked as an exact duplicate of an existing question.** -- This question is more about traversing the dictionary. Use a TRIE would have been more appropriate as a comment. It's in no way an exact duplicate. Could you explain why you think otherwise?
score: 1
comment on: http://stackoverflow.com/q/48094990
type: Comment

http://stackoverflow.com/q/48170550
upvote count: 1
downvote count: 0
has body: Im trying to create more platforms, I was wondering whats the correct approach to do this whether to create a for loop or add more stuff to the code like change the numbers in the Platform bracket, also when this code is played the platforms arent seperate how would i go about separating them? so that you see the platforms individually and in random positions something like this https://forums.crackberry.com/blackberry-10-games-f275/fall-down-game-906376/ import pygame pygame.init() clock = pygame.time.Clock() FPS = 60 DS = pygame.display.set_mode((800, 600)) sprite_image = pygame.Surface((50, 50), pygame.SRCALPHA) pygame.draw.circle(sprite_image, (90, 100, 200), [25, 25], 25) W, H = DS.get_size() class Platform(pygame.sprite.Sprite): def __init__(self, x, y, w, h): super(Platform, self).__init__() self.image = pygame.Surface((w, h)) self.image.fill((90, 90, 120)) self.rect = self.image.get_rect(topleft=(x, y)) class Sprite(pygame.sprite.Sprite): def __init__(self, pos): super(Sprite, self).__init__() self.image = sprite_image self.rect = self.image.get_rect() self.rect.center = pos self._vx = 0 self._vy = 0 self._spritex = pos[0] self._spritey = pos[1] self.level = None self._gravity = .9 def update(self): # Adjust the x-position. self._spritex += self._vx self.rect.centerx = self._spritex # And update the rect. block_hit_list = pygame.sprite.spritecollide(self, self.level, False) for block in block_hit_list: if self._vx &gt; 0: self.rect.right = block.rect.left elif self._vx &lt; 0: # Otherwise if we are moving left, do the opposite. self.rect.left = block.rect.right self._spritex = self.rect.centerx # Update the position. # Adjust the y-position. self._vy += self._gravity # Accelerate downwards. self._spritey += self._vy self.rect.centery = self._spritey # And update the rect. # Check and see if we hit anything block_hit_list = pygame.sprite.spritecollide(self, self.level, False) for block in block_hit_list: # Reset our position based on the top/bottom of the obj…
favorite count: 0
has answer: http://stackoverflow.com/a/48171173
has title: creating separate and random platforms in pygame
answer count: 1
tagged with: python
tagged with: pygame
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/48171173
type: Question

logging
tags question: http://stackoverflow.com/q/48095578
tags question: http://stackoverflow.com/q/48128075
tags question: http://stackoverflow.com/q/48165133
tag name: logging
tags question: http://stackoverflow.com/q/48045978
tags question: http://stackoverflow.com/q/48162445
tags question: http://stackoverflow.com/q/48170682
tags question: http://stackoverflow.com/q/48091757
tags question: http://stackoverflow.com/q/48030354
tags question: http://stackoverflow.com/q/48124916
tags question: http://stackoverflow.com/q/48078051
tags question: http://stackoverflow.com/q/48146822
tags question: http://stackoverflow.com/q/48149386
type: Tag

http://stackoverflow.com/comment/83279897
has text: Which python API and version do you use ? You use `ElasticSearch` with capital 'S' so I assume it is not the low level python lib : https://github.com/elastic/elasticsearch-py
comment on: http://stackoverflow.com/q/48139986
score: 0
type: Comment
type: QuestionComment

celery
tags question: http://stackoverflow.com/q/48098829
tags question: http://stackoverflow.com/q/48076703
tag name: celery
tags question: http://stackoverflow.com/q/48160247
tags question: http://stackoverflow.com/q/48040691
type: Tag
tags question: http://stackoverflow.com/q/48151647
tags question: http://stackoverflow.com/q/48080315
tags question: http://stackoverflow.com/q/48141439

http://stackoverflow.com/q/48028586
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/83027216
has title: How to install Pillow on Python 3.6.4 (Windows)
has comment: http://stackoverflow.com/comment/83027251
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/50617827
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1
has body: I am looking to do some coding on my laptop, practicing and trying to teach my self new things that I can add when I came across adding pictures. This requires Pillow, but I have no idea on where to start to download it. Please can someone help by telling me how to download and install Pillow on Windows?
type: Question
linked to: http://stackoverflow.com/q/20596204

http://stackoverflow.com/a/48159600
answers question: http://stackoverflow.com/q/48159371
score: 2
has body: There are many ways to do tests, often it depends on what framework you use. But, just assuming that you want some form of a formal test framework, you can use pytest. Step 1, install pytest $ pip install pytest Step 2, Format your code. You will test your output according to the return of the function. def host_is_pingable(x): #Do your verification logic here... putting the result in a string valid return valid Step 3, Now write the tests def test_answer(): assert host_is_pingable(ip_address) != "some error" Step 4, run the tests $ py.test This is not a unittest, but a boilerplate test framework. If you want to do unittests, there is a great guide to it here: http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html Update 2019 The unittest introductory guide link is now dead but you can find it archived at WayBackMachine here https://web.archive.org/web/20180121231649/http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48159371
type: Answer

http://stackoverflow.com/q/48152343
has answer: http://stackoverflow.com/a/48152386
tagged with: python
has comment: http://stackoverflow.com/comment/83283156
has body: I'm new to python and can't figure out why my code is throwing out this error. I'm trying to use c to compare the two lists. def playPowerball(): powerball = [] choices = [] c = [] while len(powerball) &lt; 6: number = random.randint(1,64) if number not in powerball: powerball.append(number) while len(choices) &lt; 6: pick = int(raw_input('Pick a number between 1 and 64: ')) if pick not in choices: choices.append(pick) for i in powerball: for i in choices: c += 1 print ('You have',c,'correct',powerball,choices) Error: U:\Python\Lottery Ticket.py in playPowerball() 15 choices.append(pick) 16 for i in powerball: ---&gt; 17 if i in choices: 18 c += 1 19 print ('You have',c,'correct',powerball,choices) TypeError: argument of type 'int' is not iterable Edit: I did mean choices instead of pick, yet the code still doesn't work. Edit 2: Thank you, sKwa, that solved my issue!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83283079
upvote count: 2
has comment: http://stackoverflow.com/comment/83283112
has title: TypeError: 'int' object is not iterable (new to python)
downvote count: 7
accepted answer: http://stackoverflow.com/a/48152386
has comment: http://stackoverflow.com/comment/83283202
type: Question
possible better answer: http://stackoverflow.com/a/48152390
score: -5
has answer: http://stackoverflow.com/a/48152390
linked to: http://stackoverflow.com/q/14941288
answer count: 2
has comment: http://stackoverflow.com/comment/83283107
favorite count: 0

http://stackoverflow.com/comment/83282476
type: Comment
score: 2
comment on: http://stackoverflow.com/q/48151844
type: QuestionComment
has text: OK. I get it now. Looks more like a bug that needs to be reported to atom creators. I do not see it addressed on github.

http://stackoverflow.com/comment/83068611
comment on: http://stackoverflow.com/a/48045257
score: 0
type: AnswerComment
type: Comment
has text: yes! If i compute only one point ,it will be fine! but this is my essay work, i got to figure out it, now i use arcmap tool like point distance and near, it will take lots of time,but won't get memoryerror, maybe when i get up ,it will be ok! anyway, thanks !

http://stackoverflow.com/a/48112774
has body: i don't know what app you are making but lets say i want to save the username as session. 1. we need to create a script that create a random code and assign it to and hidden input function makeid() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i &lt; 5; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } window.onload = function() { document.getElementById("session").value = makeid(); } 2. in the form that you take the data from user add a new hidden input &lt;form&gt; ... &lt;input type="hidden" name="session" id="session"&gt; &lt;/form&gt; 3. now when the user submit the form to a view we need to do this in the view def someview(request): session_id = request.GET.get('session') username = request.GET.get('username') # or any data... request.session['username_%s' % session_id] = username # now lets say you want to redirect the user to the next page... # you have to send the 'session_id' to it and always send to # the next view then in that view retrieve his name like this # ``name = request.session['username_%s' % session_id] `` # the session_id from the old view so the urls should be like this: /first-step/?session=somecode. /second-step/?session=somecode if you have more fields you have to save them in session and retrieve them as i did, hope it helps you, i know its complex! bye :)
accepted answer of: http://stackoverflow.com/q/48095737
has comment: http://stackoverflow.com/comment/83210637
upvote count: 2
answers question: http://stackoverflow.com/q/48095737
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/48104288
accepted answer: http://stackoverflow.com/a/48104304
answer count: 1
downvote count: 0
has title: TypeError: initial_value must be str or None, not bytes
has answer: http://stackoverflow.com/a/48104304
tagged with: typeerror
tagged with: python
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/7391945
upvote count: 1
type: Question
type: AnsweredQuestion
has body: # -*- coding : utf-8 -*- import tkinter as tk import requests from PIL import Image from io import StringIO class Window: def __init__(self, master): self.master = master self.url = tk.Entry() self.url.get() self.url.grid(row=0, column=1) self.button = tk.Button(text="Download", command=self.get_url) self.button.grid(row=0, column=0) self.label = tk.Label(text="Name") self.label.grid(row=1, column=0) self.path = tk.Entry() self.path.grid(row=1, column=1) def get_url(self): self.r = requests.get(self.url.get()) self.i = Image.open(StringIO(self.r.content)) self.i.save(self.path.get()) def main(): root = tk.Tk() w = Window(root) root.mainloop() if __name__ == "__main__": main() Here is my code.I'm beging to study classes in python and trying to write a simple GUI app to download images from entered URL's, but there's a problem with this part: self.i = Image.open(StringIO(self.r.content)). Please, explain me what I do wrong.
score: 1

rpmbuild
tags question: http://stackoverflow.com/q/48064648
tag name: rpmbuild
type: Tag

http://stackoverflow.com/comment/83319339
has text: +1. I was thinking about classmethod, but the list of steps of forms dependent on instance data (i.e. info about current form’s step). It worked with minor alterations.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48162298

http://stackoverflow.com/comment/83294155
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48157353
has text: The best thing to do before posting a question is to print every single unknown on every single line so you can see as much useful info as possible.

http://stackoverflow.com/comment/83233638
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48127701
score: 0
has text: Welcome to Stackoverflow! To get the most out of the site it is important to [ask good questions](http://stackoverflow.com/help/how-to-ask), that includes creating a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example.

http://stackoverflow.com/comment/94742105
type: Comment
has text: Did you solve this mrdrako?
type: QuestionComment
comment on: http://stackoverflow.com/q/48119389
score: 0

http://stackoverflow.com/comment/83112675
has text: Based on my `__init__`, `x` takes precedence, that is the reason to be and `if elif...`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48069450
score: 0

http://stackoverflow.com/q/48102429
tagged with: python
has title: Pandas One by One Entry with Python
type: Question
has answer: http://stackoverflow.com/a/48103661
has body: so I am building a simple app here I wanted some values to be put into my csv via PANDAS each time there was an entry in the interface. Here's my code: filename = 'sheet2.csv' pathto_csv = os.path.join('Walenv/',filename) if request.method == 'POST': try: data_df = pd.read_csv(pathto_csv, delimiter=',', encoding="utf-8-sig" ) lookup=request.form['lookup'] product = wapy.product_lookup(lookup) print (product.name) i=1 while(i != 0): data_df.set_value([i], ['Walmart SKU'], lookup) data_df.set_value([i], ['Price'], product.name) data_df.to_csv(pathto_csv) i+=1 except EmptyDataError: pass path = os.path.join(app.root_path, 'Walenv') return send_from_directory (path, filename) else: return render_template('success.html') But what this does is that every entry that goes in every column fills up everything, here's an image: [IMG1] what I wanted to do was to add it one by one. for example 1 14660314 Bowflex Blaze Home Gym 2 42142144 Product Item Number2 3 25235255 Product Item Number3 In this case I had three entries in total. I thought of putting it in a loop so that it would remember the index, everytime I add something new. How do I fix this so I can get my desired output? I tried putting it out of the loop and removing the i and yeah, as you can expect it only replaces the values
has answer: http://stackoverflow.com/a/48103354
has comment: http://stackoverflow.com/comment/83181079
has comment: http://stackoverflow.com/comment/83180290
score: 0
answer count: 2
tagged with: pandas
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83180912
type: UnansweredQuestion

http://stackoverflow.com/q/48161003
possible better answer: http://stackoverflow.com/a/48161308
has answer: http://stackoverflow.com/a/48161052
linked to: http://stackoverflow.com/q/27362611
has title: How to pair strings inside a list?
tagged with: python
has body: I have a list of strings, and I want to pair them in such a way that the last and second last is one pair, second last and third last in one pair and so on with a three dots in between. Example: Let's say I have the following list ['a', 'b', 'c', 'd', 'e'] and I want to convert this into something like this ['e...d', 'd...c', 'c...b', 'b...a', 'a...none'] So far I have done the following, &gt;&gt;&gt; import string &gt;&gt;&gt; &gt;&gt;&gt; letters = string.ascii_lowercase[:5] &gt;&gt;&gt; letters = iter(reversed(letters)) &gt;&gt;&gt; pair_iter = (c + '...' + next(letters, 'none') for c in letters) &gt;&gt;&gt; pair_iter = list(pair_iter) &gt;&gt;&gt; pair_iter ['e...d', 'c...b', 'a...none'] I am not sure what else to do in this case, I do know that next go to the next string, but how should I copy the previous one and then go to the next one?
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/48161052
type: AnsweredQuestion
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48161308
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/83019226
type: Comment
comment on: http://stackoverflow.com/a/48024831
score: 0
has text: is there a more efficient way without using try/except block that you can implement the stillConnected() function with? ; if so please add it to the your answer
type: AnswerComment

async-await
tags question: http://stackoverflow.com/q/48020593
type: Tag
tags question: http://stackoverflow.com/q/48035079
tag name: async-await

http://stackoverflow.com/q/48140193
favorite count: 0
answer count: 3
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48140760
has title: Why can't FLASK_APP find my factory function?
possible better answer: http://stackoverflow.com/a/54941438
has answer: http://stackoverflow.com/a/59085673
has answer: http://stackoverflow.com/a/54941438
type: Question
has body: I am trying to reconfigure an existing Flask app with an application factory to be installed with setup.py. Currently, with my non-installable package, I use a file called wsgi.py and point FLASK_APP at that. from example.factory import create_app app = create_app() export FLASK_APP=wsgi.py flask run However, if I try to point Flask directly at the factory in the installed package, I getRuntimeError: Failed to find application in module "example.factory". I found this pattern in the examples in the Flask repository. export FLASK_APP="example.factory:create_app()" flask run # doesn't find the app Why does the wsgi.py method work while the direct method fails?
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/48140760
downvote count: 0
tagged with: flask

http://stackoverflow.com/q/48150328
has comment: http://stackoverflow.com/comment/83279364
type: AnsweredQuestion
has body: Trying really hard to figure out how to solve this problem. The problem being finding nth number of Fibonacci with O(n) complexity using javascript. I found a lot of great articles how to solve this using C++ or Python, but every time I try to implement the same logic I end up in a Maximum call stack size exceeded. Example code in Python MAX = 1000 # Create an array for memoization f = [0] * MAX # Returns n'th fuibonacci number using table f[] def fib(n) : # Base cases if (n == 0) : return 0 if (n == 1 or n == 2) : f[n] = 1 return (f[n]) # If fib(n) is already computed if (f[n]) : return f[n] if( n &amp; 1) : k = (n + 1) // 2 else : k = n // 2 # Applyting above formula [Note value n&amp;1 is 1 # if n is odd, else 0. if((n &amp; 1) ) : f[n] = (fib(k) * fib(k) + fib(k-1) * fib(k-1)) else : f[n] = (2*fib(k-1) + fib(k))*fib(k) return f[n] // # Driver code // n = 9 // print(fib(n)) Then trying to port this to Javascript const MAX = 1000; let f = Array(MAX).fill(0); let k; const fib = (n) =&gt; { if (n == 0) { return 0; } if (n == 1 || n == 2) { f[n] = 1; return f[n] } if (f[n]) { return f[n] } if (n &amp; 1) { k = Math.floor(((n + 1) / 2)) } else { k = Math.floor(n / 2) } if ((n &amp; 1)) { f[n] = (fib(k) * fib(k) + fib(k-1) * fib(k-1)) } else { f[n] = (2*fib(k-1) + fib(k))*fib(k) } return f[n] } console.log(fib(9)) That obviously doesn't work. In Javascript this ends up in an infinite loops. So how would you solve this using Javascript? Thanks in advance
downvote count: 3
upvote count: 1
type: Question
has title: How to find nth Fibonacci number using Javascript with O(n) complexity
has answer: http://stackoverflow.com/a/48150570
tagged with: fibonacci
has answer: http://stackoverflow.com/a/48150484
tagged with: algorithm
score: -2
has comment: http://stackoverflow.com/comment/83278976
linked to: http://stackoverflow.com/q/3953749
has comment: http://stackoverflow.com/comment/83279707
has answer: http://stackoverflow.com/a/48150583
accepted answer: http://stackoverflow.com/a/48150583
tagged with: time-complexity
has answer: http://stackoverflow.com/a/59808054
has answer: http://stackoverflow.com/a/58896016
has comment: http://stackoverflow.com/comment/83279430
answer count: 7
tagged with: javascript
has answer: http://stackoverflow.com/a/68658863
has comment: http://stackoverflow.com/comment/83279349
favorite count: 0
has comment: http://stackoverflow.com/comment/83279212
possible better answer: http://stackoverflow.com/a/48150484
has answer: http://stackoverflow.com/a/72584625
tagged with: python

http://stackoverflow.com/comment/93150510
has text: Please explain. Explaining how the function works, will add value over the file of the answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48150978
type: Comment

http://stackoverflow.com/comment/83115541
type: Comment
comment on: http://stackoverflow.com/a/48031874
score: 0
type: AnswerComment
has text: For counting, you can just use the one from `collections`, a standard library. For hashing, I am not so sure what you are looking into. Can you say more about that? I don't seem to use hashing in my method.

http://stackoverflow.com/comment/83198555
comment on: http://stackoverflow.com/q/48111037
type: QuestionComment
has text: Why do you want to make it a singleton? If this object is useful, why would you want to deny yourself the option of instantiating more than one per application? There doesn't seem to be any reason for that. And as Sraw points out in his answer, dictionary access is already threadsafe so in fact you don't have to do anything at all.
type: Comment
score: 1

http://stackoverflow.com/a/48148380
downvote count: 0
has comment: http://stackoverflow.com/comment/83275083
upvote count: 2
has comment: http://stackoverflow.com/comment/83275133
answers question: http://stackoverflow.com/q/48147975
type: Answer
has body: If you want the result of that output as a literal, i.e.: &gt;&gt;&gt; '\xf7\x03\x07\xd6\x00\x01\x70\x10' '\xf7\x03\x07\xd6\x00\x01p\x10' Use the binascii module: &gt;&gt;&gt; import binascii &gt;&gt;&gt; s = "f70307d600017010" &gt;&gt;&gt; binascii.unhexlify(s) '\xf7\x03\x07\xd6\x00\x01p\x10'
score: 2

http://stackoverflow.com/comment/83163924
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48094687
score: 0
has text: What have you tried? We can then tell you whether it is Pythonic.

http://stackoverflow.com/comment/83101943
score: 2
has text: Even if the performance issues have been overcome in Python3, seeing `map` or `filter` molested with a `lambda` function gives me the creeps.
type: AnswerComment
comment on: http://stackoverflow.com/a/48064014
type: Comment

http://stackoverflow.com/a/48258953
has comment: http://stackoverflow.com/comment/84170605
answers question: http://stackoverflow.com/q/48173038
downvote count: 0
has body: Yes, this is completely possible. The CNTK framework itself is written in C++ and the C# as well as the Python interface are only wrappers onto the C++ code. So, as long you use versions which are compatible to each other, you can do that. For instance, if you use CNTK 2.3.1 with python and also CNTK 2.3.1 with C# there is of course nothing which should get in your way. If the versions are different, it depends if there have been breaking changes. Just for your information: There will be two formats in the near future: CNTK V2 model format and the new ONNX format.
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/48102246
score: 2
downvote count: 0
has body: for index in range(len(lst) - 1, 0, -1): if lst[index][1:] == lst[index - 1][1:]: lst.pop(index) By going through the list backwards, we remove the problems with indices changing when we remove elements. This results in an in-place reduction. If you'd like to make a new list, this can be done via list comprehension following the same idea, but since we're not doing it in place, we don't have to work in reverse: lst[0] + [lst[ind] for ind in range(1, len(lst)) if lst[ind][1:] != lst[ind-1][1:]] Again, lst[0] is trivially non-duplicate and therefore automatically included.
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/48102142

http://stackoverflow.com/comment/83110276
score: 0
has text: How I wish it were my original idea. :) Does this mean you might accept my answer?
comment on: http://stackoverflow.com/a/48066955
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84511491
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48037509
has text: how about nested loops?

http://stackoverflow.com/q/48030603
has comment: http://stackoverflow.com/comment/83031448
answer count: 2
has answer: http://stackoverflow.com/a/48031009
has body: Code 1: %%timeit students = [['Zack',38],['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] second_highest = sorted(list(set([x[1] for x in students])))[1] ([a for a,b in sorted(students) if b == second_highest]) Code 2: %%timeit students = [['Zack',38],['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] s = sorted(set([x[1] for x in students])) for name in sorted(x[0] for x in students if x[1] == s[1]): name Now I am confused about execution of two programs, how is code2 is faster than code code1, despite use of nested for loop in code2. Image below is from Jupyter notebook which show mean time taken by code from 100000 loops. Although the difference is very minute but I am confused because how can nested for-loop work faster than single for loop. I was supposed to Print the output, so can put print before the last line of code
tagged with: jupyter
tagged with: jupyter-notebook
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/18648689
tagged with: python
has title: Confused about execution of two codes in python?
score: 0
has comment: http://stackoverflow.com/comment/83031468
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48030649
type: Question
tagged with: for-loop

http://stackoverflow.com/comment/83112613
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48069329
has text: ah, got it. Thanks again!

http://stackoverflow.com/comment/83191328
score: 0
has text: @brianvu the `.concat()` method you are using is a reasonable solution. Without the actual data in the Excel spreadsheets, it is hard to identify the root cause. I would `print(df1)` and `print(df2)` to ensure that `pandas.read_excel()` function is correctly reading in the data initially.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48106822

http://stackoverflow.com/q/48021226
has comment: http://stackoverflow.com/comment/83011612
favorite count: 0
has title: Save mask to image (Python, OpenCV)
type: UnansweredQuestion
tagged with: python
tagged with: mask
has body: I am using this code to create a mask which split every image in half (left-right). import cv2 import numpy as np image = cv2.imread('box.png') h = image.shape[0] w = image.shape[1] mask_l = np.zeros(image.shape[:2], dtype="uint8") roi = cv2.rectangle(mask_l, (w//2, 0), (0, h), 255, -1) # LEFT MASK masked_l = cv2.bitwise_and(image, image, mask=mask_l) cv2.imshow("Left", masked_l) cv2.waitKey(0) mask_r = np.zeros(image.shape[:2], dtype="uint8") cv2.rectangle(mask_r, (w//2, 0), (w, h), 255, -1) # RIGHT MASK masked_r = cv2.bitwise_and(image, image, mask=mask_r) cv2.imshow("Right", masked_r) cv2.waitKey(0) How can I save the visible part of the image to a ROI ? Possible, if the saved rectangle take the name as source image as part of filename. Es: input --> box.png --> output --> box1.png, box2.png Thanks
has comment: http://stackoverflow.com/comment/83011579
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48021955
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/83011946
score: 0
answer count: 1

evaluation
tags question: http://stackoverflow.com/q/48061976
tag name: evaluation
type: Tag
tags question: http://stackoverflow.com/q/48092084

http://stackoverflow.com/comment/83110795
comment on: http://stackoverflow.com/q/48065179
score: 0
type: QuestionComment
type: Comment
has text: Are you really intending to screenshot the entire `BODY` tag? I thought you just wanted the map? The map is an `IMG` with an ID so it's easy to locate also.

http://stackoverflow.com/q/48158547
type: AnsweredQuestion
downvote count: 0
tagged with: machine-learning
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/48314642
answer count: 2
has answer: http://stackoverflow.com/a/48314642
has body: I'm working with the keras seq2seq example here: https://github.com/keras-team/keras/blob/master/examples/lstm_seq2seq.py I would like to persist the vocabulary and decoder so that I can load it again later, and apply it to new sequences. While the code calls model.save(), this is insufficient because I can see the decoding setup referencing a number of other variables which are deep pointers into the trained model: encoder_model = Model(encoder_inputs, encoder_states) decoder_state_input_h = Input(shape=(latent_dim,)) decoder_state_input_c = Input(shape=(latent_dim,)) decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c] decoder_outputs, state_h, state_c = decoder_lstm( decoder_inputs, initial_state=decoder_states_inputs) decoder_states = [state_h, state_c] decoder_outputs = decoder_dense(decoder_outputs) decoder_model = Model( [decoder_inputs] + decoder_states_inputs, [decoder_outputs] + decoder_states) I would like to translate this code to determine encoder_inputs, encoder_states, latent_dim, decoder_inputs from a model loaded from disk. It's ok to assume I know the model architecture in advance. Is there a straightforward way to do this? Update: I have made some progress using the decoder construction code and pulling out the layer inputs/outputs as needed. encoder_inputs = model.input[0] #input_1 decoder_inputs = model.input[1] #input_2 encoder_outputs, state_h_enc, state_c_enc = model.layers[2].output # lstm_1 _, state_h_dec, state_c_dec = model.layers[3].output # lstm_2 decoder_outputs = model.layers[4].output # dense_1 encoder_states = [state_h_enc, state_c_enc] encoder_model = Model(encoder_inputs, encoder_states) latent_dim = 256 # TODO: infer this from the model. Should match lstm_1 outputs. decoder_state_input_h = Input(shape=(latent_dim,)) decoder_state_input_c = Input(shape=(latent_dim,)) decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c] decoder_states = [state_h_dec, state_c_dec] decoder_model = Model( [decoder_i…
tagged with: keras
score: 4
favorite count: 0
has title: Restore keras seq2seq model
possible better answer: http://stackoverflow.com/a/50048551
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/50048551

http://stackoverflow.com/a/48095853
has body: You need to read the documentation more carefully: you are missing the kwargs maxBytes and backupCount. Replace this handler = RotatingFileHandler(file_name, 'a+', MAX_LOG_SIZE) for this handler = RotatingFileHandler(file_name, 'a+', maxBytes=MAX_LOG_SIZE, backupCount=5) Notice you shall set a backupCount value that fits your needs, I just used a random one. A further explanation of why your piece of code does not roll the file is because the value backupCount is 0. See the following: You can use the maxBytes and backupCount values to allow the file to rollover at a predetermined size. When the size is about to be exceeded, the file is closed and a new file is silently opened for output. Rollover occurs whenever the current log file is nearly maxBytes in length; but if either of maxBytes or backupCount is zero, rollover never occurs, so you generally want to set backupCount to at least 1, and have a non-zero maxBytes.
type: Answer
accepted answer of: http://stackoverflow.com/q/48095578
upvote count: 10
answers question: http://stackoverflow.com/q/48095578
has comment: http://stackoverflow.com/comment/104927485
type: AcceptedAnswer
score: 10
downvote count: 0

http://stackoverflow.com/comment/83184934
score: 0
type: Comment
type: QuestionComment
has text: Basically. In the created .py file there will be a class generated that has the name of whatever you named the widget in QtDesigner. Import this class and subclass it.
comment on: http://stackoverflow.com/q/48104077

http://stackoverflow.com/q/48070973
has comment: http://stackoverflow.com/comment/83116201
type: Question
tagged with: pythonpath
has comment: http://stackoverflow.com/comment/83116059
has comment: http://stackoverflow.com/comment/83115659
has comment: http://stackoverflow.com/comment/83115793
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/83116311
has comment: http://stackoverflow.com/comment/83115747
linked to: http://stackoverflow.com/q/37490935
has comment: http://stackoverflow.com/comment/83118721
has title: How do I get my python application to ignore PYTHONPATH
has comment: http://stackoverflow.com/comment/83116271
has body: I have a python application (it is a command line interface application) which is invoked through entry_points/console_scripts of setup.py. Whenever users have a locally specified PYTHONPATH that includes libraries from another version of Python, the application fails. I have gone through How do I get an installed script to ignore PYTHONPATH, but it recommends not using console_scripts, which is not possible in my case. I need a way to ensure that the PYTHONPATH that is locally specified by the user is ignored or removed when the application is launched. How can I achieve this?
answer count: 0
tagged with: setup.py
has comment: http://stackoverflow.com/comment/83115682
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83115647
tagged with: python
has comment: http://stackoverflow.com/comment/83115664

http://stackoverflow.com/q/48137162
score: 3
has body: Given two separate dataframes I'm looking to merge them and unify a set of their joined columns. Example: In[1]: df1 Out[1]: a_id a_time a_val 0 1 100000000 a 1 2 200000000 b 2 3 300000000 c In[10]: df2 Out[10]: b_id b_time b_val 0 1 100000000 d 1 2 150000000 e 2 3 350000000 f The resulting dataframe I'm looking for is the following id time val 0 1 100000000 a 1 1 100000000 d 2 2 150000000 e 3 2 200000000 b 4 3 300000000 c 5 3 350000000 f Assuming all IDs are present on both tables, the result should be of length len(df1) + len(df2). I was looking at some results using .stack() but I couldn't really figure out how to make it work on when merging two tables. Notice the time could be the same, or could be different.
accepted answer: http://stackoverflow.com/a/48137177
has answer: http://stackoverflow.com/a/48137654
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48137654
tagged with: pandas
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48137177
has title: Pandas - Merge two dataframes and unify set of columns
upvote count: 3
type: AnsweredQuestion

http://stackoverflow.com/comment/86405086
has text: Yeah, I too would like to know if there is a way to prevent this. All the similar questions I can find ask how to make a progress bar that works in Jupyter, not how to deal with ones which don't work because they rely on carriage returns. There is plenty of code which already implements progress bars for the terminal which people just need to use, and which they cannot simply "fix" to work with Jupyter. There needs to be something that one can do on the Jupyter side to somehow deal with this kind of attempted output. Can one do something like capture the print output and modify it?
comment on: http://stackoverflow.com/q/48072260
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83276797
type: QuestionComment
score: 2
has text: How are you forcing the exception to occur? Are you sure the `Send_Email` method is actually being called?
comment on: http://stackoverflow.com/q/48148748
type: Comment

http://stackoverflow.com/comment/83221946
type: AnswerComment
type: Comment
has text: Do you have "www.domain-a.net" anywhere in your Flask config?
comment on: http://stackoverflow.com/a/48122563
score: 0

http://stackoverflow.com/q/48135843
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48136063
type: Question
has answer: http://stackoverflow.com/a/48135935
has title: Iterable Datetime - How to get continuos datetime objects with day name in Python?
has answer: http://stackoverflow.com/a/48136062
has body: I want to create a mapping of the everyday of the week with its datetime object. So my dictionary should be having keys as "Monday", "Tuesday", .. (so on) so that I can get a datetime object for every day on the next(!) week. At the moment I have a dictionary with these values: DAYS_DATETIME_RELATIONS = { "today": datetime.datetime.now(), "tomorrow": datetime.datetime.now() + datetime.timedelta(days=1), "after_tomorrow": datetime.datetime.now() + datetime.timedelta(days=2) } Unfortunately I cannot find any algorithmic solution for this and hope anyone of you could help me.
downvote count: 0
linked to: http://stackoverflow.com/q/2776829
has answer: http://stackoverflow.com/a/48136708
favorite count: 0
linked to: http://stackoverflow.com/q/9884132
type: UnansweredQuestion
tagged with: datetime
has comment: http://stackoverflow.com/comment/83249052
tagged with: python
tagged with: dictionary
answer count: 4

http://stackoverflow.com/a/48084245
score: 2
has body: With this :-), then just select what you need from the result df.groupby('[A]',as_index=False).agg(lambda x : x.head(1) if x.dtype=='object' else x.sum()) Out[275]: [A] [B] [C] [D] [E] 0 123 X Y 5 A 1 135 D E 4 B 2 434 R F 8 C
downvote count: 0
answers question: http://stackoverflow.com/q/48083944
upvote count: 2
type: Answer

http://stackoverflow.com/a/48061704
type: Answer
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83097546
answers question: http://stackoverflow.com/q/48061508
has body: As np.prod is taking the product of all the elements in an array, if we want to exclude one element from the solution, we can set that element to 1 first in order to ignore it (as p * 1 = p). So: &gt;&gt;&gt; n = 10 &gt;&gt;&gt; x = np.arange(10) &gt;&gt;&gt; i = 0 &gt;&gt;&gt; x[i] = 1 &gt;&gt;&gt; np.prod(x) 362880 which, we can see, works: &gt;&gt;&gt; 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 362880

http://stackoverflow.com/q/48015640
tagged with: selenium
type: Question
linked to: http://stackoverflow.com/q/44912203
has comment: http://stackoverflow.com/comment/83015497
has answer: http://stackoverflow.com/a/48017970
tagged with: button
has comment: http://stackoverflow.com/comment/83014442
has title: Not able to click a button in Selenium (Booking.com)
score: 0
answer count: 3
has body: I am programming a python scraper with help of Selenium. The first few steps are: goes on booking.com, insert a city name, selects the first date and then tries to open the check-out calendar. Here is where my problem occurs. I am not able to click the check-out calendar button (The important are of the website). I tried to click every element regarding to the to check-out calendar (The elements of check-out calendar) with element.click(). I also tried the method element = self.browser.find_element_by_xpath('(//div[contains(@class,"checkout-field")]//button[@aria-label="Open calendar"])[1]') self.browser.execute_script("arguments[0].click();", element) It either does nothing (in case of execute.script() and click() on div elements) or it throws following exception when directly clicking the button: Element &lt;button class="sb-date-field__icon sb-date-field__icon-btn bk-svg-wrapper" type="button"&gt; is not clickable at point (367.5,316.29998779296875) because another element &lt;div class="sb-date-field__display"&gt; obscures it Here is a short code to test it: browser = webdriver.Firefox() browser.get("https://www.booking.com/") wait = WebDriverWait(browser, 5) element = wait.until(EC.presence_of_element_located(( By.XPATH, '(//div[contains(@class,"checkout-field")]//button[@aria-label="Open calendar"])[1]'))) element = wait.until(EC.element_to_be_clickable(( By.XPATH, '(//div[contains(@class,"checkout-field")]//button[@aria-label="Open calendar"])[1]'))) element.click() I have a temporarily solution for my problem but I am not satisfied with it. element = browser.find_element_by_xpath('(//div[contains(@class,"checkout-field")]//button[@aria-label="Open calendar"])[1]') hov = ActionChains(browser).move_to_element(element) hov.click().perform() This will open the calendar by hovering over the object and clicking it. This strangely opens the calendar. The methods mentioned above still don't work.
tagged with: python
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/48016124
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48034251

http://stackoverflow.com/a/48032340
score: 14
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48032262
upvote count: 14
has body: Trace the execution. s1=stud('student1',40) This sets s1.name to "student1" s1.mark to 40 s1.message to "student1 40" Think of the attribute values as boxes. Each of the three boxes have a value in them. Two of them hold strings. One of them holds a number. They will hold those values until they are explicitly assigned to. In particular the attribute message has NO IDEA how it got its value. It has no idea it got its value by concatenating the name attribute and the mark attribute. All it knows is that the value it has is "student1 40". print s1.message This outputs student1 40 (no surprise) s1.name='student2' You updated one of the three attributes. But you did not update the others. print s1.message Since you never explicitly changed s1.message, this still outputs student1 40. The point is the value of s1.message is just a string. There is no invisible computation that automatically updates it whenever the expression that initialized it gets changed. Other languages work that way perhaps, but Python does not. If you want that behavior, then do this: class stud(): def __init__(self,a,b): self.name=a self.mark=b @property def message(): return self.name + ' ' +str(self.mark)
accepted answer of: http://stackoverflow.com/q/48032262

http://stackoverflow.com/comment/83143124
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48084139
has text: increase_score(5, aScore) ????

jupyter-notebook
tags question: http://stackoverflow.com/q/48079133
tags question: http://stackoverflow.com/q/48014819
tags question: http://stackoverflow.com/q/48066585
tags question: http://stackoverflow.com/q/48072260
tags question: http://stackoverflow.com/q/48113872
tags question: http://stackoverflow.com/q/48085110
tags question: http://stackoverflow.com/q/48036369
tags question: http://stackoverflow.com/q/48122157
tags question: http://stackoverflow.com/q/48109094
tags question: http://stackoverflow.com/q/48106135
tags question: http://stackoverflow.com/q/48144431
tags question: http://stackoverflow.com/q/48090119
tags question: http://stackoverflow.com/q/48130290
tags question: http://stackoverflow.com/q/48137595
tags question: http://stackoverflow.com/q/48036695
type: Tag
tags question: http://stackoverflow.com/q/48014844
tags question: http://stackoverflow.com/q/48022199
tags question: http://stackoverflow.com/q/48030603
tags question: http://stackoverflow.com/q/48067529
tags question: http://stackoverflow.com/q/48135088
tags question: http://stackoverflow.com/q/48150506
tags question: http://stackoverflow.com/q/48133282
tags question: http://stackoverflow.com/q/48078170
tags question: http://stackoverflow.com/q/48130916
tags question: http://stackoverflow.com/q/48024903
tags question: http://stackoverflow.com/q/48038335
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/48142618
tags question: http://stackoverflow.com/q/48020345
tags question: http://stackoverflow.com/q/48147248
tags question: http://stackoverflow.com/q/48159441
tags question: http://stackoverflow.com/q/48047235

http://stackoverflow.com/comment/83323858
type: QuestionComment
has text: @WillemVanOnsem that may be what the OP is searching for. I understand they wrote `a-zA-Z`, but even if it's not what the OP is searching for maybe it will help another user. Just write a note letting users know that it matches Unicode characters and the `Lm`, `Lt`, `Lu`, `Ll`, `Lo` categories. Or just add logic from [this](https://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii) post to your answer.
comment on: http://stackoverflow.com/q/48171985
score: 0
type: Comment

http://stackoverflow.com/comment/83015153
score: 0
comment on: http://stackoverflow.com/a/48022892
has text: Right, but that defeats the purpose of trying to fit the curve. The initial parameters I gave to solver in excel is 1,1 just as the default is in curve_fit.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83207024
type: AnswerComment
has text: Though I do not understand why this works, and your original solution did not, great that it works!
comment on: http://stackoverflow.com/a/48114830
type: Comment
score: 0

http://stackoverflow.com/a/48040353
upvote count: 2
answers question: http://stackoverflow.com/q/48039728
has comment: http://stackoverflow.com/comment/83079974
type: AcceptedAnswer
downvote count: 0
has body: I may give an idea , that create a 'subgrids' object and a 'main grid' object that contain the 'subgrids'. These two objects would be GridLayout objects. Here is a simple example in python2.7 : import kivy from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label class SubGrids(GridLayout): def __init__(self): GridLayout.__init__(self, cols=3, rows=3); self.add_widget(Label(text='1st')); self.add_widget(Label(text='')); self.add_widget(Label(text='2nd')); self.add_widget(Label(text='')); self.add_widget(Label(text='3rd')); self.add_widget(Label(text='')); self.add_widget(Label(text='4th')); self.add_widget(Label(text='')); self.add_widget(Label(text='5th')); class Grids(GridLayout): def __init__(self): GridLayout.__init__(self, cols=2, rows = 2); self.add_widget(SubGrids()); self.add_widget(SubGrids()); self.add_widget(SubGrids()); self.add_widget(SubGrids()); class Example(App): def build(self): return Grids() if __name__ == '__main__': x = Example(); x.run(); Hope this gives an idea.
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48039728

http://stackoverflow.com/comment/83303351
comment on: http://stackoverflow.com/q/48156281
type: Comment
type: QuestionComment
score: 1
has text: @TagueGriffith you are right it was configuration issue. I was able to solve it by setting `decode_responses` flag.

http://stackoverflow.com/comment/83114397
type: Comment
has text: also - sorry when i said started up project. I meant I logged into the production server, then through cmd prompt, wrote in python manage.py runserver X.x.x.x:8000 for the app to start on the server. This was not on my desktop. There is a WSGI file which is under the project name - WSGI.PY i believe. But no Gunicorn that I can see. I am not how, or what benefit, it would be for me to SSH into the machine given I already have access to the production server - unless I misunderstood your question. THANKS AGAIN BTW
score: 0
comment on: http://stackoverflow.com/q/48070008
type: QuestionComment

http://stackoverflow.com/comment/83230899
score: 0
type: Comment
type: QuestionComment
has text: Can you indent this properly?
comment on: http://stackoverflow.com/q/48127152

http://stackoverflow.com/comment/83180437
has text: You have to implement `__hash__` and `__eq__`.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48102501

http://stackoverflow.com/q/48079421
tagged with: numpy
linked to: http://stackoverflow.com/q/8486294
has comment: http://stackoverflow.com/comment/83133019
has answer: http://stackoverflow.com/a/48081913
score: -2
tagged with: arrays
duplicate of: http://stackoverflow.com/q/8486294
accepted answer: http://stackoverflow.com/a/48079881
has body: I have an 2D array : 1 2 3 4 5 6 2 6 5 2 4 1 8 7 9 0 0 0 2 3 4 5 6 2 How can I add a new column of 1D array to the above array? 1 0 1 0 So that the result will look like this? 1 2 3 4 5 6 1 2 6 5 2 4 1 0 8 7 9 0 0 0 1 2 3 4 5 6 2 0 EDIT: I'm not adding a column of zeros here.
possible better answer: http://stackoverflow.com/a/48080531
has answer: http://stackoverflow.com/a/48080531
downvote count: 2
has answer: http://stackoverflow.com/a/48079881
favorite count: 0
has comment: http://stackoverflow.com/comment/83132798
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/83133507
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/48079514
has title: How to add a column to a 2D np array python?
type: Question

http://stackoverflow.com/comment/83134716
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48060464
has text: Is it possible to run this code on a whole tex converting the letters to their hex value on the fly ? Because hex(ord(u'è')) returns an str type but uclist.lookup takes an int as an argument.

http://stackoverflow.com/comment/83084205
type: QuestionComment
has text: As long as you run it on all the fields, `generic_filter` at the end would modify all data
score: 0
comment on: http://stackoverflow.com/q/48055971
type: Comment

http://stackoverflow.com/q/48104449
has body: I was reading an interesting post on Short-Circuiting in Python and wondered if this was true for the in operator. My simple testing would conclude that it does not: %%timeit -n 1000 0 in list(range(10)) 1000 loops, best of 3: 639 ns per loop %%timeit -n 1000 0 in list(range(1000)) 1000 loops, best of 3: 23.7 µs per loop # larger the list, the longer it takes. however, i do notice that a higher # value does take longer. %%timeit -n 1000 999 in list(range(1000)) 1000 loops, best of 3: 45.1 µs per loop Is there a detailed explanation of why 999 takes longer than 0. Is the in operator like a loop? Also, is there a way to tell the in operator to "stop the loop" once the value is found (or is this the already defaulted behavior that I'm not seeing)? Lastly- Is there another operator/function that I am skipping over that does what I'm talking about in regards to "short-circuiting" in?
has comment: http://stackoverflow.com/comment/83184570
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48104489
has comment: http://stackoverflow.com/comment/83184674
has comment: http://stackoverflow.com/comment/83184783
has answer: http://stackoverflow.com/a/48104545
type: Question
possible better answer: http://stackoverflow.com/a/48104489
tagged with: short-circuiting
linked to: http://stackoverflow.com/q/30081275
duplicate of: http://stackoverflow.com/q/64090762
has comment: http://stackoverflow.com/comment/83184756
linked to: http://stackoverflow.com/q/64090762
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/2580136
favorite count: 0
has comment: http://stackoverflow.com/comment/83184726
upvote count: 3
has comment: http://stackoverflow.com/comment/139633801
has comment: http://stackoverflow.com/comment/83184727
tagged with: python-internals
downvote count: 3
has comment: http://stackoverflow.com/comment/83184557
has title: Python In Operator - Short Circuit
has comment: http://stackoverflow.com/comment/83184590
tagged with: python
has answer: http://stackoverflow.com/a/48104631
accepted answer: http://stackoverflow.com/a/48104631

http://stackoverflow.com/a/48027820
type: AcceptedAnswer
type: Answer
has body: This is a sequence forecasting problem which is best solved with recurrent or long short-term memory networks. Following can be a good starter: from keras.models import Sequential from keras.layers import LSTM, Dense, Dropout import numpy as np #assuming all 4 columns correspond to 1 song data_dim = 4 #so one song would be 10x4 2D array number_of_notes_per_song = 10 nsongs_train = 100 #tunable parameter batch_size = 32 epochs = 5 # I generated dummy data, but you have your own... x_train = np.random.random((nsongs_train, number_of_notes_per_song, data_dim)).reshape(nsongs_train*number_of_notes_per_song,data_dim) #this is a supervised learning problem, but your dataset has no labels.. #we can use last note in each song as a label when training LSTM X = x_train[np.mod(np.arange(x_train.shape[0]),number_of_notes_per_song)!=0].reshape(nsongs_train,number_of_notes_per_song-1,data_dim) y = x_train[::number_of_notes_per_song].reshape(nsongs_train,data_dim) model = Sequential() model.add(LSTM(32, input_shape=(number_of_notes_per_song-1, data_dim),return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(64)) model.add(Dropout(0.2)) model.add(Dense(data_dim, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam') model.fit(X,y,batch_size=batch_size, epochs=epochs) #predict on unseen data, expects tensors of shape (None, number_of_notes_per_song-1, data_dim) model.predict(...) Note, that this is a supervised machine learning problem, but your dataset has no labels. We can go around this by using the last note in each song as a label. This effectively reduces the sequence length by 1 note. Note also, that if your song had hundreds of notes, it would be best to feed them to LSTM in sub-sequences, not resetting states until the end of the song. Here is an example of stateful training with Keras. If need to forecast entire songs (rather than just a next character), you'd need to set return_sequences=True in all LSTM layers and use TimeDistribu…
answers question: http://stackoverflow.com/q/48026129
score: 0
accepted answer of: http://stackoverflow.com/q/48026129
has comment: http://stackoverflow.com/comment/83071028

http://stackoverflow.com/comment/83090863
type: QuestionComment
comment on: http://stackoverflow.com/q/48058717
has text: Right, then my question would be: **why are you doing that?** Your SQL library will tell you for sure if the count doesn't match, as my comment above shows for `sqlite3`. Please give some context, this is an [XY problem](http://xyproblem.info) at the moment.
score: 0
type: Comment

http://stackoverflow.com/q/48077265
has body: In python I get "n" number of json objects on request to an api. I need to convert this to a list and display it in django. What is the easiest way to do it. I did use json.dumps(data) it just dumps the entire data.
type: UnansweredQuestion
score: -3
tagged with: django
has title: JSON formatting to a list in python
has answer: http://stackoverflow.com/a/48077331
downvote count: 3
type: Question
answer count: 2
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48077396
tagged with: python
tagged with: python-3.x

http://stackoverflow.com/q/48015016
has comment: http://stackoverflow.com/comment/83136231
upvote count: 6
answer count: 2
has comment: http://stackoverflow.com/comment/83134902
has answer: http://stackoverflow.com/a/48115072
favorite count: 0
tagged with: python-3.x
tagged with: django-2.0
type: UnansweredQuestion
score: 6
tagged with: django
has comment: http://stackoverflow.com/comment/82999609
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/83259991
has body: I want to connect to internal http services with django and I need to buffer the output the http response of those services because some contents are very large. I am using python 3.6, django 2.0, http.client and the following code: class HTTPStreamIterAndClose(): def __init__(self, conn, res, buffsize): self.conn = conn self.res = res self.buffsize = buffsize self.length = 1 bytes_length = int(res.getheader('Content-Length')) if buffsize &lt; bytes_length: self.length = math.ceil(bytes_length/buffsize) def __iter__(self): return self def __next__(self): buff = self.res.read(self.buffsize) if buff is b'': self.res.close() self.conn.close() raise StopIteration else: return buff def __len__(self): return self.length def passthru_http_service(request, server, timeout, path): serv = HTTPService(server, timeout) res = serv.request(path) response = StreamingHttpResponse( HTTPStreamIterAndClose(serv.connection, res, 200), content_type='application/json' ) response['Content-Length'] = res.getheader('Content-Length') return response And the reponse is empty, I test the iterator with: b''.join(HTTPStreamIterAndClose(serv.connection, res, 200) And everything works fine, I don't know why is not working.
has answer: http://stackoverflow.com/a/48270985
has comment: http://stackoverflow.com/comment/83143375
has comment: http://stackoverflow.com/comment/83144825
type: Question
has title: Iterable object and Django StreamingHttpResponse
has comment: http://stackoverflow.com/comment/83130617

http://stackoverflow.com/comment/83235805
type: AnswerComment
comment on: http://stackoverflow.com/a/48129380
type: Comment
score: 2
has text: Need `df["Timestamp"] = pd.to_datetime(df["Timestamp"])` as first step ;)

http://stackoverflow.com/q/48071753
tagged with: machine-learning
type: Question
has answer: http://stackoverflow.com/a/48072042
has body: Hello old faithful community, This might be a though one as I can barely find any material on this. The Problem I have a data set of crimes committed in NSW Australia by council, and have merged this with average house prices by council. I'm now looking to produce a linear regression to try and predict said house price by the crime in the neighbourhood. The issue is, I have 49 crimes, and only want the best ones (statistically speaking) to be used in my model. I've run the regression score over all and some variables (using correlation), and had results from .23 - .38 but I want to perfect this to the best possible - if there is a way to do this of course. I've thought about looping over every possible combination, but this would end up by couple of million according to google. So, my friends - how can I python this dataframe to get the best columns?
upvote count: 5
answer count: 2
score: 5
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48072357
type: UnansweredQuestion
tagged with: python
has title: Selecting the best combination of variables for regression model based on reg score
tagged with: regression

http://stackoverflow.com/comment/83039630
type: Comment
type: QuestionComment
has text: The script is run via the terminal
comment on: http://stackoverflow.com/q/48034141
score: 0

http://stackoverflow.com/a/50051605
upvote count: 4
has comment: http://stackoverflow.com/comment/93779378
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/89484210
answers question: http://stackoverflow.com/q/48081182
downvote count: 1
has body: This worked for me. Hope this helps other people who encounter this issue. brew install python3 pip3 install awscli --upgrade --user

http://stackoverflow.com/comment/83317255
type: Comment
has text: IDK, I didn't experiment.
comment on: http://stackoverflow.com/a/48115072
score: 0
type: AnswerComment

http://stackoverflow.com/q/48152124
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/83284402
type: Question
has comment: http://stackoverflow.com/comment/83284926
upvote count: 1
answer count: 1
has body: I have a tensor of 10.000 pictures in 32x32x3 format. So the Tensor is D4 (shape (10000,32,32,3). Tensor("...", shape=(10000, 32, 32, 3), dtype=float32) Now i want to apply the tf.image.per_image_standardization operations to the individual images: tf. image. per_image_standardization (...) What is the best practice in this case? Maybe slice the tensor in 10000 tensors with the shape (32,32,3)?
has answer: http://stackoverflow.com/a/48154276
accepted answer: http://stackoverflow.com/a/48154276
has title: How to apply tf.image.per_image_standardization() to a tensor with the wrong shape?
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/q/48169759
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: When I define a class like so class SimpleGraphCreator: """ Some simple graph object... """ def __init__(self): self.graph_obj = tf.Graph() with self.graph_obj.as_default() as g_def: x_input_fun = tf.placeholder(dtype=tf.float32, name='input') y_output_fun = tf.placeholder(dtype=tf.float32, name='output') w_weights_fun = tf.get_variable('weight_set', dtype=tf.float32, shape=(5,5)) output = tf.matmul(x_input_fun, w_weights_fun, name='pred') loss = tf.subtract(output, y_output_fun, name='loss') self.opti = tf.train.AdamOptimizer(loss, name='opti') g_def.add_to_collection(tf.GraphKeys.TRAIN_OP, self.opti) # self.saver = tf.train.Saver() self.graph_obj = g_def When I want to access the Optimizer node of this graph, I would like to do this using some_graph = SimpleGraphCreater() some_graph.graph_obj.get_operation_by_name('opti') However, this name cannot be found in the operations list... (looking at some_graph.graph_obj.get_operations()) Only when I specially say in the graph that this optimizer should be added to the tf.GraphKeys.TRAIN_OP collection, am I able to get it back. Is there a more easy way? One constraint that I have though is that I can only pass graph objects... so no individual graph operations.
score: 1
has title: Tensorflor optimizer operation not found in get_operations
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/48169997
type: Question
tagged with: graph
upvote count: 1
answer count: 1
tagged with: neural-network
has answer: http://stackoverflow.com/a/48169997
favorite count: 0
tagged with: optimization

http://stackoverflow.com/comment/83275879
comment on: http://stackoverflow.com/a/48145726
score: 0
type: Comment
has text: Yes, It is in pandas object
type: AnswerComment

http://stackoverflow.com/comment/83064070
comment on: http://stackoverflow.com/q/48046350
type: Comment
type: QuestionComment
has text: Usually to capture subparts (i.e. protocol, domain, path, querystring, etc.)
score: 1

http://stackoverflow.com/comment/83317945
score: 1
has text: Have you considered NumPy's masked arrays? This sounds just the use-case for those.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48169184

http://stackoverflow.com/q/48070802
answer count: 2
has title: Regex to convert csv to pipe-separated
has comment: http://stackoverflow.com/comment/83115391
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48070888
tagged with: regex
favorite count: 0
has comment: http://stackoverflow.com/comment/83115420
has body: I have the following string: s = "XIDJIJFHD8","Gothika","a0KU000000JMYCrMAP","USA","English","Sub &amp; Audio","VOD","SD","01/01/2011 00:00:00.000000","12/31/2049 00:00:00.000000",,"Confirmed",,,,"Feature",,"2003-11-21","2004-03-23",,"R","for violence, brief language and nudity.","2024863","6000008953",,,"10.5240/A6FC-02AE-8093-3B05-6240-T","10.5240/D052-B470-0D01-25DF-DA91-4","2024863_6000008953","idwb:2024863_6000008953","CA-0000950613" I need to convert it to 'pipe-separated'. Fields are enclosed with quotations ", though if a field is empty, it won't have anything. The number of | in the final output should be 31. Here is what I have so far: re.sub(r'(\,|\")(,)(,|\")', '|', s) However, the length of the above has only 23. What would the correct regex be? Or, even better, maybe I could just do it directly in the csv module. Something like: string_with_pipes = csv.write(s, delimiter="|") Note that I just want to get a modified string, not actually save a file.
possible better answer: http://stackoverflow.com/a/48070888
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83115527
has answer: http://stackoverflow.com/a/48070886
accepted answer: http://stackoverflow.com/a/48070886
type: Question
linked to: http://stackoverflow.com/q/13120127

http://stackoverflow.com/a/48169099
score: 2
has comment: http://stackoverflow.com/comment/83787322
has comment: http://stackoverflow.com/comment/83320991
upvote count: 2
has comment: http://stackoverflow.com/comment/83323179
answers question: http://stackoverflow.com/q/48168235
has comment: http://stackoverflow.com/comment/83321240
downvote count: 0
has body: Following exactly the procedure you have described seems to work just fine for me. I start by opening a shapefile: &gt;&gt;&gt; e = shapefile.Editor('example') This file has three shapes: &gt;&gt;&gt; e.shapes() [&lt;shapefile._Shape instance at 0x7f6cb5f67dd0&gt;, &lt;shapefile._Shape instance at 0x7f6cb5f67f38&gt;, &lt;shapefile._Shape instance at 0x7f6cb5f6e050&gt;] I delete the first shape and save the file: &gt;&gt;&gt; e.delete(0) &gt;&gt;&gt; e.save('example') Now I re-open the file: &gt;&gt;&gt; e = shapefile.Editor('example') And I can see that it now has only two shapes: &gt;&gt;&gt; e.shapes() [&lt;shapefile._Shape instance at 0x7f6cb5f6e518&gt;, &lt;shapefile._Shape instance at 0x7f6cb5f6e560&gt;]
type: Answer
has comment: http://stackoverflow.com/comment/83322557

http://stackoverflow.com/a/48094774
has comment: http://stackoverflow.com/comment/83164188
type: Answer
score: 2
has body: The simplest (and imo most pythonic) way of doing this would be: b = dict(enumerate(a))
upvote count: 3
has comment: http://stackoverflow.com/comment/83165142
downvote count: 1
answers question: http://stackoverflow.com/q/48094687
has comment: http://stackoverflow.com/comment/83164147

http://stackoverflow.com/q/48016441
has answer: http://stackoverflow.com/a/48021422
has body: I am a newbie in python and django. Trying to setup django to work with Dropbox but keep getting error "'BadRequestException' object has no attribute 'get'". Here is my code. def get_dropbox_auth_flow(web_app_session): APP_KEY= '****' APP_SECRET = '****' redirect_uri = "http://localhost:8000/dropbox" return DropboxOAuth2Flow(APP_KEY, APP_SECRET, redirect_uri, web_app_session, "dropbox-auth-csrf-token") # URL handler for /dropbox-auth-start def dropbox_auth_start(request): authorize_url = get_dropbox_auth_flow(request.session).start() return HttpResponseRedirect(authorize_url) # URL handler for /dropbox-auth-finish def dropbox_auth_finish(request): try: access_token, user_id, url_state = get_dropbox_auth_flow(request.session).finish(request.GET) # oauth_result = get_dropbox_auth_flow(request.session).finish(request.query_params) except oauth.BadRequestException as e: return e except oauth.BadStateException as e: # Start the auth flow again. return HttpResponseRedirect("http://localhost:8000/dropbox_auth_start") except oauth.CsrfException as e: return HttpResponseForbidden() except oauth.NotApprovedException as e: raise e except oauth.ProviderException as e: raise e I am following the documentation here Adding traceback here
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83003837
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83002177
has comment: http://stackoverflow.com/comment/83002290
has title: Getting an error 'BadRequestException' object has no attribute 'get'
type: Question
has comment: http://stackoverflow.com/comment/83002791
answer count: 1
has comment: http://stackoverflow.com/comment/83002192
score: 0

tor
tags question: http://stackoverflow.com/q/48104071
tags question: http://stackoverflow.com/q/48054399
tag name: tor
tags question: http://stackoverflow.com/q/48117693
type: Tag

http://stackoverflow.com/comment/83033575
comment on: http://stackoverflow.com/q/48030527
has text: Fair enough! There's a bit of a learning curve to POV-Ray, it's not something that you can pick up in a couple of days. But the time you invest in it is worthwhile, IMHO, because it's so stable. I can still run POV scripts that I created over 20 years ago.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48046688
score: 1
has title: tried to install a python package but encountered "cannot find -lgcc_s" error
has body: Hi I was trying to install a python package called 'pysptk' under the Ubuntu 16.04, but when I use: pip install pysptk I have encountered the following error. /usr/bin/ld: cannot find -lgcc_s collect2: error: ld returned 1 exit status error: command 'gcc' failed with exit status 1 However, I already have gcc 4.8.5 installed as 'gcc -v' produces an output. My python version is 3.6.1 and the environment is Anaconda. I have googled the bug but reinstalling gcc and python3-dev does not work. The code easy_install pysptk will give the following output. Searching for pysptk Reading https://pypi.python.org/simple/pysptk/ Downloading https://pypi.python.org/packages/3d/86/5520242ab99426d8d9b2f18a86ed73f1be848b9fb14e57b2b81b8f17a1bb/pysptk-0.1.8.tar.gz#md5=d34133d2eaccba83f634310602721657 Best match: pysptk 0.1.8 Processing pysptk-0.1.8.tar.gz Writing /tmp/easy_install-0xk7me9z/pysptk-0.1.8/setup.cfg Running pysptk-0.1.8/setup.py -q bdist_egg --dist-dir /tmp/easy_install-0xk7me9z/pysptk-0.1.8/egg-dist-tmp-wm2zkn7r fatal: Not a git repository (or any of the parent directories): .git -- Building version 0.1.8 In file included from /home/luke/anaconda3/lib/python3.6/site- packages/numpy/core/include/numpy/ndarraytypes.h:1809:0, from /home/luke/anaconda3/lib/python3.6/site- packages/numpy/core/include/numpy/ndarrayobject.h:18, from /home/luke/anaconda3/lib/python3.6/site- packages/numpy/core/include/numpy/arrayobject.h:4, from pysptk/_sptk.c:436: /home/luke/anaconda3/lib/python3.6/site- packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp] #warning "Using deprecated NumPy API, disable it by " \ ^ /usr/bin/ld: cannot find -lgcc_s collect2: error: ld returned 1 exit status error: Setup script exited with error: command 'gcc' failed with exit status 1 Does anyone know what the problem is? I really appreciate your help! If there is any missing infor…
type: Question
upvote count: 1
has answer: http://stackoverflow.com/a/51624956
answer count: 1
downvote count: 0
favorite count: 0
tagged with: gcc
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83210496
comment on: http://stackoverflow.com/a/48115708
type: AnswerComment
score: 0
type: Comment
has text: sorry I should ask another question, if my dataframe do not have a consistent header but for example, Date2 highlow Date3 close ... using filter will not work in this case?

http://stackoverflow.com/a/48035732
accepted answer of: http://stackoverflow.com/q/48034814
type: AcceptedAnswer
upvote count: 1
type: Answer
downvote count: 0
has body: Go to facebook developers. Select your app. On the left menu choodse Facebook login -> Settings. In the "Valid OAuth redirect URI's" enter the proper URL. It your site is https://example.com and you registerd all_auth app url's under /accounts the default callback URL should look like this: https://example.com/accounts/facebook/login/callback/
answers question: http://stackoverflow.com/q/48034814
score: 1

http://stackoverflow.com/a/48100430
type: Answer
upvote count: 6
score: 6
has body: I'll try two explanations. Here's the short one. These decorators are equivalent. def attach_wrapper(obj, func=None): if func is None: return partial(attach_wrapper, obj) setattr(obj, func.__name__, func) return func def my_attach_wrapper(obj): def wrapper(func): setattr(obj, func.__name__, func) return func return wrapper And here's the long version. This is a step-by-step of what the wrapper does. @attach_wrapper(wrapper) def set_level(newlevel): level = newlevel is equivalent to: def set_level(newlevel): level = newlevel set_level = attach_wrapper(wrapper)(set_level) first, attach_wrapper(wrapper, func=None) returns a partial function that takes one argument, func. for simplicity, let's call this new function partial_attach. And we can define it like so: def partial_attach(func): setattr(wrapper, func.__name__, func) return func when attach_wrapper(wrapper, func=None) returns partial_attach, we have: set_level = partial_attach(set_level) since that returns set_level, set_level is equal to itself. But now wrapper has an attribute, set_level, which points to the same function.
accepted answer of: http://stackoverflow.com/q/48098569
answers question: http://stackoverflow.com/q/48098569
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83038335
comment on: http://stackoverflow.com/q/48034172
type: Comment
has text: Exactly. That's what I'm trying to do.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83248640
type: QuestionComment
type: Comment
has text: Well that was surprisingly easy to do! Thank you. Only problem that I ran into is that my user id on this PC doesn't have admin rights (the PC is my son's cast-off - a sign that I am getting old) so I had to sign in as him.
comment on: http://stackoverflow.com/q/48121451
score: 0

http://stackoverflow.com/q/48144477
type: Question
has title: What is the best way to save tensor value to file as binary format?
tagged with: python
linked to: http://stackoverflow.com/q/48123877
has answer: http://stackoverflow.com/a/48158098
tagged with: floating-point
answer count: 1
downvote count: 1
tagged with: tensorflow
has body: I'm trying to save tensor value to file as binary format. Especially I'm trying to save float32 tensor value as binary format(IEEE-754 format). Could you please help me ?? import tensorflow as tf x = tf.constant([[1.0, 2.0, 3.0], [5.5, 4.3, 2.5]]) # how to save tensor x as binary format ??
accepted answer: http://stackoverflow.com/a/48158098
score: 11
has comment: http://stackoverflow.com/comment/83271787
upvote count: 12
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/83271797

http://stackoverflow.com/a/48137225
upvote count: 0
has body: One good thing about windows (not sure if it exists in other OS's so please excuse me) is that it comes with a nifty GUI editor for you to change your PATH variables. Just search for 'PATH' in your start bar, from there you can check what variables are on your path and if some are missing, it allows you to add new ones very easily. Remember to restart CMD once you've done this for all changes to take effect.
answers question: http://stackoverflow.com/q/48137207
has comment: http://stackoverflow.com/comment/83256880
score: -1
has comment: http://stackoverflow.com/comment/83260628
has comment: http://stackoverflow.com/comment/99255938
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/83257337

http://stackoverflow.com/q/48085313
tagged with: pdb
downvote count: 0
accepted answer: http://stackoverflow.com/a/48087602
answer count: 1
tagged with: python
has body: I'm trying to run a test suite using python manage.py test, but I run into an error which ends like this: return self.cursor.execute(sql) django.db.utils.ProgrammingError: type "hstore" does not exist LINE 1: ..., "options" varchar(255)[] NOT NULL, "conditions" hstore NOT... I'd like to drop into the debugger at this point in order to see the full sql statement. To this end, I've run pip install django-pdb and added the following lines to my settings.py (as per the instructions): # Order is important and depends on your Django version. # With Django 1.7+ put it towards the beginning, otherwise towards the end. INSTALLED_APPS = ( ... 'django_pdb', ... ) # Make sure to add PdbMiddleware after all other middleware. # PdbMiddleware only activates when settings.DEBUG is True. MIDDLEWARE_CLASSES = ( ... 'django_pdb.middleware.PdbMiddleware', ) Then I try to re-run the test with the --pm option: python manage.py test lucy_web.tests.notifications --pm However, this is not recognized: manage.py test: error: unrecognized arguments: --pm I've also tried to run this command with --ipdb instead of --pm, but it seems to not work: I simply get an error message without dropping into the debugger. Any ideas what the issue might be? Is post mortem debugging perhaps not supported for test commands?
has title: Running django-pdb in post mortem mode for a test command
favorite count: 0
upvote count: 2
tagged with: django
has answer: http://stackoverflow.com/a/48087602
type: AnsweredQuestion
score: 2
type: Question

http://stackoverflow.com/comment/83031684
type: Comment
has text: May as well finish: jumps right to B, skips A, Z as duplicates. Checks the instance dictionary. Raises an attribute error.
type: AnswerComment
comment on: http://stackoverflow.com/a/48030727
score: 0

http://stackoverflow.com/q/48102465
linked to: http://stackoverflow.com/q/2612802
has body: I have a code that opens sample and background data (10^5 points each) and subtracts one from the other. When running the code for the first time, it works flawlessly. However, when I remove the background data and choose another file for the background, the subtraction is not performed. I found it is due to the doubling of the sample array size when executing the "subtract_bkgr_from_magn" command. What happens is that before "for i in range" the size is 100000 points but immediately after this command it becomes 200000. There's obviously something going on that I am not aware of. Could someone explain to me what is wrong with my code and how it could be rectified? import tkinter as Tk from tkinter.filedialog import askopenfilename top = Tk.Tk() class Window: def __init__(self): self.top = top self.m = [] self.m_bkgr = [] self.m_true = [] Tk.Button(top, text='Sample', command=self.open_sample, width=10).pack() Tk.Button(top, text='X', command=self.remove_bkgr).pack() Tk.Button(top, text='Background', command=self.open_bkgr, width=10).pack() Tk.Button(top, text='Calculate', command=self.calculate, width=7).pack() def openfile(self): self.opfi = askopenfilename() def calc_file_length(self): with open(self.opfi, 'r') as file: for i, l in enumerate(file): pass self.number = i + 1 def open_sample(self): self.openfile() self.calc_file_length() def open_bkgr(self): self.opbkgr = askopenfilename() def empty_arrays(self): del self.m[:], self.m_bkgr[:], self.m_true[:] def columns_for_sample(self): with open(self.opfi, 'r') as file: for line in range(self.number): g = file.readline().split('\t') if line &gt;= 7: self.magn = str(g[5]) self.m.append(eval(self.magn)) def column_for_bkgr(self): if self.opbkgr: with open(self.opbkgr, 'r') as file: for line in range(self.number): w = file.readline().split('\t') if line &gt;= 7: self.magn_bkgr = str(w[5]) self.m_bkgr.append(eval(self.magn_bkgr)) else: # no background pass def subtract_bkgr_from_magn(self): if self.opbkgr: for i in ra…
duplicate of: http://stackoverflow.com/q/2612802
has comment: http://stackoverflow.com/comment/83181922
type: UnansweredQuestion
tagged with: python
has title: Size of array doubling when using "in range"
tagged with: tkinter
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/83180294
score: 0

http://stackoverflow.com/a/48026411
answers question: http://stackoverflow.com/q/48024253
has body: This is a great opportunity to start using pathlib! from pathlib import Path p = input("Gimme a path: ") newest_mp3 = sorted(Path(p).glob('*.mp3'), reverse=True, key=lambda p: p.stat().st_mtime)[0] os.system('start "{}"'.format(newest_mp3))
score: 0
has comment: http://stackoverflow.com/comment/83038382
has comment: http://stackoverflow.com/comment/83042495
type: Answer

http://stackoverflow.com/q/48152618
has body: File "/home/shuo/.local/bin/pip", line 7, in &lt;module&gt; from pip import main File "/home/shuo/.opt/platform_venv/lib/python2.7/site-packages/pip/__init__.py", line 13, in &lt;module&gt; from pip.commands import commands, get_similar_commands, get_summaries File "/home/shuo/.opt/platform_venv/lib/python2.7/site-packages/pip/commands/__init__.py", line 6, in &lt;module&gt; from pip.commands.bundle import BundleCommand File "/home/shuo/.opt/platform_venv/lib/python2.7/site-packages/pip/commands/bundle.py", line 6, in &lt;module&gt; from pip.commands.install import InstallCommand File "/home/shuo/.opt/platform_venv/lib/python2.7/site-packages/pip/commands/install.py", line 5, in &lt;module&gt; from pip.req import InstallRequirement, RequirementSet, parse_requirements File "/home/shuo/.opt/platform_venv/lib/python2.7/site-packages/pip/req/__init__.py", line 3, in &lt;module&gt; from .req_install import InstallRequirement File "/home/shuo/.opt/platform_venv/lib/python2.7/site-packages/pip/req/req_install.py", line 32, in &lt;module&gt; from pip.locations import ( ImportError: cannot import name bin_user I'm using Ubuntu 16.04 system. Please help me fixing this problem.
has answer: http://stackoverflow.com/a/51027234
accepted answer: http://stackoverflow.com/a/51027234
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83283881
has title: How to fix 'ImportError: cannot import name bin_user'
tagged with: pip
has comment: http://stackoverflow.com/comment/84416479
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/83284170
has comment: http://stackoverflow.com/comment/83283872
type: Question

http://stackoverflow.com/a/50016797
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48152574
has body: I am using class-based views with this set-up, with one difference in my settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), } then in the API view, I have the following: from rest_framework import viewsets, permissions, authentication from oauth2_provider.contrib.rest_framework import IsAuthenticatedOrTokenHasScope, OAuth2Authentication from . import models, serializers class MyViewSet(viewsets.ModelViewSet): serializer_class = serializers.MySerializer authentication_classes = [OAuth2Authentication, authentication.SessionAuthentication] permission_classes = [IsAuthenticatedOrTokenHasScope,] required_scopes = ['scope',] It all works fine. But true, adding 'oauth2_provider.contrib.rest_framework.OAuth2Authentication' in the DEFAULT_AUTHENTICATION_CLASSES of the DRF settings did not work. It may be that the OAuth2 authentication backend throws a 401, since it does not find a Token in the AJAX request, and that it is not handled by DRF to give SessionAuthentication a second chance. I hope this gives you hints to use OAuth2 in your function-based views.
downvote count: 0

http://stackoverflow.com/q/48161676
tagged with: django-forms
type: Question
score: 5
has title: Django: NoReverseMatch at / 'myapp' is not a registered namespace
has answer: http://stackoverflow.com/a/50668435
upvote count: 5
downvote count: 0
has answer: http://stackoverflow.com/a/48163465
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/50088584
has answer: http://stackoverflow.com/a/48161779
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/50088584
type: AnsweredQuestion
tagged with: django-views
has body: I have this error during template rendering. What i'm trying to do is allow the user to upload a csv then process the data into models. error at line 109 'myapp' is not a registered namespace This is my line 109 code &lt;form action="{% url "myapp:upload_csv" %}" method="POST" enctype="multipart/form-data" class="form-horizontal"&gt; urls.py in mysite urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('anomaly.urls')), ] urls.py in anomaly urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^upload/csv/$', views.upload_csv, name='upload_csv'), ]
accepted answer: http://stackoverflow.com/a/48163465

http://stackoverflow.com/comment/83255556
score: 0
type: Comment
type: QuestionComment
has text: @JoshKisb Why little similarity? I used in both cases the natural way to read a file line-by-line. `with open('myfile.txt', 'r') as f: for l in f: ...` for Python, and this for C++: https://stackoverflow.com/a/7868998/1422096
comment on: http://stackoverflow.com/q/48138966

http://stackoverflow.com/q/48089161
tagged with: python
has comment: http://stackoverflow.com/comment/83153484
has body: I'm learning how to use selenium and I'm stuck on figuring out how to scroll down in a website to verify an element exists. I tried using the methods that was found in this question Scrolling to element using webdriver? but selenium won't scroll down the page. Instead it'll give me an error "selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: element" Heres the codes I am using moveToElement: element = driver.find_element_by_xpath('xpath') actions = ActionChains(driver) actions.move_to_element(element).perform() Scrolling into View element = driver.find_element_by_xpath('xpath') driver.execute_script("arguments[1].scrollIntoView();", element) The whole code: from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains driver = webdriver.Firefox() driver.get("https://www.linkedin.com/") element = driver.find_element_by_xpath('/html/body/div/main/div/div[1]/div/h1/img') element = driver.find_element_by_xpath('//*[@id="login-email"]') element.send_keys('') element = driver.find_element_by_xpath('//*[@id="login-password"]') element.send_keys('') element = driver.find_element_by_xpath('//*[@id="login-submit"]') element.click(); element = driver.find_element_by_xpath('') actions = ActionChains(driver) actions.move_to_element(element).perform()
has comment: http://stackoverflow.com/comment/83152827
linked to: http://stackoverflow.com/q/41744368
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83153649
has comment: http://stackoverflow.com/comment/83152967
tagged with: selenium
has answer: http://stackoverflow.com/a/48089800
has title: How to scroll down a web page to verify a specific element?
has comment: http://stackoverflow.com/comment/83152937
has answer: http://stackoverflow.com/a/48090017
has comment: http://stackoverflow.com/comment/83153112
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83153334
has comment: http://stackoverflow.com/comment/83153263
score: 0
has comment: http://stackoverflow.com/comment/83153162
has comment: http://stackoverflow.com/comment/83152987

http://stackoverflow.com/comment/113659142
comment on: http://stackoverflow.com/a/50654136
has text: As the 4 lines correspond to the `wsgi.py` file content (like mentioned in the answer), you can also just do `import your_project.wsgi.py` in any standalone python file to get your django modules bootstrapped. (For example useful for trying out snippets)
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83268701
has text: Hmmm, fo you think `.set_index(sch_inx)` should working?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48145353

http://stackoverflow.com/comment/83068378
comment on: http://stackoverflow.com/q/48048330
score: 0
type: Comment
type: QuestionComment
has text: Actually this data is to be consumed in an android app for my personal use.

http://stackoverflow.com/comment/83142562
score: 0
type: Comment
type: QuestionComment
has text: I'm voting to close this question as off-topic because it is based on a misconception.
comment on: http://stackoverflow.com/q/48083114

http://stackoverflow.com/q/48085228
type: Question
tagged with: url
has comment: http://stackoverflow.com/comment/83147125
score: 0
tagged with: blogs
has comment: http://stackoverflow.com/comment/83231903
has body: I'm rather new to Django and I've been following a tutorial on building a simple blog application. My application works fine so far (using Django 1.8.6). Here are my urls.py, views.py and models.py: urls.py urlpatterns = [ url('admin/', admin.site.urls), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), blog/urls.py urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^(?P&lt;year&gt;\d{4})/(?P&lt;month&gt;\d{2})/(?P&lt;day&gt;\d{2})/'\ r'(?P&lt;post&gt;[-\w]+)/$', views.post_detail, name='post_detail'), url(r'^tag/(?P&lt;tag_slug&gt;[-\w]+)/$', views.post_list, name='post_list_by_tag'), ] blog/views.py def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) return render(request, 'blog/post/list.html', { 'posts': posts, 'tag': tag }) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids)\ .exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags'))\ .order_by('-same_tags','-publish')[:4] return render(request, 'blog/post/detail.html', {'post': post, 'similar_posts': similar_posts}) blog/models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') tags …
tagged with: view
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Django displaying blog posts on different pages

http://stackoverflow.com/comment/83185319
type: QuestionComment
type: Comment
score: 0
has text: What is the `dtype`? `shape`?
comment on: http://stackoverflow.com/q/48104713

http://stackoverflow.com/comment/83097358
type: Comment
comment on: http://stackoverflow.com/a/48062170
score: 0
has text: Hmmm, are you angry? Because I think not, but I promise you something, so if want you can add this solution to youar answer and I remove this.
type: AnswerComment

http://stackoverflow.com/comment/83145586
score: 1
type: Comment
type: QuestionComment
has text: which version of python are you using? utf-8 should be default for python 3
comment on: http://stackoverflow.com/q/48085319

http://stackoverflow.com/q/48039690
type: AnsweredQuestion
has body: My sample code will be like this import numpy as np from io import BytesIO data = "1, 2, 3\n4, 5, 6" np.genfromtxt(data, delimiter=",") while run this code throws error Traceback (most recent call last): File "", line 1, in TypeError: a bytes-like object is required, not 'str'
score: 1
accepted answer: http://stackoverflow.com/a/48039752
has comment: http://stackoverflow.com/comment/83049867
type: Question
tagged with: numpy
has title: Numpy throws error while using genfromtxt function in python 3
has comment: http://stackoverflow.com/comment/83049858
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48039752
favorite count: 0
has comment: http://stackoverflow.com/comment/83049872
linked to: http://stackoverflow.com/q/33054527
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/83013574
type: QuestionComment
comment on: http://stackoverflow.com/q/48022243
has text: I also not getting any ERROR, could you please specify steps to reproduce it
score: 0
type: Comment

http://stackoverflow.com/q/48084482
has body: pathway.txt contains lines like this (below) a, b,0 c,8 d, dummy should print [a,d] #!/usr/bin/python3.6 def pathway(file): dict={} dummy=[] file_object=open(file, "r+") for line in file_object: a, b = line.split(',') if b == '': dummy.append(a) print (dummy) pathway("pathway.txt")
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/24285306
accepted answer: http://stackoverflow.com/a/48084535
downvote count: 2
has comment: http://stackoverflow.com/comment/83143838
type: Question
upvote count: 0
score: -2
answer count: 1
has answer: http://stackoverflow.com/a/48084535
has comment: http://stackoverflow.com/comment/83143827
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/24285306
tagged with: python
has title: print (dummy) is not printing anything. is it empty?

http://stackoverflow.com/comment/83082628
type: Comment
type: QuestionComment
has text: Keep in mind that functions and values share a namespace in python, so the `lista_caminhos` parameter to the `caminhos` function shadows the top-level `lista_caminhos` function.
comment on: http://stackoverflow.com/q/48054583
score: 0

http://stackoverflow.com/comment/83076801
score: 0
has text: @muazfaiz no, inside views. I found [this](https://www.youtube.com/watch?v=FNQxxpM1yOs&list=PLQVvvaa0QuDeA05ZouE4OzDYLHY-XH-Nd) good to get me on my feet with django because the docs are quite heavy when you're starting out.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48052296

http://stackoverflow.com/comment/83158170
has text: I cloned your GitHub project and it worked for me too. Setting `imported_members=True` in the `generate_autosummary_docs` function seems to be the key. But it is problematic that it should be necessary to edit the Sphinx source code to make it work.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48082204

http://stackoverflow.com/a/48170725
has comment: http://stackoverflow.com/comment/83321521
downvote count: 0
has comment: http://stackoverflow.com/comment/109014817
accepted answer of: http://stackoverflow.com/q/48170405
answers question: http://stackoverflow.com/q/48170405
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/109009910
has body: Dummies are any variables that are either one or zero for each observation. pd.get_dummies when applied to a column of categories where we have one category per observation will produce a new column (variable) for each unique categorical value. It will place a one in the column corresponding to the categorical value present for that observation. This is equivalent to one hot encoding. One-hot encoding is characterized by having only one one per set of categorical values per observation. Consider the series s s = pd.Series(list('AABBCCABCDDEE')) s 0 A 1 A 2 B 3 B 4 C 5 C 6 A 7 B 8 C 9 D 10 D 11 E 12 E dtype: object pd.get_dummies will produce one-hot encoding. And yes! it is absolutely appropriate to not fit the intercept. pd.get_dummies(s) A B C D E 0 1 0 0 0 0 1 1 0 0 0 0 2 0 1 0 0 0 3 0 1 0 0 0 4 0 0 1 0 0 5 0 0 1 0 0 6 1 0 0 0 0 7 0 1 0 0 0 8 0 0 1 0 0 9 0 0 0 1 0 10 0 0 0 1 0 11 0 0 0 0 1 12 0 0 0 0 1 However, if you had s include different data and used pd.Series.str.get_dummies s = pd.Series('A|B,A,B,B,C|D,D|B,A,B,C,A|D'.split(',')) s 0 A|B 1 A 2 B 3 B 4 C|D 5 D|B 6 A 7 B 8 C 9 A|D dtype: object Then get_dummies produces dummy variables that are not one-hot encoded and you could theoretically leave the intercept. s.str.get_dummies() A B C D 0 1 1 0 0 1 1 0 0 0 2 0 1 0 0 3 0 1 0 0 4 0 0 1 1 5 0 1 0 1 6 1 0 0 0 7 0 1 0 0 8 0 0 1 0 9 1 0 0 1
type: Answer
score: 31
upvote count: 31

http://stackoverflow.com/comment/83160737
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48018162
has text: thank u guys, actually my company group policy overlaps with my setting n thats why I was failed to screen unlock. But I found one app 'https://downloads.tomsguide.com/Dont-Sleep,0301-28162.html' which solved my issue :)

http://stackoverflow.com/a/48043178
answers question: http://stackoverflow.com/q/48043091
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48043091
has body: I am not 100% sure but I think I had this problem a while back and it could be something to do with the microphone source. You can fix it by... change all instances of Microphone() to Microphone(device_index=MICROPHONE_INDEX), where MICROPHONE_INDEX is the hardware-specific index of the microphone To figure out what the value of MICROPHONE_INDEX should be, run the following code: import speech_recognition as sr for index, name in enumerate(sr.Microphone.list_microphone_names()): print("Microphone with name \"{1}\" found for `Microphone(device_index={0})`".format(index, name)) This will print out something like the following: Microphone with name "HDA Intel HDMI: 0 (hw:0,3)" found for `Microphone(device_index=0)` Microphone with name "HDA Intel HDMI: 1 (hw:0,7)" found for `Microphone(device_index=1)` Microphone with name "HDA Intel HDMI: 2 (hw:0,8)" found for `Microphone(device_index=2)` Microphone with name "Blue Snowball: USB Audio (hw:1,0)" found for `Microphone(device_index=3)` Microphone with name "hdmi" found for `Microphone(device_index=4)` Microphone with name "pulse" found for `Microphone(device_index=5)` Microphone with name "default" found for `Microphone(device_index=6)` Now, for example, to use the Snowball microphone, you would change Microphone() to Microphone(device_index=3). I hope this helped :)
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48128411
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48128261
type: Answer
answers question: http://stackoverflow.com/q/48128261
downvote count: 0
has comment: http://stackoverflow.com/comment/83233634
score: 3
has comment: http://stackoverflow.com/comment/83233617
has comment: http://stackoverflow.com/comment/83233580
has comment: http://stackoverflow.com/comment/83233547
upvote count: 3
has comment: http://stackoverflow.com/comment/83233526
has body: The position of the bars is a bit off. You insert the first label group at [0, 1, 2] (index), the second on [0.45, 1.45, 2.45] (index + bar_width) and the third at [0.9, 1.9, 2.9] (index + 2*bar_width). Each bar has a width of 0.45 so no wonder these overlap. For the following part I chose just some data for visualization, you have to insert or use the correct values. If you change bar_width to 1/3 then there's no empty space between the groups: bar_width = 1 / 3 If you choose something like 1/4 then it will have exactly the space for one additional bar between each group: bar_width = 1 / 4 But the label isn't centered correctly yet, but that can be easily fixed by using a new index in plt.xticks: bar_width = 1 / 4 plt.xticks(index + bar_width, ('Tariff Market', 'Wholesale Market', 'Balancing Market'))

http://stackoverflow.com/comment/83060445
score: 0
type: Comment
type: QuestionComment
has text: Your code has no regard for types. `str`s get arithmetic operations whereas `int`s are trying to be concatenate with `str`s.
comment on: http://stackoverflow.com/q/48044687

http://stackoverflow.com/comment/83044776
score: 1
comment on: http://stackoverflow.com/q/48037224
has text: AFAI can tell, you could go from quadratic to linear time complexity simply by turning `unique_idx` into a `set`: `unique_idx, locations = set(), {}` and `unique_idx.add(_id)`
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83059311
comment on: http://stackoverflow.com/q/48043891
has text: Nice, data could have been text but you provided some "example data" - now wait and watch the SO magic happen :) +1
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/48051128
type: Answer
upvote count: 1
score: 1
has body: The pipe character ("|") is not allowed in Windows filenames either. Source: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
downvote count: 0
answers question: http://stackoverflow.com/q/48051104

http://stackoverflow.com/a/48119537
type: Answer
has comment: http://stackoverflow.com/comment/83223189
upvote count: 4
has comment: http://stackoverflow.com/comment/89306930
accepted answer of: http://stackoverflow.com/q/48118537
answers question: http://stackoverflow.com/q/48118537
score: 4
has body: Here's one way: mask = (((df['criteria_1'] &gt;=1.0) | (df['criteria_2'] &gt;=2.0)) &amp; (df['criteria_3'] &gt;=90.0) &amp; (df['criteria_4'] &lt;=180.0) &amp; ((df['criteria_5'].notnull()) &amp; (df['criteria_6'].notnull()))) # reset_index() defaults to drop=False. It inserts the old index into the DF # as a new column named 'index'. idx = df.reset_index()[mask].groupby('id').first().reset_index(drop=True)['index'] df['flag'] = df.index.isin(idx).astype(int)
type: AcceptedAnswer
downvote count: 0

email-validation
tags question: http://stackoverflow.com/q/48019851
type: Tag
tag name: email-validation

http://stackoverflow.com/comment/83250387
has text: The error message indicates a library version mismatch. So, the tutorial might not be right. Can you try Python 3.4?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48135310
score: 0

http://stackoverflow.com/a/48024709
has comment: http://stackoverflow.com/comment/83018871
score: 6
answers question: http://stackoverflow.com/q/48024682
has comment: http://stackoverflow.com/comment/83019012
has comment: http://stackoverflow.com/comment/83018958
has comment: http://stackoverflow.com/comment/83018805
has comment: http://stackoverflow.com/comment/83018729
has comment: http://stackoverflow.com/comment/83018774
has body: You can use any: names = ["John Lennon (Beatle)", "Paul McCartney (Beatle)", "Ringo Starr (Beatle)", "Yoko Ono (Beatle)", "Mick Jagger (Rolling Stone)", "Brian Jones (Rolling Stone)", "Alex Jones (na)", "Adam Smith (na)"] names1 = [i for i in names if any(b in i for b in ['(Beatle)', 'Paul', 'Yoko','Ringo'])] ideal_names = names1 or [i for i in names if 'Mick' in i] Output: ['John Lennon (Beatle)', 'Paul McCartney (Beatle)', 'Ringo Starr (Beatle)', 'Yoko Ono (Beatle)']
downvote count: 0
has comment: http://stackoverflow.com/comment/83018890
type: Answer
upvote count: 6

http://stackoverflow.com/q/48059904
has title: Extract step pulse from 1D signal for object segmentation
type: Question
has answer: http://stackoverflow.com/a/48060742
score: 0
tagged with: image-segmentation
tagged with: vector
answer count: 1
tagged with: python
has body: I have 1D vector and i want to get the start and the end locations of the rectangle signal inside (highlighted in the images below). I am using python, and this signal is a histogram of white pixels inside a binary image on y-axis. I am trying to get the ROI of the object without the noise around it.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48060742

http://stackoverflow.com/comment/83080828
score: 0
type: QuestionComment
has text: Also, when using a custom model manager, you should explicitly assign the defautl manager `objects = models.Manager()` if you want to retrieve all objects.
comment on: http://stackoverflow.com/q/48053283
type: Comment

http://stackoverflow.com/comment/83098755
score: 22
comment on: http://stackoverflow.com/q/48062499
type: Comment
type: QuestionComment
has text: This is because your data are _strings_.

http://stackoverflow.com/q/48039657
score: 3
has comment: http://stackoverflow.com/comment/83049755
has answer: http://stackoverflow.com/a/48039677
has body: I am wondering how I can take only positive values in a list in Python. For example, if I have A = [1, 2, 3], it should return [1, 2, 3] If I have A = [-1, 2, 3], it should return [2, 3] if I have A = [-1, -2], it should return None Thank you very much!
upvote count: 6
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/83049751
answer count: 3
has comment: http://stackoverflow.com/comment/83049783
has answer: http://stackoverflow.com/a/48039664
has comment: http://stackoverflow.com/comment/83049776
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83049845
has answer: http://stackoverflow.com/a/48039679
has title: How to take only positive values in a list in Python?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83049757
linked to: http://stackoverflow.com/q/46251689

http://stackoverflow.com/comment/83144489
score: 0
type: Comment
type: QuestionComment
has text: The OS *distributes* the processes to the various CPUs. How can you tell that only one CPU is being used?
comment on: http://stackoverflow.com/q/48084341

arabic
tags question: http://stackoverflow.com/q/48150638
type: Tag
tag name: arabic

http://stackoverflow.com/comment/83121457
type: Comment
score: 0
type: AnswerComment
has text: Error occurs when my code reached to conn.request("GET","/")
comment on: http://stackoverflow.com/a/48073076

http://stackoverflow.com/comment/83114157
type: Comment
type: QuestionComment
score: 6
comment on: http://stackoverflow.com/q/48070146
has text: Use enumerate https://docs.python.org/3.5/library/functions.html#enumerate

http://stackoverflow.com/comment/83050867
has text: well to simplify leaving the detection side out... if I simply have coordinates on the screen. Position x,y and I want to draw a box around that. can it be done in python?
comment on: http://stackoverflow.com/a/48039976
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48079442
answer count: 3
has answer: http://stackoverflow.com/a/48079554
favorite count: 0
has body: My question is why the following syntax produces the correct answer for house robber: last, now = 0, 0 for element in nums: last, now = now, max(last + element, now) return now vs the same thing, but not inline: last, now = 0, 0 for element in nums: last = now now = max(last + element, now) return now I expect they should be the same. I traced this out though (in the second snippet) and it is giving me the wrong answer. For example: in an array [3, 5, 3] my given answer for the second code snippet will be 11 - it will just keep adding things. I'm obviously missing something about the inline capabilities of python. Is there anyone that could provide some insight? Thank You.
has answer: http://stackoverflow.com/a/48079531
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83132897
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48079554
score: 1
possible better answer: http://stackoverflow.com/a/48079527
has title: House robber - Python Syntax
has comment: http://stackoverflow.com/comment/83132782
has answer: http://stackoverflow.com/a/48079527
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/83132762

http://stackoverflow.com/a/48051821
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48051766
score: 2
has body: This modified code got me the href together with the data from bs4 import BeautifulSoup content=""" 1964 Townes, Charles HardCharles Hard Townes; Basov, NikolayNikolay Basov; Prokhorov, AlexanderAlexander Prokhorov Hodgkin, DorothyDorothy Hodgkin Bloch, Konrad EmilKonrad Emil Bloch; Lynen, Feodor Felix KonradFeodor Felix Konrad Lynen Sartre, Jean-PaulJean-Paul Sartre[D] King, Jr., Martin LutherMartin Luther King, Jr. — """ soup = BeautifulSoup(content,"lxml") for items in soup.select('tr'): item_name = [[item.text,item.get('href')] for item in items.select(".fn a")] print(item_name) OUTPUT [['Charles Hard Townes', '/wiki/Charles_Hard_Townes'], ['Nikolay Basov', '/wiki/Nikolay_Basov'], ['Alexander Prokhorov', '/wiki/Alexander_Prokhorov'], ['Dorothy Hodgkin', '/wiki/Dorothy_Hodgkin'], ['Konrad Emil Bloch', '/wiki/Konrad_Emil_Bloch'], ['Feodor Felix Konrad Lynen', '/wiki/Feodor_Felix_Konrad_Lynen'], ['Jean-Paul Sartre', '/wiki/Jean-Paul_Sartre'], ['Martin Luther King, Jr.', '/wiki/Martin_Luther_King,_Jr.']]
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48051766

http://stackoverflow.com/q/48086938
accepted answer: http://stackoverflow.com/a/48087058
tagged with: python
has answer: http://stackoverflow.com/a/48087033
has comment: http://stackoverflow.com/comment/83148798
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/83149002
possible better answer: http://stackoverflow.com/a/48087033
downvote count: 1
has body: I am trying to build a BlackJack game. The program starts, and uses the random module to generate 2 different numbers which tells you which card you have. Number 1 is the value, e.g. 8 Number 2 is the suit, e.g. 4 = Spades The program gives me 2 cards sometimes, and the other half the time it gives me one card. Question: Why is this program not working as desired? types = [" of Spades", " of Diamonds", " of Clubs", " of Hearts"] special = ["King", "Queen", "Jack", "Ace"] tries = 0 import random import time print("Welcome to BlackJack.") time.sleep(1) print("Let's Begin.") time.sleep(1) while tries &lt; 1: cardnumber1 = random.randint(2, 13) random.shuffle(types) random.shuffle(special) cardnumber2 = random.randint(2, 13) random.shuffle(special) random.shuffle(types) cardnumber3 = random.randint(2, 9) random.shuffle(special) random.shuffle(types) cardnumber4 = random.randint(2, 9) random.shuffle(special) random.shuffle(types) cardtype1 = random.choice(types) random.shuffle(special) random.shuffle(types) cardtype2 = random.choice(types) random.shuffle(special) random.shuffle(types) cardtype3 = random.choice(types) random.shuffle(special) random.shuffle(types) cardtype4 = random.choice(types) random.shuffle(special) random.shuffle(types) cardspecial = random.choice(special) random.shuffle(special) random.shuffle(types) cardspecial2 = random.choice(special) random.shuffle(special) random.shuffle(types) if cardnumber1 &gt; 10: print(str(cardnumber3) + cardtype1) tries = tries + 1 if cardnumber2 &gt; 10: print(str(cardnumber4) + cardtype2) tries = tries + 1 if cardnumber1 &lt; 9: print(cardspecial + cardtype3) tries = tries + 1 if cardnumber2 &lt; 9: print(cardspecial2 + cardtype4) tries = tries + 1
has comment: http://stackoverflow.com/comment/83148939
has title: My program isn't showing 2 answers in a loop that stops only when two answers are given
has answer: http://stackoverflow.com/a/48087058
type: AnsweredQuestion
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83148905
has comment: http://stackoverflow.com/comment/83148946
type: Question
has comment: http://stackoverflow.com/comment/83148863
has comment: http://stackoverflow.com/comment/83148998
has comment: http://stackoverflow.com/comment/83148967

http://stackoverflow.com/comment/83079508
type: AnswerComment
has text: So does that mean that you can run Javascript from a background thread in Qt Quick, but not Python or C++?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48053463

http://stackoverflow.com/comment/83334428
type: Comment
comment on: http://stackoverflow.com/a/48122040
has text: Obviously, have you taken a look at the accepted answer?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83272430
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48147050
has text: @khelwood looks like that fixes it. thx
score: 0

http://stackoverflow.com/q/48049189
has answer: http://stackoverflow.com/a/48049848
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48049214
has body: I am trying to extract the number from the URL. Here is the code I tried: urlss = 'http://www.deyi.com/thread-24488-1-1.html' urlss = re.sub('http://www.deyi.com/thread-(.*?)-1-1.html', '', urlss) print(urlss) My expected result is the below number: 24488 How can I achieve this?
upvote count: 1
tagged with: python
downvote count: 1
has title: Regex to extract specific number from the URL based on the URL pattern
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48049214
type: Question
answer count: 2
favorite count: 0
score: 0
possible better answer: http://stackoverflow.com/a/48049848
tagged with: regex

http://stackoverflow.com/comment/133584970
has text: where is payload?
comment on: http://stackoverflow.com/a/48158940
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83046643
comment on: http://stackoverflow.com/a/48033904
score: 0
has text: Thanks...I'll check this out in depth after the weekend. much appreciated
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48052811
has comment: http://stackoverflow.com/comment/83077859
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48052710
has body: First approach, without the global var, returning value: def increase_score (aValue, aScore): aScore += aValue return aScore def pass_score(test_string, aScore): if re.match(a, test_string): aScore = increase_score(5, aScore) print (aScore) Second approach, using global var: score = 0 def increase_score (aValue): #don't need to receive score, I've it. global score score += aValue def pass_score(test_string): global score if re.match(a, test_string): increase_score(5) print (score) I guess you need a mix of both. Any case, your code looks a bit dirty at this moment, mixing local and global vars.
downvote count: 0

http://stackoverflow.com/a/48095698
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: Okay since all the possible values are known in advance. Then below is a slightly hackish way of doing it. import numpy as np import pandas as pd # This is a one time process # Keep all the possible data here in lists # Can add other categorical variables too which have this type of data all_possible_states= ['AL', 'MS', 'MS', 'OK', 'VA', 'NJ', 'NM', 'CD', 'WY'] all_possible_cities= ['A', 'B', 'C', 'D', 'E', 'G', 'Z', 'F'] # Declare our transformer class from sklearn.base import BaseEstimator, TransformerMixin from sklearn.preprocessing import LabelEncoder, OneHotEncoder class MyOneHotEncoder(BaseEstimator, TransformerMixin): def __init__(self, all_possible_values): self.le = LabelEncoder() self.ohe = OneHotEncoder() self.ohe.fit(self.le.fit_transform(all_possible_values).reshape(-1,1)) def transform(self, X, y=None): return self.ohe.transform(self.le.transform(X).reshape(-1,1)).toarray() # Allow the transformer to see all the data here encoders = {} encoders['state'] = MyOneHotEncoder(all_possible_states) encoders['city'] = MyOneHotEncoder(all_possible_cities) # Do this for all categorical columns # Now this is our method which will be used on the incoming data def encode(df): tup = (encoders['state'].transform(df['state']), encoders['city'].transform(df['city']), # Add all other columns which are not to be transformed df'age') return np.hstack(tup) # Testing: day1_data = pd.DataFrame({'state': ['MS', 'OK', 'VA', 'NJ', 'NM'], 'city': ['C', 'B', 'G', 'Z', 'F'], 'age': [27, 19, 63, 40, 93]}) print(encode(day1_data)) [[ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 27.] [ 0. 0. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 19.] [ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 63.] [ 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 40.] [ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 93.]] day2_data = pd.DataFrame({'state': ['AL', 'WY', 'VA'], 'city': ['A', 'B', 'E'], 'age': [42, 52, 73]}) print(encode(day2_data)) [[ 1. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. …
accepted answer of: http://stackoverflow.com/q/48034035
answers question: http://stackoverflow.com/q/48034035
type: AcceptedAnswer

http://stackoverflow.com/a/48058495
upvote count: 1
has comment: http://stackoverflow.com/comment/83090296
score: 1
has comment: http://stackoverflow.com/comment/83102628
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48053060
accepted answer of: http://stackoverflow.com/q/48053060
type: Answer
has body: The best way to accomplish that is inserting inputs with the same name and then in Django get all those inputs as a list like: def view(request): inputs = request.POST.getlist('your_input_name') for i in inputs: Model.objects.create() # Save your model

mayavi
tags question: http://stackoverflow.com/q/48023267
type: Tag
tag name: mayavi

http://stackoverflow.com/comment/83204248
has text: You can be notified if the content has GST using regrex. But, you also need the details of that particular news. What exactly do you mean by details? location of the word in the page? or link to that news?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48113622

http://stackoverflow.com/comment/83193429
comment on: http://stackoverflow.com/a/48090774
has text: @Prabu That's not how this site works. If you have another problem, please open a new question. Each post is meant for a separate, atomic query.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48029204
has answer: http://stackoverflow.com/a/48029293
accepted answer: http://stackoverflow.com/a/48029293
duplicate of: http://stackoverflow.com/q/45766736
has comment: http://stackoverflow.com/comment/83028624
score: -1
has comment: http://stackoverflow.com/comment/83028559
linked to: http://stackoverflow.com/q/45766736
has comment: http://stackoverflow.com/comment/83028571
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83028519
favorite count: 0
tagged with: python
has body: I'm having a bit of trouble understanding a couple of things regarding recursive functions in Python (well, I guess in general). I tried looking for the answer but wasn't sure how to look for it either. Taking the recursive function example most common when I search: def sfactorr(j): if j == 1: return 1 else: return j * sfactorr(j-1) each time the function is greater than 1, it starts again until j == 1. But when it hits 1, shouldn't the return value be 1? Obviously when you run it you get the result of the whole function, but I don't seem to fully understand why that is. In other words, how come it returns the correct value and not the one the base condition is returning? Thanks
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83028763
has title: Return Value for Recursive Functions in Python
downvote count: 1
type: Question
tagged with: recursion

http://stackoverflow.com/comment/83129653
score: 0
type: QuestionComment
type: Comment
has text: I use 64 bit windows 7. No I didnt get any message in this version(32 bit). but it did in amd_64 bit file
comment on: http://stackoverflow.com/q/48076805

http://stackoverflow.com/comment/83209238
has text: Once you print it to stdout the data is beyond the control of your program. Put the values in a list and sort the list before outputting.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48116533

http://stackoverflow.com/q/48085512
has answer: http://stackoverflow.com/a/48085626
has answer: http://stackoverflow.com/a/48085745
score: 0
has answer: http://stackoverflow.com/a/48085570
has comment: http://stackoverflow.com/comment/83146846
has comment: http://stackoverflow.com/comment/83146065
has body: I have this: list = ['h', 'e', "'", 'l', 'l', 'o'] And I want to have this: list = ['h', "e'", 'l', 'l', 'o'] I want to join only two list elements. How can I do that?
favorite count: 0
has answer: http://stackoverflow.com/a/48085592
answer count: 5
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48088203
has comment: http://stackoverflow.com/comment/83146022
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48085592
has comment: http://stackoverflow.com/comment/83146100
has title: How to join two items in a Python list?
has comment: http://stackoverflow.com/comment/83146020
possible better answer: http://stackoverflow.com/a/48085570

http://stackoverflow.com/a/48122931
answers question: http://stackoverflow.com/q/48122904
accepted answer of: http://stackoverflow.com/q/48122904
type: AcceptedAnswer
downvote count: 0
upvote count: 2
has body: You're on the right track. Use groupby + count - v = df.groupby(['source', 'target']).source.count() You could also use size, but note that size also counts NaN entries (count does not) - v = df.groupby(['source', 'target']).size() Now, find the sum along the 0th index level, and divide the original amount by this sum - v / v.sum(level=0) * 100 source target a b 66.666667 c 33.333333 b d 75.000000 e 25.000000 Name: source, dtype: float64 If you want the % symbol on the right of the percentages, convert to string - (v / v.sum(level=0) * 100).round(2).astype(str) + '%' source target a b 66.67% c 33.33% b d 75.0% e 25.0% Name: source, dtype: object
type: Answer
score: 2

http://stackoverflow.com/comment/83267112
type: QuestionComment
comment on: http://stackoverflow.com/q/48143929
has text: Is the only [solution](https://stackoverflow.com/a/18337754) to use `json.dumps`, or is there a way of using `json.dump`?
score: 0
type: Comment

http://stackoverflow.com/comment/83323176
comment on: http://stackoverflow.com/q/48167216
has text: @BenjaminW. In a very straightforward manner: `cron = CronTab(tabfile=filename, user=False)`.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83253453
type: Comment
type: AnswerComment
has text: @rnso Thank you!
score: 0
comment on: http://stackoverflow.com/a/48137517

http://stackoverflow.com/comment/83061763
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/48045302
type: Comment
has text: Please include a full stack trace.

http://stackoverflow.com/a/48169942
answers question: http://stackoverflow.com/q/48169885
upvote count: 1
type: Answer
downvote count: 0
has body: replace print(random.randint(0,1)) with print(random.randint(0,1), end=""). See https://docs.python.org/3/tutorial/inputoutput.html
score: 1

http://stackoverflow.com/a/48039222
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48038949
has comment: http://stackoverflow.com/comment/83105759
type: Answer
score: 6
answers question: http://stackoverflow.com/q/48038949
upvote count: 6
has body: You should be able to calculate the difference between open and close values, and divide by the relevant multiplier for the pair. Like this: def pip_calc(open, close): if str(open).index('.') &gt;= 3: # JPY pair multiplier = 0.01 else: multiplier = 0.0001 pips = round((close - open) / multiplier) return int(pips) pip_calc(112.65, 112.68) # 3 pip_calc(1.6566, 1.6568) # 2

http://stackoverflow.com/q/48036741
favorite count: 0
has answer: http://stackoverflow.com/a/70109532
tagged with: python
accepted answer: http://stackoverflow.com/a/70109532
type: AnsweredQuestion
has title: Acceptance-rate in PyMC3 (Metropolis-Hastings)
possible better answer: http://stackoverflow.com/a/67345074
tagged with: pymc3
upvote count: 2
downvote count: 2
type: Question
has answer: http://stackoverflow.com/a/48042507
has body: Does anyone know how I can see the final acceptance-rate in PyMC3 (Metropolis-Hastings) ? Or in general, how can I see all the information that pymc3.sample() returns ? Thanks
has comment: http://stackoverflow.com/comment/83262746
has answer: http://stackoverflow.com/a/67345074
score: 0
answer count: 3

http://stackoverflow.com/q/48052572
has answer: http://stackoverflow.com/a/48052588
has title: Creating a Backup Dataframe from Entries Discarded by Pandas drop_duplicates()
tagged with: pandas
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48052588
tagged with: python
has body: I have a Pandas dataframe, ds. And I would like to drop duplicate entries from a particular column, named 'Name'. +---------+------+-------+----------+--------+ | Invoice | Name | Price | Date | Coupon | +---------+------+-------+----------+--------+ | 123412 | Jim | 50 | 12/01/17 | ALBB1 | | 431311 | Jane | 25 | 12/02/17 | BB2 | | 134123 | Joe | 70 | 12/03/17 | BB2 | | 333131 | Jim | 85 | 12/04/17 | ALBB1 | +---------+------+-------+----------+--------+ Here is my code: ds = ds.drop_duplicates(subset='Name', keep='first') I am using the keep='first' option to keep the first instance found in the dataframe. What I would like to do is to create a separate dataframe from all the discarded entries. So, in this example. The second dataframe, ds2, would be equal to: +---------+------+-------+----------+--------+ | Invoice | Name | Price | Date | Coupon | +---------+------+-------+----------+--------+ | 333131 | Jim | 85 | 01/04/18 | ALBB1 | +---------+------+-------+----------+--------+
score: 0
answer count: 1

http://stackoverflow.com/q/48149945
has answer: http://stackoverflow.com/a/48150482
has title: How can I show data one after another in django models
type: Question
has answer: http://stackoverflow.com/a/48150009
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83278373
has body: I am Using Django Framework in my project. I want the results that start with query first then results that contain query next but when I am using the following code it is giving mixed results instead of one after other. How can I achieve My requirement collections = TokenCollection.objects.filter(Q(title__istartswith=query) | Q(title__icontains=query))
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/83166637
type: QuestionComment
comment on: http://stackoverflow.com/q/48095895
has text: Where do you call either of these functions? What has the JSON file got to do with anything? Neither of these functions return anything so how do you get any output at all? Please read [How to ask](https://stackoverflow.com/help/asking) and edit your question to make it something that can be answered.
score: 0
type: Comment

http://stackoverflow.com/q/48142104
upvote count: 0
has comment: http://stackoverflow.com/comment/83262358
has comment: http://stackoverflow.com/comment/83263520
answer count: 1
has comment: http://stackoverflow.com/comment/83262815
has comment: http://stackoverflow.com/comment/83284825
tagged with: python
tagged with: python-2.x
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83262288
score: -3
has answer: http://stackoverflow.com/a/48143006
has title: tkinter: set askopenfilename to entry
downvote count: 3
has body: I'm trying to set askopenfilename to entry box. But I don't know how to do it. import Tkinter as tk from tkFileDialog import * import ttk class ESA(tk.Tk): def __init__(self,*args,**kwargs): tk.Tk.__init__(self,*args,**kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames={} for f in (newProject, existingProject, exportProject): frame = f(container, self) self.frames[f] = frame frame.grid(row=0, column=0, sticky = "nsew") self.show_frame(newProject) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class newProject(tk.Frame): def load_file(self): global fname,logo self.fname = askopenfilename(initialdir=r"C:\Users", filetypes=( ('JPEG / JFIF','*.jpg'), ('Portable Network Graphics','*.png'), ('Windows Bitmap','*.bmp'), ("All files", "*.*"))) newProject.__init__.clientLogoEntry.delete(0, END) newProject.__init__.clientLogoEntry.insert(0, self.fname) def __init__(self, parent, controller): tk.Frame.__init__(self,parent) stepOne = tk.LabelFrame(self, text=" 1. Configuration:") stepOne.grid(row=1, columnspan=7, sticky='WE', \ padx=5, pady=5, ipadx=5, ipady=5) logo = tk.StringVar() clientLogoEntry = tk.Entry(stepOne, textvariable=logo) clientLogoEntry.grid(row=4, column=1, sticky="WE", pady=2) stepOne.button = tk.Button(stepOne, text="Browse...", command=self.load_file, width=10) stepOne.button.grid(row=4, column=7, sticky="W") It's giving me this error File "C:\Users\Vincent Law\Desktop\23.py", line 36, in load_file newProject.__init__.clientLogoEntry.delete(0, END) AttributeError: 'function' object has no attribute 'clientLogoEntry'
type: Question

http://stackoverflow.com/comment/83143677
has text: https://gist.github.com/jakemmarsh/8273963
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48084192

http://stackoverflow.com/q/48086073
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83148394
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has title: Python3 function with pandas dataframe input runs slower then 1st time and faster the 2nd time
has comment: http://stackoverflow.com/comment/83147128
tagged with: python
has body: I built 2 functions major_check_with_dataframe and major_check_with_list, and I wanted to see which one runs faster. I'm puzzled by their run time. import numpy as np DTYPE_FLOAT = np.float import anapyfunc.major import pandas as pd from testpython.timer import timer # wrapper function def major_check(**kwargs): #return major_check_with_list(**kwargs) return major_check_with_dataframe(**kwargs) # functions to be timed def major_check_with_dataframe(df, s_major_single_hi_percent, s_major_single_lo_percent): ... def major_check_with_list(source_list, s_major_single_hi_percent, s_major_single_lo_percent): ... # main function starts here t = timer.Timer(verbose = True, run = False) t.set_name(name = 'major check timer') a = np.random.choice(101, 2500) b = np.random.choice(101, 2500) c = np.random.choice(101, 2500) s_major_single_hi_percent = 70 s_major_single_lo_percent = 10 dd = {'a' : a, 'b' : b , 'c' : c} df = pd.DataFrame(dd) # axis 0 = tick # axis 1 = input arrays t.set_name(name = 'major_check_with_dataframe') t.start() ret1 = anapyfunc.major.major_check_with_dataframe( df = df, s_major_single_hi_percent = s_major_single_hi_percent, s_major_single_lo_percent = s_major_single_lo_percent, ) t.stop_reset() t.set_name(name = 'major_check_with_list') t.start() ret2 = anapyfunc.major.major_check_with_list( source_list = [a, b, c,], s_major_single_hi_percent = s_major_single_hi_percent, s_major_single_lo_percent = s_major_single_lo_percent, ) t.stop_reset() t.set_name(name = 'major_check') t.start() ret3 = anapyfunc.major.major_check( #source_list = [a, b, c,], df = df, s_major_single_hi_percent = s_major_single_hi_percent, s_major_single_lo_percent = s_major_single_lo_percent, ) t.stop_reset() Output when major_check calls major_check_with_dataframe major_check_with_dataframe elapsed time: 94.261000 ms major_check_with_list elapsed time: 2.316000 ms major_check elapsed time: 3.055000 ms Output when major_check calls major_check_with_list major_check_with_dataframe elaps…
tagged with: performance
type: Question
has comment: http://stackoverflow.com/comment/83147315
tagged with: function
has comment: http://stackoverflow.com/comment/83147344

http://stackoverflow.com/comment/83257005
has text: you can't create it with `pack()` - but you can create frame using `pack()` and then inside frame you can use `grid()`.
score: 1
comment on: http://stackoverflow.com/a/48139178
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48069621
has comment: http://stackoverflow.com/comment/83150795
has comment: http://stackoverflow.com/comment/83213733
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48069579
has body: Just do this n = '1234567890' for i in range(len(n)): print(n[i:i+5]) this should do the trick. But I need to say that it is hard to believe you actually search the Internet because it is a frequently asked question... UPDATE if you want to use the different slices you can try this: n = '1234567890' ar= [None]*len(n) for i in range(len(n)): if len(n[i:i+5]) == 5: ar[i] = n[i:i+5] else: del ar[i:-1] del ar[-1] break for i in ar: print(i) So what happens here is: You make an array that has the size of the string and fill them with None values You check if the remaining size of the string is 5 pieces long if so you slice the string in pieces of 5 with [i:i+5] and do the check again for the next slices if not you delete the remaining None values and break the loop

http://stackoverflow.com/comment/83211551
type: Comment
has text: Possible duplicate of [How to parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date)
comment on: http://stackoverflow.com/q/48117256
score: 0
type: QuestionComment

http://stackoverflow.com/q/48031026
has answer: http://stackoverflow.com/a/48031100
has body: I am cleaning a dataset, and have a field gender. In this field, there are entries such as Male, male, and MALE. To resolve this, I am trying to update my MongoDB database using pymongo. In the database, the Gender attribute is Gender (which a capital G at the front) My code currently looks like this: import pymongo from pymongo import MongoClient db_info = { 'db_name': 'MentalHealth', 'collection_name': 'MentalHealth', } if __name__ == "__main__": mongo_client = MongoClient() mongo_db = mongo_client[db_info['db_name']] mongo_collection = mongo_db[db_info['collection_name']] #normalize to lowercase mongo_collection.aggregate([{ '$project': { 'Gender':{ '$toLower':"$Gender"}}}]) The code runs without issue, but the database is not updating, and I am unsure what is the error with the code. Any help would be greatly appreciated. Thank you!!!
has comment: http://stackoverflow.com/comment/83057308
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3974985
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48031256
duplicate of: http://stackoverflow.com/q/3974985
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83057416
has title: PyMongo - Setting all values in an attribute to lowercase
has comment: http://stackoverflow.com/comment/83046479
answer count: 3
tagged with: pymongo
has answer: http://stackoverflow.com/a/48031117
tagged with: mongodb
has comment: http://stackoverflow.com/comment/83032343
has comment: http://stackoverflow.com/comment/83050716
has answer: http://stackoverflow.com/a/48031256
possible better answer: http://stackoverflow.com/a/48031100
has comment: http://stackoverflow.com/comment/83057626
downvote count: 0

http://stackoverflow.com/comment/83268984
type: AnswerComment
score: 0
type: Comment
has text: @jezrael the edited answer won't work thats the reason I used `set_index`
comment on: http://stackoverflow.com/a/48145069

http://stackoverflow.com/comment/83275537
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48148619
has text: No I don't know where I can see that. Into `/var/log/syslog`?

http://stackoverflow.com/comment/83004959
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48017666
score: 1
has text: You could try using the internal `sre_parse` module – `list(sre_parse.parse(r"{")) == list(sre_parse.parse(r"\{"))`.

http://stackoverflow.com/comment/83095664
type: QuestionComment
has text: @Reti43 Unless `numpy` optimises, that is *extremely* inefficient
score: 0
comment on: http://stackoverflow.com/q/48061508
type: Comment

algorithm
tags question: http://stackoverflow.com/q/48126065
tags question: http://stackoverflow.com/q/48109624
tags question: http://stackoverflow.com/q/48095978
tags question: http://stackoverflow.com/q/48092288
tag name: algorithm
tags question: http://stackoverflow.com/q/48045217
tags question: http://stackoverflow.com/q/48099239
tags question: http://stackoverflow.com/q/48061766
tags question: http://stackoverflow.com/q/48028385
tags question: http://stackoverflow.com/q/48120431
tags question: http://stackoverflow.com/q/48162081
tags question: http://stackoverflow.com/q/48066606
tags question: http://stackoverflow.com/q/48072904
tags question: http://stackoverflow.com/q/48084884
tags question: http://stackoverflow.com/q/48046055
tags question: http://stackoverflow.com/q/48129418
tags question: http://stackoverflow.com/q/48052322
tags question: http://stackoverflow.com/q/48095508
tags question: http://stackoverflow.com/q/48072749
tags question: http://stackoverflow.com/q/48108496
tags question: http://stackoverflow.com/q/48017422
tags question: http://stackoverflow.com/q/48053753
tags question: http://stackoverflow.com/q/48045590
type: Tag
tags question: http://stackoverflow.com/q/48134865
tags question: http://stackoverflow.com/q/48059415
tags question: http://stackoverflow.com/q/48137037
tags question: http://stackoverflow.com/q/48103119
tags question: http://stackoverflow.com/q/48138475
tags question: http://stackoverflow.com/q/48081912
tags question: http://stackoverflow.com/q/48059523
tags question: http://stackoverflow.com/q/48113498
tags question: http://stackoverflow.com/q/48146012
tags question: http://stackoverflow.com/q/48150328
tags question: http://stackoverflow.com/q/48077309
tags question: http://stackoverflow.com/q/48149442
tags question: http://stackoverflow.com/q/48149626
tags question: http://stackoverflow.com/q/48099570
tags question: http://stackoverflow.com/q/48117641
tags question: http://stackoverflow.com/q/48046020

http://stackoverflow.com/comment/83271888
type: Comment
has text: I have added question for above problem.Please find it here:https://stackoverflow.com/questions/48146862/tooltips-show-on-hover-but-dont-disappear-using-mpld3
comment on: http://stackoverflow.com/a/48049546
type: AnswerComment
score: 0

http://stackoverflow.com/q/48104071
has comment: http://stackoverflow.com/comment/83259798
tagged with: tor
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83221133
has comment: http://stackoverflow.com/comment/83220747
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48144823
has title: Python - IP not changing with stem?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/43682909
tagged with: torsocks
upvote count: 1
has comment: http://stackoverflow.com/comment/83221016
score: 1
tagged with: stem
linked to: http://stackoverflow.com/q/1096379
type: Question
has body: I wrote a script that changes the IP with stem, but it seems like it does not work. Here is a shortened version of the script: from stem import Signal from stem.control import Controller from stem.connection import connect def changeIP(): with Controller.from_port(port = 9051) as controller: controller.authenticate() controller.signal(Signal.NEWNYM) def printIP(): my_ip = urlopen('http://ip.42.pl/raw').read() print("IP -&gt; %s" % my_ip) #Some of my other codes while(true): j+=1 if j == 2: changeIP() j = 0 printIP() And it just prints my public IP again and again. It should print the same IP 2 times and then change, but it doesn't. My torrc config is correctly configured. ControlPort = 9051 HashedControlPassword 16:AD2DD67382E391D960F7E38F49A1AAB31479A0576222AB885C3CCFD70B cookie authentication 1 I even tried putting the hashed Control password in the control.authenticate(password='AD2DD67382E391D960F7E38F49A1AAB31479A0576222AB885C3CCFD70B'), but it still did not work, and I also want my script to not use it. I have been searching for this weeks now, and I found out that I can use SocksiPy module, but I can't do it. Please recode my script, Thank you very much.

xml-parsing
tags question: http://stackoverflow.com/q/48171974
tag name: xml-parsing
type: Tag

http://stackoverflow.com/q/48142723
has answer: http://stackoverflow.com/a/58349541
has title: Template does not exist. Django looking for wrong path
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83264782
tagged with: django-models
answer count: 1
downvote count: 0
score: 1
tagged with: templates
has comment: http://stackoverflow.com/comment/83265067
favorite count: 0
has comment: http://stackoverflow.com/comment/83264924
has comment: http://stackoverflow.com/comment/83266470
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83264195
has body: im following a django tutorial but have had this error coming up for a while now. i've had the course code up next to mine to comepare it to try to find the bug but i haven't had any luck with it TemplateDoesNotExist at /posts/new/ posts/post_form.html Request Method: GET Request URL: http://127.0.0.1:8000/posts/new/ Django Version: 1.11 Exception Type: TemplateDoesNotExist Exception Value: posts/post_form.html Exception Location: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/django/template/loader.py in select_template, line 53 Python Executable: /Users/chrismaltez/anaconda3/envs/simplesocialenv/bin/python Python Version: 3.5.0 Python Path: ['/Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial', '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python35.zip', '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5', '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/plat-darwin', '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/lib-dynload', '/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages'] Here is the postmortem traceback: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /Users/chrismaltez/Desktop/pycharmprojects/UDEMY/simple_social_clone/simplesocial/templates/posts/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/django/contrib/admin/templates/posts/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/django/contrib/auth/templates/posts/post_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/bootstrap3/t…
tagged with: django
tagged with: python
tagged with: django-templates

http://stackoverflow.com/a/48065732
answers question: http://stackoverflow.com/q/48065601
type: Answer
score: 5
upvote count: 5
downvote count: 0
has body: From Scikit Learn documentation: Split arrays or matrices into random train and test subsets.. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; from sklearn.model_selection import train_test_split &gt;&gt;&gt; X, y = np.arange(10).reshape((5, 2)), range(5) &gt;&gt;&gt; X array([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]) &gt;&gt;&gt; list(y) [0, 1, 2, 3, 4] &gt;&gt;&gt; X_train, X_test, y_train, y_test = train_test_split( ... X, y, test_size=0.33, random_state=42) ... &gt;&gt;&gt; X_train array([[4, 5], [0, 1], [6, 7]]) &gt;&gt;&gt; y_train [2, 0, 3] &gt;&gt;&gt; X_test array([[2, 3], [8, 9]]) &gt;&gt;&gt; y_test [1, 4] also you can turn off shuffling: &gt;&gt;&gt; train_test_split(y, shuffle=False) [[0, 1, 2], [3, 4]]

http://stackoverflow.com/a/48189810
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48169130
downvote count: 0
score: 8
has body: There is indeed a way of submitting jobs to Cloud ML Engine from a Python script. You can use the Google Python API Client Library for that purpose, and in the link I shared you can have a look at a close explanation of how the API calls. There's a command-by-command explanation, and at the end an example of how to put everything together. In order to work with the library, you will have to install it first, as explained in this other page. Then, the method you are interested in (for submitting jobs) is cloudml.projects.jobs.create(), and you can find detailed information on how to call it in the developers page. I think you might be interested in playing around with the REST API first, in order to get familiar with how it works; you can do so through the APIs Explorer. Below there's an example of a body used to make the API call: training_inputs = {'scaleTier': 'CUSTOM', 'masterType': 'complex_model_m', 'workerType': 'complex_model_m', 'parameterServerType': 'large_model', 'workerCount': 9, 'parameterServerCount': 3, 'packageUris': ['gs://&lt;YOUR_TRAINER_PATH&gt;/package-0.0.0.tar.gz'], 'pythonModule': 'trainer.task', 'args': ['--arg1', 'value1', '--arg2', 'value2'], 'region': '&lt;REGION&gt;', 'jobDir': 'gs://&lt;YOUR_TRAINING_PATH&gt;', 'runtimeVersion': '1.4'} job_spec = {'jobId': my_job_name, 'trainingInput': training_inputs} You should, adapt it to the specifications of your model. Once it is ready, you can have a look at this page explaining how to submit a training job using Python, but in short, it should be something like this: from oauth2client.client import GoogleCredentials from googleapiclient import discovery from googleapiclient import errors project_name = 'my_project_name' project_id = 'projects/{}'.format(project_name) credentials = GoogleCredentials.get_application_default() cloudml = discovery.build('ml', 'v1', credentials=credentials) request = cloudml.projects().jobs().create(body=job_spec, parent=project_id) try: response = request.execute()…
type: Answer
upvote count: 8
has comment: http://stackoverflow.com/comment/112771421
answers question: http://stackoverflow.com/q/48169130

http://stackoverflow.com/comment/83215972
has text: WebDriverException: unknown error: failed to wait for extension background page to load: chrome-extensions://lotsofcharacters/_generated_background_page.html
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48118496

http://stackoverflow.com/comment/83119901
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48057299
has text: @SCB How could I convert the file into a list format?
score: 0

http://stackoverflow.com/comment/83311105
type: AnswerComment
has text: This is of course a possibility, but in this particular case I'd rather be explicit with the mapping and not commit myself to naming classes in a specific way and dynamically mangling the names.
type: Comment
comment on: http://stackoverflow.com/a/48165920
score: 0

http://stackoverflow.com/comment/102836028
comment on: http://stackoverflow.com/a/48058539
has text: I learned here how to approach the problem - Using pd.factorize and group them by new index. Also, you can always pick the repeating index if you need only that.
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/comment/83060537
type: Comment
has text: Like I said, you may not be hitting the page you think you hit, because the application does not behave as simply as you think, this is why often it is simpler to use a framework that more closely simulate an human behavior to fool applications. That would save you some work, `mechanize` uses `urllib2` so in theory you could redo everything with just `requests` yes I believe, but why not reusing what exists?
score: 0
comment on: http://stackoverflow.com/q/48043907
type: QuestionComment

http://stackoverflow.com/comment/83059546
comment on: http://stackoverflow.com/a/48044299
score: 1
type: AnswerComment
has text: This seems like a neat but overly complex way to solve the problem.
type: Comment

http://stackoverflow.com/q/48095807
has title: django unable to connect mysql server on aws
has comment: http://stackoverflow.com/comment/83166962
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83166888
type: AnsweredQuestion
has body: my django version is 2.0.1, i would like to connect with mysql. Database which is located on a amzon ec2 I get this error when I'm running the Django server : this is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'graph', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'hostname', # Or an IP Address that your DB is hosted on 'PORT': '3306', } }
score: 1
tagged with: mysql
has answer: http://stackoverflow.com/a/48096192
type: Question
accepted answer: http://stackoverflow.com/a/48096192
answer count: 1
downvote count: 0
tagged with: amazon-web-services
favorite count: 0
has comment: http://stackoverflow.com/comment/83166349

http://stackoverflow.com/comment/135147198
type: Comment
comment on: http://stackoverflow.com/a/48105262
score: 0
type: AnswerComment
has text: if ping is not working for this particular url, try another one. possible problems : the url is not correct so it's notreachable from the machine your using or the machine is not configured to access any other urls

http://stackoverflow.com/comment/83007576
comment on: http://stackoverflow.com/q/48019249
has text: Possible duplicate of [Rodeo UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)](https://stackoverflow.com/questions/45487013/rodeo-unicodedecodeerror-ascii-codec-cant-decode-byte-0xef-in-position-0-or)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/76309906
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48129537
downvote count: 0
has body: I encountered a similar issue and devised the following solution. After conducting extensive research, I was unable to identify a direct method of transmitting binary data directly to HTML. Therefore, I opted for a straightforward approach by storing the video locally and subsequently passing the file path to the template. In Python, using the Flask web framework, you can implement this solution as follows: from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): # Assume Videos schema has file path in them file_data = Videos.query.filter_by(id=1).first() video_path = file_data.path return render_template('index.html', video_path=video_path) if __name__ == '__main__': app.run()
type: Answer

http://stackoverflow.com/a/48031256
upvote count: 2
answers question: http://stackoverflow.com/q/48031026
has body: You are using aggregate query which will return you the result with all Gender fields cast to lower case. If you wish to update the value for a field you have to use update query. Since you are using pymongo to query your documents your code should be like this import pymongo from pymongo import MongoClient from bson.objectid import ObjectId db_info = { 'db_name': 'MentalHealth', 'collection_name': 'MentalHealth' } if __name__ == "__main__": mongo_client = MongoClient() mongo_db = mongo_client[db_info['db_name']] mongo_collection = mongo_db[db_info['collection_name']] for doc in mongo_collection.find(no_cursor_timeout=True): pk = ObjectId(str(doc.get("_id"))) g = doc.get('Gender') if g: g = g.lower() mongo_collection.update({"_id": pk}, {"$set":{"Gender":g}})
score: 2
has comment: http://stackoverflow.com/comment/83046531
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48031026

http://stackoverflow.com/q/48023363
has comment: http://stackoverflow.com/comment/83017277
accepted answer: http://stackoverflow.com/a/48042099
type: AnsweredQuestion
upvote count: 1
tagged with: jinja2
downvote count: 1
type: Question
has body: I am using Flask with the default template engine, Jinja2. So I have a bunch of products in my database and they each have a style column which contains information for how they should be rendered, i.e: accent colors, fonts, but when trying to use inline styles - I would like to do it that way it seems the most concise - I get no results. The template engine just seems to the ignore variable I insert... ... style="border-color:#{{ product.style.color }}"&gt; I inspect the code from the browser's developer tools - both in Firefox and Chrome - and it seems that the variable hasn't been expanded at all by Jinja. I get the following if I view the code... ... style="border-color:#"&gt; I have queried all the products and made sure that their style row's (for the products I am working with) are all valid. So I am asking if there is a way to inline styles and dynamically set their properties using templates? I am sorry in advance if this question has been solved. It's very specific and I couldn't manage to find and questions that struggled in this area. Feel free to point me to any external resources. regards Keagan
has comment: http://stackoverflow.com/comment/83016670
has comment: http://stackoverflow.com/comment/83016621
has comment: http://stackoverflow.com/comment/83015885
has comment: http://stackoverflow.com/comment/83016337
has comment: http://stackoverflow.com/comment/83018221
score: 0
has answer: http://stackoverflow.com/a/48042099
answer count: 1
has comment: http://stackoverflow.com/comment/83023608
tagged with: flask
has title: Set CSS style properties using templates
favorite count: 0
has comment: http://stackoverflow.com/comment/83017194
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/83016831
tagged with: python
tagged with: css

surf
tags question: http://stackoverflow.com/q/48045412
type: Tag
tag name: surf

http://stackoverflow.com/comment/83228760
type: QuestionComment
score: 1
has text: I have a feeling this issue has nothing to do with Flask as long as the server is running properly. What I believe is the sticking point to your problem is the way your web server is configured. As far as I am aware, flask does not care what your domains are. You could have hundreds of domains pointing to the application, you just need to configure the web server properly. What do the web server logs say?
comment on: http://stackoverflow.com/q/48122283
type: Comment

http://stackoverflow.com/q/48028394
type: Question
has title: Using len() with if/else to populate dataframe variable
has comment: http://stackoverflow.com/comment/83026851
has comment: http://stackoverflow.com/comment/83026964
has comment: http://stackoverflow.com/comment/83026943
answer count: 1
has body: I am looking to add a variable to my dataframe that concatenates several other variables. I know that if variable 'do' is less that 4 characters, it is garbage input and I should instead use variable 'ra'. However, the below throws an attribute error: "AttributeError: ("'str' object has no attribute 'len'", 'occurred at index 0')". Is the apply operation the correct way to go about what I'm doing, and if so, how can I correct my function? def get_combined(row): if row['do'].len() &lt; 4: return row['ra']+' '+row['mi']+' '+row['fa']+' '+row['so'] else: return row['do']+' '+row['mi']+' '+row['fa']+' '+row['so'] df['Combined'] = df.apply(get_combined, axis=1)
has answer: http://stackoverflow.com/a/48028417
score: 0
tagged with: pandas
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/83270358
score: 0
type: Comment
type: QuestionComment
has text: Are your test values `-455` and `10002`? Edit the question.
comment on: http://stackoverflow.com/q/48146012

http://stackoverflow.com/a/48016710
accepted answer of: http://stackoverflow.com/q/48016658
upvote count: 20
answers question: http://stackoverflow.com/q/48016658
has comment: http://stackoverflow.com/comment/83002729
score: 20
type: AcceptedAnswer
downvote count: 0
has body: This is more efficient than your call because it uses bulk_create, which invokes just one SQL bulk create operation, as opposed to one create per object; also, it is much more elegant: ModelB.objects.bulk_create([ ModelB(**q) for q in data ]) As to how this works, the double asterisk unpacks a dictionary (or dictionary-like object) into keyword arguments to a Python function. Official Django documentation: https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create
type: Answer

http://stackoverflow.com/comment/83285108
score: 0
comment on: http://stackoverflow.com/q/48152069
has text: Thanks @TomDalton, it makes more sense now. Basically the `file1` is an executable taking the input `file2`. The output of it is `script.py` which is a python script accustomed to interpret `file2` but in more from the language perspective (it might be a Fortran). Then to actually decode the `file2` it needs to be run as `python script.py file2` and this provides the output. Thanks for your help.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48069868
downvote count: 0
answer count: 1
tagged with: python
has title: How to send a message on the bot startup to every server it is in?
tagged with: discord
favorite count: 0
score: 8
upvote count: 8
type: UnansweredQuestion
has body: I want to send an announcement to all the servers my bot is in. I found this on GitHub, but it requires a server ID and a channel ID. @bot.event async def on_ready(): server = bot.get_server("server id") await bot.send_message(bot.get_channel("channel id"), "Test") I found a similar question, but it is in discord.js. It says something with default channel, but when I tried this: @bot.event async def on_ready(): await bot.send_message(discord.Server.default_channel, "Hello everyone") it gave me this error: Destination must be Channel, PrivateChannel, User, or Object
type: Question
tagged with: discord.py
has answer: http://stackoverflow.com/a/48078278

http://stackoverflow.com/q/48148724
type: Question
has comment: http://stackoverflow.com/comment/83275730
has answer: http://stackoverflow.com/a/48148867
upvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83275710
has comment: http://stackoverflow.com/comment/83276399
has body: I have several python scripts. First script is needed to store a logic of creation of the object, rest scripts import the object from the first script and work with it. My trouble is about first script: it firstly check if pickle file corresponding to object exist, and if it exists, script load object from pickle file and stop executing. So how can I stop execution of first script without terminating python iterpretator? The first script(let name it as create_main_object.py) looks like: import pickle import os with open('main_object', 'rb') as input1: main_object = pickle.load(input1) exit() #this currently terminate interpretator .... ###logic for creation main_object ... with open('main_object', 'wb') as output: pickle.dump(main_object, output, pickle.HIGHEST_PROTOCOL) The other script import main_object in the way: from create_main_object import main_object
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48148867
has title: how to exit from module in python?

http://stackoverflow.com/q/48154637
answer count: 0
has comment: http://stackoverflow.com/comment/83293542
type: Question
has comment: http://stackoverflow.com/comment/83288839
has comment: http://stackoverflow.com/comment/83293500
tagged with: python-2.7
score: 0
has title: How to Use or Execute Command CMD to use Xalan with Python Script/Code
has comment: http://stackoverflow.com/comment/83293046
tagged with: xalan
type: UnansweredQuestion
has body: I am doing a task as well as learning to program using Python 2.7 and Xalan XSLT processor. The code: import wx, os from subprocess import call def OnImport(self, event): if self.Controler is not None and not self.CheckSaveBeforeClosing(): return filepath = "" if self.Controler is not None: filepath = self.Controler.GetFilePath() if filepath != "": directory = os.path.dirname(filepath) else: directory = os.getcwd() #Choose Source File dialogIn = wx.FileDialog(self, _("Choose a model file"), directory, "", _("model files (*.xml)|*.xml|All files|*.*"), wx.OPEN) if dialogIn.ShowModal() == wx.ID_OK: filepath = dialogIn.GetPath() else: return dialogIn.Destroy() #Choose Out XML Directory dirpath = "" dialogOut = wx.DirDialog (self,"Choose Out XML Directory","",wx.OPEN) if dialogOut.ShowModal () == wx.ID_OK: dirpath = dialogOut.GetPath () filepathplc = dirpath + "\plc.xml" # calling xalan via cmd call (['java', '-classpath', '"xalan.jar";"serializer.jar"', 'org.apache.xalan.xslt.Process', '-in', filepath, '-xsl', 'C:\Users\User\Desktop\XSL_Folder\debproj3.xsl', '-out', filepathplc, '/n']) else: return dialogOut.Destroy () I want to do xslt with xalan xslt processor with the calling xalan section but I get nothing. I want to write this command in cmd: java -classpath "xalan.jar";"serializer.jar" org.apache.xalan.xslt.Process -in "source directory file" -xsl "xsl directory file" -out "output target directory file"
tagged with: python
linked to: http://stackoverflow.com/q/12130163

http://stackoverflow.com/comment/117108725
score: 0
type: Comment
comment on: http://stackoverflow.com/a/62925227
has text: Unfortunately, importing models in alembic 1.5.4 didn't help: upgrade(), downgrade() were left unpopulated
type: AnswerComment

http://stackoverflow.com/q/48034593
upvote count: 2
has comment: http://stackoverflow.com/comment/83039594
linked to: http://stackoverflow.com/q/44715393
has comment: http://stackoverflow.com/comment/83039133
favorite count: 0
tagged with: multidimensional-array
type: UnansweredQuestion
has title: Append multidimensional numpy array to existing pandas dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83039208
score: 2
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83039450
type: Question
tagged with: numpy
tagged with: arrays
has body: I am trying to append a numpy array into an already existing dataframe. df_train = pd.DataFrame() sk_train = sklearn_representation_train.toarray() The shape of both dataframe and sk_train is: sk_train -&gt; array([[ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.]]) sk_train.shape -&gt; (95851, 2000) df_train.shape -&gt; (95851, 9) How do convert the sk_train numpy array to dataframe and concatenate it to df_train?

http://stackoverflow.com/comment/83298864
type: Comment
has text: Thank you. value1 = 'test1' value2 = 'test2' cmd = ["mypath/myphp.php {value1} {value2}"] proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
score: 0
comment on: http://stackoverflow.com/a/48159575
type: AnswerComment

http://stackoverflow.com/comment/83103875
score: 1
comment on: http://stackoverflow.com/a/48063492
type: AnswerComment
has text: Updated the code. Check it now. No empty value is there. Don't get confused to see `Alagoas` in the first position, all the values you can grab now.
type: Comment

http://stackoverflow.com/a/48200407
has body: Right from 2009, the download feature was described as: If a repository is private, the URL for downloading a file will look a bit different (it will include an authentication token that is good for 24 hours), You cannot use ssh with username/password, as you don't have an account on the remote server (only 'git' has one). You can see a download process in "Deploy build artifacts to Bitbucket Downloads"
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48133559
has comment: http://stackoverflow.com/comment/83393644
answers question: http://stackoverflow.com/q/48133559
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/78233333
score: 1
has body: I had a similar issue post Apache Airflow installation; Airflow requires constraint file, I suspect there were conflicts. Following a Jupyter Github Discussion Thread someone provided a solution to upgrade jupyterlab. pip install --upgrade jupyterlab jupyterlab_server jupyter_server This remedied the error.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48090119
downvote count: 0

http://stackoverflow.com/comment/83297654
type: QuestionComment
has text: df1.query('ilevel_0=="CHF" & ilevel_1=="MXN"') this works on my computer.
comment on: http://stackoverflow.com/q/48158984
score: 0
type: Comment

http://stackoverflow.com/q/48103810
tagged with: django
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48105403
score: 0
has answer: http://stackoverflow.com/a/60603345
tagged with: python
has body: I am using Django allauth for sign up and social authentication. For users signing up with there email, they are redirected normally to their profile based on their username as the slug. For example, something like this: views.py class RegisterView(SignupView): form_class = RegisterForm template_name = 'oauth/auth_form.html' def form_valid(self, form): return redirect('profiles:Index', slug=form.cleaned_data['username']) The user is redirected to the profiles app which contains an Index view that displays their profile based on the slug (their username inputted). This works correctly, however, when I try to do social sign in with Facebook or Google for example, it redirects me to /accounts/profile/# which is the default Django profiles page. I want them to be redirected to the profiles app, which is /profiles/{their username} How can I make this happen?
has title: Redirecting users signing in with social accounts
type: UnansweredQuestion

http://stackoverflow.com/q/48017236
has comment: http://stackoverflow.com/comment/83022862
has comment: http://stackoverflow.com/comment/83003716
score: 1
has comment: http://stackoverflow.com/comment/83015111
tagged with: numpy
tagged with: python-2.7
has body: I am writing for following line of code: holiday['real_or_not'] = np.where((holiday['transferred']=='False',1,0)) holiday Minimum reproducible example: date type locale locale_name description transferred 2012-03-02 False locale Manta Fundacion de Manta False 2012-03-02 False Regional Regional Gunanta True I am getting: ValueError: The truth value of a Series is ambiguous. Use a.empty,a.bool(), a.item(), a.any() or a.all(). Any ideas why? I write a fairly similar np.where statement on a different pandas data frame in my code and it works perfectly fine. No idea why it would work there but not in here.
has comment: http://stackoverflow.com/comment/83003928
has comment: http://stackoverflow.com/comment/83003941
has comment: http://stackoverflow.com/comment/83003850
downvote count: 0
answer count: 1
tagged with: where-clause
favorite count: 0
has title: np where statement gets: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
has comment: http://stackoverflow.com/comment/83003744
has answer: http://stackoverflow.com/a/48017392
has comment: http://stackoverflow.com/comment/83003637
tagged with: pandas
has comment: http://stackoverflow.com/comment/83003805
tagged with: python
has comment: http://stackoverflow.com/comment/83003705
has comment: http://stackoverflow.com/comment/83004010
has comment: http://stackoverflow.com/comment/83003773
has comment: http://stackoverflow.com/comment/83003724
type: UnansweredQuestion
upvote count: 1
linked to: http://stackoverflow.com/q/47996444
has comment: http://stackoverflow.com/comment/83015156
type: Question

http://stackoverflow.com/q/48023982
tagged with: dataframe
has comment: http://stackoverflow.com/comment/83017239
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/59506670
tagged with: time-series
linked to: http://stackoverflow.com/q/33937445
has answer: http://stackoverflow.com/a/48024165
has comment: http://stackoverflow.com/comment/83017860
has answer: http://stackoverflow.com/a/74964697
tagged with: pandas
upvote count: 57
has comment: http://stackoverflow.com/comment/83017165
accepted answer: http://stackoverflow.com/a/48024165
has title: Pandas finding local max and min
favorite count: 0
score: 56
has answer: http://stackoverflow.com/a/50836425
tagged with: python
downvote count: 1
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/50836425
has body: I have a pandas data frame with two columns one is temperature the other is time. I would like to make third and fourth columns called min and max. Each of these columns would be filled with nan's except where there is a local min or max, then it would have the value of that extrema. Here is a sample of what the data looks like, essentially I am trying to identify all the peaks and low points in the figure. Are there any built in tools with pandas that can accomplish this?

http://stackoverflow.com/comment/83315674
comment on: http://stackoverflow.com/q/48166212
type: Comment
type: QuestionComment
has text: Can you explain this procedure a bit better? How are `T1` and `T2` related to each other and how exactly do you use the result of *step 1* in the rest of the calculation? The voltage values within one row of the table are not monotonous, so it might be hard to find the correct column by interpolation.
score: 0

http://stackoverflow.com/q/48139274
has body: I have a pandas.core.series.Series with data 0 [00115840, 00110005, 001000033, 00116000... 1 [00267285, 00263627, 00267010, 0026513... 2 [00335595, 00350750] I want to remove leading zeros from the series.I tried x.astype('int64') But got error message ValueError: setting an array element with a sequence. Can you suggest me how to do this in python 3.x?
favorite count: 0
has answer: http://stackoverflow.com/a/63653843
tagged with: python
has answer: http://stackoverflow.com/a/48139309
has answer: http://stackoverflow.com/a/48139379
type: AnsweredQuestion
score: 7
accepted answer: http://stackoverflow.com/a/48139309
upvote count: 7
type: Question
possible better answer: http://stackoverflow.com/a/48139373
tagged with: time-series
has title: Removing leading zeros from pandas.core.series.Series
has answer: http://stackoverflow.com/a/48139373
answer count: 6
has answer: http://stackoverflow.com/a/68532516
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/63653926

http://stackoverflow.com/q/48061939
has comment: http://stackoverflow.com/comment/83096612
type: Question
has comment: http://stackoverflow.com/comment/83097250
has comment: http://stackoverflow.com/comment/83097003
has comment: http://stackoverflow.com/comment/83096697
tagged with: decision-tree
has comment: http://stackoverflow.com/comment/83096475
tagged with: binary-tree
has comment: http://stackoverflow.com/comment/83096825
type: UnansweredQuestion
has title: Building a decision tree from two lists
tagged with: python
tagged with: tree
tagged with: list
has body: I'm trying to build this decision tree through two lists that I have. input: records= ['dead','healthy','cold','influenza'] symptoms= ['cough','sneezing','fever'] (doesn't always have to be this exact lists can be different lengths etc..) the records list represent the leafs in the tree output: cough Yes / \ No sneezing sneezing Yes / \ No Yes / \ No fever fever fever fever Yes / \ No Yes/ \No Yes / \ No Yes/ \No dead cold influenza cold dead influenza cold healthy my code: def buildtree(symptoms,record): if len(record)==0: return Node(symptoms[0]) else: withelt=buildtree(symptoms+[record[0]],record[1:]) withoutelt=buildtree(symptoms,record[1:]) here=Node(symptoms[0],withelt,withoutelt) return here def get_leafs_from_records(records): optimal_illness = {} list_of_illnesses = [] illness_in_records=[] for record in records: if diagnoser.diagnose(record.symptoms) == record.illness: list_of_illnesses.append(record.illness) for illness in list_of_illnesses: if illness in optimal_illness: optimal_illness[illness] += 1 else: optimal_illness[illness] = 1 for illness in optimal_illness: illness_in_records.append(illness) return illness_in_records def build_tree(records, symptoms): records = get_leafs_from_records(records) return buildtree(symptoms,records) the node class: class Node: def __init__(self, data="", pos=None, neg=None): self.data = data self.positive_child = pos self.negative_child = neg my get_leafs_from_records(records) function is just to make it as list that i i put input in the start u can ignore it. My code is not working as it supposed its not building the tree like its supposed It keeps building just the first node any ideas? If anything else is unclear please let me know.
answer count: 0
score: 0

http://stackoverflow.com/q/48030583
tagged with: python
has comment: http://stackoverflow.com/comment/83031585
tagged with: text
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48030629
has comment: http://stackoverflow.com/comment/83032680
tagged with: file
has body: I have a need to work with configuration files that use nested HTML-style tags of key-value pairs using equals signs. I'd like a Python approach that would allow me to read such files, add, delete or modify sections, and write the updated file. The files look like: &lt;tag1&gt; key1=value1 key2=value2 &lt;tag2&gt; key3=value3 &lt;/tag2&gt; &lt;tag2&gt; key3=value four &lt;/tag2&gt; &lt;/tag1&gt; So its not quite a HTML or XML file, and not a Windows INI file either. There are no spaces surrounding the equals signs, there are a few random blank lines in the files that seem to be ignored and values in the key-value pairs don't use quote marks and may have embedded spaces. I could not find a definition or name for this exact file structure but I found it hard to focus the search so I may have missed something obvious. Is this a recognized standard file structure? If so what is it called? I'd appreciate any pointers on what libraries can be coerced into working with this structure and maybe some examples if they are not readily available in the docco. Thanks.
type: Question
accepted answer: http://stackoverflow.com/a/48030629
score: 0
answer count: 1
has title: Manipulating a file with nested tags and key-value pairs
tagged with: parsing
has comment: http://stackoverflow.com/comment/83031345
has comment: http://stackoverflow.com/comment/83032740

http://stackoverflow.com/q/48047866
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/45090982
tagged with: python
tagged with: qt
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/83067519
has comment: http://stackoverflow.com/comment/83067474
duplicate of: http://stackoverflow.com/q/45090982
score: 0
has body: The component being connected is a combobox within a table. The connection works, but I want to be able to pass arguments to the function. Just as a simplified example, I made those arguments the cell row and column, as well as a password. def setTableCellToCombo(qtbl, row, column, password): #qtbl is a QTableWidget qtbl.blockSignals(True) comp = QtWidgets.QComboBox() comp.insertItems(0, ['Example']) comp.setCurrentIndex(0) qtbl.setCellWidget(row, column, comp) comp.currentIndexChanged.connect(comboListener(row, column, password)) qtbl.blockSignals(False) def comboListener(row, column, password): print(password) The error I get is: TypeError: Qt.ConnectionType expected, not 'function' Is there a way to pass arguments to the connected 'comboListener' function? And if so, how?
has title: How to pass extra arguments in PyQt5 for connect?
tagged with: python-3.x

http://stackoverflow.com/q/48083587
type: AnsweredQuestion
score: 2
upvote count: 2
possible better answer: http://stackoverflow.com/a/70503958
tagged with: mysql
has answer: http://stackoverflow.com/a/70503958
type: Question
has body: For all the tables some of columns are generated and some of columns didn't. Here is my models personalInfo.py from django.db import models # Create your models here. class Students(models.Model): student_name = models.CharField(max_length=100) student_id = models.CharField(max_length=50) student_dept = models.CharField(max_length=30) student_sec = models.CharField(max_length=2) class StudentDetails(models.Model): students = models.ForeignKey(Students, on_delete=models.CASCADE) present_address = models.TextField permanent_address = models.TextField student_phone = models.BigIntegerField gpo_box_number = models.IntegerField class Teachers(models.Model): teacher_name = models.CharField(max_length=100) teacher_id = models.CharField(max_length=50) teacher_dept = models.CharField(max_length=30) class TeacherDetails(models.Model): teachers = models.ForeignKey(Teachers, on_delete=models.CASCADE) present_address = models.TextField permanent_address = models.TextField teacher_phone = models.BigIntegerField gpo_box_number = models.IntegerField studentAdvising.py from django.db import models from personalInfo.models import Students, Teachers # Create your models here. class Advising(models.Model): student = models.ForeignKey(Students, on_delete=models.CASCADE) teacher = models.ForeignKey(Teachers, on_delete=models.CASCADE) subject_matter = models.CharField(max_length=400) comment = models.TextField starting_time = models.TimeField ending_time = models.TimeField date = models.DateField migration details for personalInfo.py # Generated by Django 2.0 on 2018-01-03 17:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='StudentDetails', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='Students', fields=[ ('id', models.AutoField(auto_created=True, p…
has answer: http://stackoverflow.com/a/48083629
has title: Django migration: all the columns are not generated as the model
answer count: 2
has comment: http://stackoverflow.com/comment/83142190
has comment: http://stackoverflow.com/comment/83141836
accepted answer: http://stackoverflow.com/a/48083629
downvote count: 0
has comment: http://stackoverflow.com/comment/83141929
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83141982

http://stackoverflow.com/comment/96891632
type: Comment
comment on: http://stackoverflow.com/a/48072551
score: 3
has text: You'll want to add `idx = tuple(idx)` now to avoid a `FutureWarning` (and later an error / incorrect result). Something like this is really needed in the `argsort` docs; there should be an easy/standard way to get from the sorted indices to the sorted array.
type: AnswerComment

http://stackoverflow.com/comment/84265721
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48047118
has text: Oh really, but as I've been suggested by the apscheduler team, I couldn't use flaks/wsgi if I want my jobs to be automatically restarted, so I created a separate process for the jobs.

http://stackoverflow.com/comment/83082439
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48055016
has text: [what-exactly-are-pythons-iterator-iterable-and-iteration-protocols](https://stackoverflow.com/questions/9884132/what-exactly-are-pythons-iterator-iterable-and-iteration-protocols) might be helpful

http://stackoverflow.com/a/48061931
has comment: http://stackoverflow.com/comment/83096700
has comment: http://stackoverflow.com/comment/83096332
score: 1
answers question: http://stackoverflow.com/q/48061766
upvote count: 1
has body: I think you want to pass a function to the key argument to the sorted function. Something like this: &gt;&gt;&gt; a = ['a', 'b', 'c'] &gt;&gt;&gt; codes = {'a': 3, 'b': 1, 'c':2} &gt;&gt;&gt; sorted(a, key=lambda e: codes[e]) ['b', 'c', 'a'] https://docs.python.org/3/library/functions.html#sorted Edit: To sort an OrderedDict as described in the question you'll need to use the list of keys returned by sorted to build a new one - o is an existing OrderedDict: &gt;&gt;&gt; o2 = OrderedDict() &gt;&gt;&gt; for k in sorted(o, key=lambda e: codes[e]): ... o2[k] = o[k]
has comment: http://stackoverflow.com/comment/83096821
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48061766
type: Answer

http://stackoverflow.com/comment/83164738
score: 1
has text: If you would perform `a = b = c = [[] for e in range(6)]` you would let `a`, `b` and `c` refer to the **same** list.
type: Comment
comment on: http://stackoverflow.com/q/48095092
type: QuestionComment

http://stackoverflow.com/a/48135734
has comment: http://stackoverflow.com/comment/83250116
has comment: http://stackoverflow.com/comment/83249801
score: 1
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48135071
has body: This might help: from datetime import datetime from itertools import groupby from pprint import pprint # assuming that collection of data objects is a list datas = [ { "id": "abcd", "value": 100.0, "timestamp": "2011-07-14 19:43:37" }, { "id": "abcd", "value": 500.0, "timestamp": "2011-07-15 20:30:37" }, { "id": "abcd", "value": 400.0, "timestamp": "2011-07-15 20:30:38" } ] decorated_datas = [] # first we need to add a key with each data, that would be needed during sorting # and that key would be date and hour for data in datas: timestamp = datetime.strptime(data["timestamp"], "%Y-%m-%d %H:%M:%S") # assuming your timestamp is in this format only decorated_datas.append((timestamp.date(), timestamp.time().hour, data)) # then we sort the data created in the last step using the date and hour sorted_decorated_datas = sorted(decorated_datas, key=lambda x: (x[0], x[1])) # function for calculating statistics of a given collection of numbers def calculate_stats(collection_of_numbers): maxVal = max(collection_of_numbers) minVal = min(collection_of_numbers) avgVal = sum(collection_of_numbers) / len(collection_of_numbers) return (maxVal, minVal, avgVal) results = [] # then we group our sorted data by date and hour, and then we calculate # statistics for the group and append result to our final results for key, group_iter in groupby(sorted_decorated_datas, lambda x: (x[0], x[1])): group_values = [data[2]["value"] for data in group_iter] maxValue, minValue, avgValue = calculate_stats(group_values) result = {"date": key[0], "hour": key[1], "minVal": minValue, "maxVal": maxValue, "avgVal": avgValue} results.append(result) pprint(results) And the output was: [{'avgVal': 100.0, 'date': datetime.date(2011, 7, 14), 'hour': 19, 'maxVal': 100.0, 'minVal': 100.0}, {'avgVal': 450.0, 'date': datetime.date(2011, 7, 15), 'hour': 20, 'maxVal': 500.0, 'minVal': 400.0}] EDIT After giving it a thought, I found out that the format in which you represent timestamp in a string is the perfect candid…
downvote count: 1

http://stackoverflow.com/q/48151844
tagged with: unicode
has comment: http://stackoverflow.com/comment/83283948
favorite count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83283122
has comment: http://stackoverflow.com/comment/83282287
answer count: 4
has comment: http://stackoverflow.com/comment/83282476
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48152219
score: 1
has comment: http://stackoverflow.com/comment/83282988
has comment: http://stackoverflow.com/comment/83282316
has body: Some special character like '', in Python it's as a character. &gt;&gt;&gt; s = '' &gt;&gt;&gt; len(s) 3 &gt;&gt;&gt; s[:1] '' but when I put it in Atom, it's as 2 character In addition in java it is also as 2 character jshell&gt; String s = "" s ==&gt; "" jshell&gt; s.length() $4 ==&gt; 6 but in terminal it is as one character ➜ ~ echo -n '' | wc -m 3 So how to let Python consistent with Atom? Background: I want to write some text into excel, but some text is so large and excel cell has a limit: maximum 32767 characters, so I have to restrict text length, e.g. text[:32767] but I found even in this case still cannot open the generated excel, because if there are special characters in the text, its length is actually more than 32767.
has comment: http://stackoverflow.com/comment/83465698
has answer: http://stackoverflow.com/a/48162375
has comment: http://stackoverflow.com/comment/83306184
has answer: http://stackoverflow.com/a/48160434
has answer: http://stackoverflow.com/a/48152974
type: Question
has comment: http://stackoverflow.com/comment/83293813
possible better answer: http://stackoverflow.com/a/48162375
has comment: http://stackoverflow.com/comment/83282466
has comment: http://stackoverflow.com/comment/83282133
has title: about len str with special characters
has comment: http://stackoverflow.com/comment/83282184
downvote count: 0
accepted answer: http://stackoverflow.com/a/48152974

http://stackoverflow.com/q/48031163
has title: read_pdf error from tabule for read the pdf files..?
has comment: http://stackoverflow.com/comment/83032791
type: UnansweredQuestion
tagged with: tabula
has comment: http://stackoverflow.com/comment/83032784
type: Question
has answer: http://stackoverflow.com/a/48031325
answer count: 1
has comment: http://stackoverflow.com/comment/83032672
score: 0
has body: I use the tabula package for pdf reading ,but here i got these error df = tabula.read_pdf("/tmp/university_exam_results.pdf", output_format="json", pages="all") AttributeError: 'module' object has no attribute 'read_pdf' what can i do for this error .please fix my issue..
tagged with: python

http://stackoverflow.com/q/48127659
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48129165
type: AnsweredQuestion
upvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/48129165
has title: python :zlib.error: Error -3 while decompressing data: incorrect data check
has body: [Emergent!] when I use pip3 to install scipy, I get this error: Exception: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 328, in run wb.build(autobuilding=True) File "/usr/lib/python3/dist-packages/pip/wheel.py", line 748, in build self.requirement_set.prepare_files(self.finder) File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 360, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 577, in _prepare_file session=self.session, hashes=hashes) File "/usr/lib/python3/dist-packages/pip/download.py", line 810, in unpack_url hashes=hashes File "/usr/lib/python3/dist-packages/pip/download.py", line 649, in unpack_http_url hashes) File "/usr/lib/python3/dist-packages/pip/download.py", line 842, in _download_http_url stream=True, File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 480, in get return self.request('GET', url, **kwargs) File "/usr/lib/python3/dist-packages/pip/download.py", line 378, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/adapter.py", line 36, in send cached_response = self.controller.cached_request(request) File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/controller.py", line 102, in cached_request resp = self.serializer.loads(request, self.cache.get(cache_url)) File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-no…
score: 2
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/83091177
comment on: http://stackoverflow.com/q/48058717
has text: *"for some reason"* - oh, for pity's... for **what** reason?! *"will be good"* - will it? How exactly? What if other placeholders (e.g. `%d`, which I think some libraries do use) appear? I won't waste further time on this, but you should really reconsider your approach. I'd also strongly recommend you rewrite the question to clarify **what you're trying to do** *before* the details of **how you're trying to do it**; the calibre and relevance of answers you've received hopefully demonstrates clearly why the current revision isn't helping you out.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/83295909
type: Comment
has text: After a restart there are no GPU processes. Then I run the cell once and I always have to run it again because of some directory it never finds the first time. Tried a few commands to kill it. Guess I'll keep looking.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48157558

http://stackoverflow.com/comment/83229331
type: AnswerComment
has text: Maybe also mention that he's used `continue;` in his JS, which isn't valid
type: Comment
comment on: http://stackoverflow.com/a/48126341
score: 0

http://stackoverflow.com/comment/82999362
comment on: http://stackoverflow.com/a/48015051
type: Comment
has text: @schwobaseggl Here I did, yes. Python 3.6.1. Why?
score: 0
type: AnswerComment

http://stackoverflow.com/a/48129161
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48128995
has body: Could you please give a bit more information as to how exactly is your data stored in your code? Is it a numpy array, a scipy.signal.spectrogram or simple python lists? A snippet of code would help a lot in trying to help you find a good solution. For the moment the only "easy" way I would suggest is to have a look at numpy.amax(), choosing wisely the value given to the axis parameter, should get you the maximum you are looking for.

http://stackoverflow.com/comment/83262118
type: Comment
comment on: http://stackoverflow.com/q/48141393
type: QuestionComment
has text: `event` exists only inside `for event` loop.
score: 0

http://stackoverflow.com/comment/83175545
score: 0
type: AnswerComment
has text: Thank you for expanding on your answer! it really helped!
type: Comment
comment on: http://stackoverflow.com/a/48089100

http://stackoverflow.com/comment/83061821
type: QuestionComment
has text: If you move globals into a class, and make them static members, you're basically just using the class to create a namespace. I would say that namespaced globals are far better than non-namespaced globals. Namespacing solves the name collision problem with globals at least.
score: 1
comment on: http://stackoverflow.com/q/48045311
type: Comment

http://stackoverflow.com/a/48052996
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48052962
has comment: http://stackoverflow.com/comment/83078269
score: 3
answers question: http://stackoverflow.com/q/48052962
upvote count: 3
has comment: http://stackoverflow.com/comment/83078188
has body: Looking at the docs, %I matches hours for times in AM/PM format, meaning valid values range from 01 to 12. You have 13 (1 PM) I guess you need to use %H import datetime mytime = '[29/Oct/2017:13:11:38 ' fmt = '[%d/%b/%Y:%H:%M:%S ' now = datetime.datetime.strptime(mytime, fmt) print("now: %s" % now.strftime('%Y-%m-%d %H:%M:%S')) prints: now: 2017-10-29 13:11:38 Check this: fmt = '[%d/%b/%Y:%I:%M:%S ' for test in range(1, 24): mytime = '[29/Oct/2017:%02d:11:38 ' % test now = datetime.datetime.strptime(mytime, fmt) print("now: %s" % now.strftime('%Y-%m-%d %H:%M:%S')) Will work "fine" (I quote because 12 is assumed to be midnight) until test hits 13: now: 2017-10-29 01:11:38 now: 2017-10-29 02:11:38 now: 2017-10-29 03:11:38 now: 2017-10-29 04:11:38 now: 2017-10-29 05:11:38 now: 2017-10-29 06:11:38 now: 2017-10-29 07:11:38 now: 2017-10-29 08:11:38 now: 2017-10-29 09:11:38 now: 2017-10-29 10:11:38 now: 2017-10-29 11:11:38 now: 2017-10-29 00:11:38 Traceback (most recent call last): File "./stack_096.py", line 12, in &lt;module&gt; now = datetime.datetime.strptime(mytime, fmt) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 500, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/_strptime.py", line 337, in _strptime (data_string, format)) ValueError: time data '[29/Oct/2017:13:11:38 ' does not match format '[%d/%b/%Y:%I:%M:%S '

django-staticfiles
tags question: http://stackoverflow.com/q/48103144
tags question: http://stackoverflow.com/q/48040102
tag name: django-staticfiles
type: Tag

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/48053355
tags question: http://stackoverflow.com/q/48097653
tags question: http://stackoverflow.com/q/48171761
type: Tag
tags question: http://stackoverflow.com/q/48045302
tags question: http://stackoverflow.com/q/48041609
tags question: http://stackoverflow.com/q/48079130
tags question: http://stackoverflow.com/q/48029089
tags question: http://stackoverflow.com/q/48019798
tags question: http://stackoverflow.com/q/48061681
tags question: http://stackoverflow.com/q/48097514

http://stackoverflow.com/q/48137714
score: 1
has title: Is there a function in tensorflow for doing transformations that a functions of the indices?
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: differential-equations
upvote count: 1
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/48138052
has body: I'm looking for (but have been completely unable to find) a function in tensorflow that will allow me to do a 'map' on a tensor. map Firstly, I'm not even sure if there is a 'map' function? By this a mean something that lets me apply a given f(x) to even entry in a tensor. e.g. I want something like this def f(x): return x**2 Y = tf.Variable(np.array([[1.0, 2.0], [3.0, 4.0]]) Y = tf.map_function(X, f) producing (after suitably running in a session, obviously) a tensor with values Y = [[1.0, 4.0], [9.0, 16.0]] Does this exist (for general f - I realise that tf.nn.relu and tf.nn.sigmoid? On one hand, it seems like it should, sincemap` is a pretty fundamental operation. On the other hand, it would involve taking the supplied python function and somehow converting it to be executed on the GPU, and that sounds like something that might not be possible. Am I asking for the moon on a stick here? **mapi* If such a function exists, is there a version that allows me to use an index-aware f? e.g. def f(x, i): if (i != [0, 0]): k2 = np.sum([x**2 for x in i]) else: k2 = 1.0 # To avoid division by zero return (x / k2) Y = tf.Variable(np.ones(shape=(2,3))) Y = tf.mapi_function(X, f) producing Y = [[1.0, 1.0, 0.25], [1.0, 0.5, 0.2]] If such function don't exist, would it be possible (for fixed f) for me to add them by building tensorflow from (slightly modified) source? Why I need such a function The reason I'm asking this is that I'm trying to use tensorflow to numerically integrate a PDE. As part of that I need to compute the laplacian (d^2/dx^2 + d^2/dy^2 + d^2/dz^2) u(x,y,z). In a Fourier-transformed representation of the field u(k_X, k_y, k_z) this involves dividing by k_x^2 + k_y^2 + k_z^2. I could precompute a tensor of inverse squared wavenumber values and dow an element-wise multiply. But this would use up a lot of memory. I suspect it would also be slower to load those values from memory.
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48078136
has answer: http://stackoverflow.com/a/48078458
score: 0
has body: My website gives deatails about different servers. I have used requests to check which server ILO IP is not working through http and which is not. AFter using requests.. the page loads super slow! My server checks ILO Ips of many servers and if the server is broken it shows the IP as a text and if not it shows a link(THE IP) to the ILO. Do you know how to make the server load much faster? Thanks.. models.py - from django.db import models import requests class serverlist(models.Model): ServerName = models.CharField(max_length = 30,blank=True) Owner = models.CharField(max_length = 50,blank=True) Project = models.CharField(max_length = 30,blank=True) Description = models.CharField(max_length = 255,blank=True) IP = models.CharField(max_length = 30,blank=True) ILO = models.CharField(max_length = 30,blank=True) Rack = models.CharField(max_length = 30,blank=True) Status = models.CharField(max_length = 30,blank=True) def checkUrlAvailable(self): ip_check = 'https://' + self.ILO resp = requests.head(ip_check,allow_redirects=False) if resp.status_code == 303: return True else: return False index.html - {% if server.checkUrlAvailable is True %} &lt;a href="//{{ server.ILO }}"&gt; {{ server.ILO }} &lt;/a&gt; {% else %} {{ server.ILO }} {% endif %}
has title: Django website loads slow after using requests to check broken links
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: web
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: mysql
type: Question

http://stackoverflow.com/q/48042926
has body: I'm trying to run a python app on gcloud and everything works fine until I add "from flask_sqlalchemy import SQLAlchemy" to my file. The error I get is "Internal server error" This is my Dockerfile FROM tiangolo/uwsgi-nginx-flask:python3.6 MAINTAINER COPY ./app /app RUN apt-get update RUN apt-get --upgrade install -y nmap curl nano dialog net-tools python-pip python3-pip python-dev build-essential python-distribute python3 mysql-server RUN pip install --upgrade pip flask Flask-PyMongo Flask-WTF SQLAlchemy mysqlclient And this the part where I import the extensions from flask import Flask, render_template, flash, redirect, url_for, session, request from flask_pymongo import PyMongo from wtforms import Form, StringField, TextAreaField, PasswordField, validators from functools import wraps from flask_sqlalchemy import SQLAlchemy from datetime import datetime
has answer: http://stackoverflow.com/a/48044974
accepted answer: http://stackoverflow.com/a/48044974
has title: Internal Server Error running Flask on gcloud using Docker
tagged with: google-app-engine
tagged with: python
type: AnsweredQuestion
type: Question
score: 0
answer count: 1
tagged with: gcloud
tagged with: flask
tagged with: flask-sqlalchemy

http://stackoverflow.com/comment/83247033
comment on: http://stackoverflow.com/q/48099543
type: QuestionComment
has text: @DavidW (1) That's not really what I'm asking: I'm asking for API to request a buffer of certain size. This is quite possible to achieve without heap allocation. (2) The problem is, actually the unnecessary copying of bytes: my primary use case is writing to actual files, and there OS already allocated whatever memory required. (3) `BytesIO` is just an example. I'd like the code to work for any object that implements buffer protocol. If this was specific for `BytesIO` the problem would've been much simpler (I could just call its `write()` method).
score: 0
type: Comment

http://stackoverflow.com/a/48118514
has body: After combining resources from here and here I came up with the following code. Maybe it will help you. The idea is that you can override the Callbacks class from keras and then use the on_batch_end method to check the loss value from the logs that keras will supply automatically to that method. Here is a working code of an NN with that particular function built in. Maybe you can start from here - import numpy as np import pandas as pd import seaborn as sns import os import matplotlib.pyplot as plt import time from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import keras from keras.models import Sequential from keras.layers import Dense from keras.callbacks import Callback # fix random seed for reproducibility seed = 155 np.random.seed(seed) # load pima indians dataset # download directly from website dataset = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data", header=None).values X_train, X_test, Y_train, Y_test = train_test_split(dataset[:,0:8], dataset[:,8], test_size=0.25, random_state=87) class NBatchLogger(Callback): def __init__(self,display=100): ''' display: Number of batches to wait before outputting loss ''' self.seen = 0 self.display = display def on_batch_end(self,batch,logs={}): self.seen += logs.get('size', 0) if self.seen % self.display == 0: print('\n{0}/{1} - Batch Loss: {2}'.format(self.seen,self.params['samples'], logs.get('loss'))) out_batch = NBatchLogger(display=1000) np.random.seed(seed) my_first_nn = Sequential() # create model my_first_nn.add(Dense(5, input_dim=8, activation='relu')) # hidden layer my_first_nn.add(Dense(1, activation='sigmoid')) # output layer my_first_nn.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) my_first_nn_fitted = my_first_nn.fit(X_train, Y_train, epochs=1000, verbose=0, batch_size=128, callbacks=[out_batch], initial_epoch=0) Please let me know if you wanted to have…
has comment: http://stackoverflow.com/comment/83215121
has comment: http://stackoverflow.com/comment/83214342
has comment: http://stackoverflow.com/comment/83214396
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48118111
has comment: http://stackoverflow.com/comment/83229477
has comment: http://stackoverflow.com/comment/83215411
has comment: http://stackoverflow.com/comment/83213985

http://stackoverflow.com/comment/89484210
type: AnswerComment
type: Comment
has text: this involves replacing the stock Python with Homebrew Python, and does not address the actual problem in the question
comment on: http://stackoverflow.com/a/50051605
score: 0

http://stackoverflow.com/comment/83043559
type: Comment
has text: unambiguous, that is, it was actually the shortest path, and not only found as the first of all the shortest paths.
comment on: http://stackoverflow.com/q/48036690
score: 0
type: QuestionComment

neural-network
tags question: http://stackoverflow.com/q/48131106
tags question: http://stackoverflow.com/q/48056014
tags question: http://stackoverflow.com/q/48138475
tags question: http://stackoverflow.com/q/48169791
tags question: http://stackoverflow.com/q/48125575
tags question: http://stackoverflow.com/q/48169759
tags question: http://stackoverflow.com/q/48057841
tags question: http://stackoverflow.com/q/48027263
tags question: http://stackoverflow.com/q/48126924
tags question: http://stackoverflow.com/q/48040685
tags question: http://stackoverflow.com/q/48117562
tags question: http://stackoverflow.com/q/48029692
tags question: http://stackoverflow.com/q/48044595
tags question: http://stackoverflow.com/q/48141319
type: Tag
tags question: http://stackoverflow.com/q/48121895
tags question: http://stackoverflow.com/q/48089155
tags question: http://stackoverflow.com/q/48142421
tags question: http://stackoverflow.com/q/48041000
tags question: http://stackoverflow.com/q/48069241
tags question: http://stackoverflow.com/q/48042659
tags question: http://stackoverflow.com/q/48053625
tags question: http://stackoverflow.com/q/48119910
tags question: http://stackoverflow.com/q/48116484
tags question: http://stackoverflow.com/q/48015101
tags question: http://stackoverflow.com/q/48102882
tags question: http://stackoverflow.com/q/48137219
tags question: http://stackoverflow.com/q/48026129
tags question: http://stackoverflow.com/q/48040054
tags question: http://stackoverflow.com/q/48133855
tags question: http://stackoverflow.com/q/48162322
tag name: neural-network
tags question: http://stackoverflow.com/q/48043891
tags question: http://stackoverflow.com/q/48055704
tags question: http://stackoverflow.com/q/48070505

http://stackoverflow.com/q/48119634
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/83215932
has comment: http://stackoverflow.com/comment/83215751
has comment: http://stackoverflow.com/comment/83215764
has comment: http://stackoverflow.com/comment/83215851
has comment: http://stackoverflow.com/comment/83215885
favorite count: 0
accepted answer: http://stackoverflow.com/a/48119877
has comment: http://stackoverflow.com/comment/83215782
has answer: http://stackoverflow.com/a/48120279
upvote count: 2
has comment: http://stackoverflow.com/comment/83215707
downvote count: 2
has comment: http://stackoverflow.com/comment/83215878
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83215824
has title: Python: instantiate an object to a reference
has body: What I am asking might not be possible in Python and probably stems from my being used to pointers, but this is how it goes: is the following achievable in python? class A(object): #body of class a = A() #create a new object b = A(a) #"b" is now an alias for "a" My naive attempt to do this was class A(object): def __init__(self, x): if isinstance(x, A): self = x But, of course, this is non-sense since self is just a local variable. EDIT: To be clear, this is not about simple variable assignment (i.e. b=a creates an alias but I don't care). This question came while I was trying to construct a loop with lots of objects of the same type: class A(object): #blah l = [] for cond in conditions: tmp = A(*cond) l.append(tmp) If cond[0] is another object of type A, then tmp is just a reference to that object. Now, there is a work-around for everything, but that's not what I am asking. I'd like to know if there is a solution to my original question.
type: Question
has answer: http://stackoverflow.com/a/48119877
has comment: http://stackoverflow.com/comment/83215716
has comment: http://stackoverflow.com/comment/83215860
has answer: http://stackoverflow.com/a/48119862
has comment: http://stackoverflow.com/comment/83215999
possible better answer: http://stackoverflow.com/a/48119862

http://stackoverflow.com/q/48104001
downvote count: 0
has title: Pandas Read_CSV incorrectly reads numbers
score: 1
type: Question
has body: Method1 def getAndBuildDatafrmeFromCsvBasic(filename): colTypes = {'Open': 'float64', 'High': 'float64', 'Low': 'float64', 'Close': 'float64', 'Volume': 'float64'} dfEurUsd2017 = pd.read_csv(filename, delimiter=",", index_col='Gmt time', dtype=colTypes, parse_dates=['Gmt time']) return dfEurUsd2017 Method2 def getAndBuildDatafrmeFromCsv(filename): df = pd.read_csv(filename, header=None) df.columns = ['date', 'Open', 'High', 'Low', 'Close', 'Volume'] df.date = pd.to_datetime(df.date, format='%d.%m.%Y %H:%M:%S.%f') df.index = df['date'] df = df'Open', 'High', 'Low', 'Close', 'Volume' return df Results Method1 Open High Low Close Volume Gmt time 2017-12-04 23:00:00 1.06672 1.06699 1.06636 1.06698 1889.56 Results Method2 Open High Low Close Volume Gmt time 2017-12-04 23:00:00 1.18686 1.18699 1.18666 1.18682 2004.46 Why does method1 incorrectly parse the values for Open,High,Low,Close,Volume? Method2 produces the correct output. I'm concerned why both methods output completely different numerical values, even the volume is different. Yet the csv file is the same. Rows from CSV 04.12.2017 23:00:00.000,1.18686,1.18699,1.18666,1.18682,2004.4599999999998 04.12.2017 23:30:00.000,1.18682,1.18706,1.18652,1.18681,1242.68 05.12.2017 00:00:00.000,1.18681,1.18691,1.18639,1.18653,2666.81 05.12.2017 00:30:00.000,1.18653,1.18726,1.18650,1.18709,3567.2400000000007 05.12.2017 01:00:00.000,1.18708,1.18750,1.18707,1.18738,3105.4699999999993 05.12.2017 01:30:00.000,1.18738,1.18744,1.18691,1.18732,3561.5 05.12.2017 02:00:00.000,1.18732,1.18766,1.18704,1.18740,2706.6400000000003
has comment: http://stackoverflow.com/comment/83184852
has answer: http://stackoverflow.com/a/48104759
accepted answer: http://stackoverflow.com/a/48104759
has comment: http://stackoverflow.com/comment/83183686
has comment: http://stackoverflow.com/comment/83183876
tagged with: python-2.7
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83183854
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83183594
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48126283
tagged with: time
type: UnansweredQuestion
tagged with: python
tagged with: influxdb
score: 2
answer count: 0
upvote count: 2
type: Question
has title: How to post CSV file data into the InfluxDB server in same time series as CSV File's time series?
has body: I would like to post data from a CSV file to InfluxDB file and the Time column of InfluxDB should match with CSV file Time column. I meant InfluxDB time series should same as CSV file's Time series. My main motive is InfluxDB should store the data of CSV file with respect CSV file's time series. The CSV file is shown below Time Energy Power 12-26-2017 7:34:27 103691 24.838 12-26-2017 7:35:28 103693 19.525 I have used this spice code to convert CSV file's time to epoch to send the InfluxDB server t = "2017-12-26 07:34:27" lctime = (int(time.mktime(time.strptime(t,"%Y-%m-%d %H:%M:%S")))) * 1000000000 #in nano second` and I have posted this data to InfluxDB server in JSON format. client.write_points([ {"measurement": "Meter1", "tags":{"host": "localPC", "Region": "Northam"}, "Time":lctime, "fields":{"Energy": e1, "Power": p1, } } ] There was no issue with posting these data to InfluxDB server but when I went to check whether the correct data was written or not into Influxdb using this query in database panel. Select * From Meter1 The influxDB showed me this "2018-01-04T05:43:41.580065574Z" time but it should have shown me "2017-12-26 07:34:27" as same as CSV file's time. Please tell me in which method I can match the time of CSV and InfluxDB? Please tell me in which method I can do this thing which I want?
has comment: http://stackoverflow.com/comment/87295252
downvote count: 0
tagged with: influxdb-python
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/48053384
type: AcceptedAnswer
has body: Generally speaking, it would be quite difficult (if possible) to reliably cover all the possible arbitrary locations of a profile name on an arbitrary site. The main problem is that you cannot predict what the HTML layout would be on a target site. One possible alternative way to approach the problem would be to switch from HTML parsing to Natural Language Processing and Named Entity Recognition in particular. There are few tools to choose from - the StanfordNERTagger from nltk, spacy etc. Here is a sample using nltk (this answer should help to set things up): import nltk import requests from bs4 import BeautifulSoup from nltk.tag.stanford import StanfordNERTagger st = StanfordNERTagger('stanford-ner/english.all.3class.distsim.crf.ser.gz', 'stanford-ner/stanford-ner.jar') links = { "https://www.paulweiss.com/professionals/associates/robert-j-agar", "http://www.cadwalader.com/index.php?/professionals/matthew-lefkowitz", "https://www.kirkland.com/sitecontent.cfm?contentID=220&amp;itemID=12061" } for link in links: res = requests.get(link) soup = BeautifulSoup(res.text,"lxml") text = soup.body.get_text() for sent in nltk.sent_tokenize(text): tokens = nltk.tokenize.word_tokenize(sent) tags = st.tag(tokens) for tag in tags: if tag[1] == 'PERSON': print(tag) print("----------") Now, this would extract the person names but would also have a lot of noise: ('Mark', 'PERSON') ('Adler', 'PERSON') ('Ellis', 'PERSON') ('Mark', 'PERSON') ('Adler', 'PERSON') ('J.D.', 'PERSON') ('Mark', 'PERSON') ('Adler', 'PERSON') ('Kirkland', 'PERSON') ('Mark', 'PERSON') ---------- ('PAUL', 'PERSON') ('Agar', 'PERSON') ('Robert', 'PERSON') ... ('Paul', 'PERSON') ('Weiss', 'PERSON') ('Rifkind', 'PERSON') ---------- ('Bono', 'PERSON') ('Bono', 'PERSON') ('ProjectsPro', 'PERSON') ... ('Jason', 'PERSON') ('Schwartz', 'PERSON') ('Jodi', 'PERSON') ('Avergun', 'PERSON') ('Top', 'PERSON') ---------- One of the reasons for this noise is that we are parsing the text of the body of a webpage which, of cour…
score: 4
has comment: http://stackoverflow.com/comment/83080007
has comment: http://stackoverflow.com/comment/83108692
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/48014693
answers question: http://stackoverflow.com/q/48014693
downvote count: 0

http://stackoverflow.com/comment/83321336
comment on: http://stackoverflow.com/a/48166659
type: Comment
has text: Awesome ! Exactly what I was looking for ;)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83022233
type: Comment
comment on: http://stackoverflow.com/q/48026203
has text: my fault... three lists of second half that consists of lots of pairs is desired output. First half that starts with 'import random' is my def to get a desired output.
score: 0
type: QuestionComment

http://stackoverflow.com/q/48094854
linked to: http://stackoverflow.com/q/15891038
downvote count: 0
answer count: 6
tagged with: pandas
has answer: http://stackoverflow.com/a/68691143
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/66651208
has answer: http://stackoverflow.com/a/69323468
has comment: http://stackoverflow.com/comment/83164354
has comment: http://stackoverflow.com/comment/83164465
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/67912260
duplicate of: http://stackoverflow.com/q/15891038
score: 31
upvote count: 31
has answer: http://stackoverflow.com/a/48114190
has title: Pandas convert data type from object to float
has body: I read some weather data from a .csv file as a dataframe named "weather". The problem is that the data type of one of the columns is object. This is weird, as it indicates temperature. How do I change it to having a float data type? I tried to_numeric, but it can't parse it. weather.info() weather.head() <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 304 entries, 2017-01-01 to 2017-10-31 Data columns (total 2 columns): Temp 304 non-null object Rain 304 non-null float64 dtypes: float64(1), object(1) memory usage: 17.1+ KB Temp Rain Date 2017-01-01 12.4 0.0 2017-02-01 11 0.6 2017-03-01 10.4 0.6 2017-04-01 10.9 0.2 2017-05-01 13.2 0.0
has answer: http://stackoverflow.com/a/48094978
type: Question
has comment: http://stackoverflow.com/comment/83203937

http://stackoverflow.com/q/48076228
has comment: http://stackoverflow.com/comment/83126322
tagged with: python
has comment: http://stackoverflow.com/comment/83126211
type: AnsweredQuestion
score: 3
tagged with: list
upvote count: 3
has title: Remove items from tuple if substring exists
has body: I have a tuple that looks like this full = [('Ethernet4/3', 'odsa', 'connected'),('Port-Channel161', 'odsa', 'connected'),('Port-Channel545', 'odsa', 'connected')] I want to remove all the Port-Channels to return only the interfaces. I can hard code each Port-Channel in a list and remove it that way, but that isn't very scalable. I'm trying to remove anything with 'Port' in it from a list, so my script looks like this full = [('Ethernet4/3', 'odsa', 'connected'),('Port-Channel161', 'odsa', 'connected')] skip_interfaces = ['Ethernet49/1', 'Ethernet49/2', 'Ethernet49/3', 'Ethernet49/4', 'Ethernet50/1', 'Ethernet50/2', 'Ethernet50/3','Ethernet50/4','Ethernet51/1', 'Ethernet51/2', 'Ethernet51/3', 'Ethernet51/4', 'Ethernet52/1', 'Ethernet52/2', 'Ethernet52/3', 'Ethernet52/4', 'Port', 'Management1', 'Port-Channel44', 'Port-Channel34'] new = [tup for tup in full if tup[0] not in skip_interfaces] print new But when printed i still get [('Ethernet4/3', 'odsa', 'connected'),('Port-Channel161', 'odsa', 'connected'),('Port-Channel545', 'odsa', 'connected')] Is there a better way to remove items from a tuple when a substring is in a list? Thanks
has answer: http://stackoverflow.com/a/48076282
type: Question
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48076282
favorite count: 0
tagged with: tuples

http://stackoverflow.com/comment/83299228
score: 1
type: Comment
type: QuestionComment
has text: Can you provide python script you are trying to run? In addition, provide detail on the boot disk image/OS and python version you are running on the GCE instance.
comment on: http://stackoverflow.com/q/48158624

http://stackoverflow.com/q/48048095
tagged with: oop
score: 1
upvote count: 1
type: Question
has title: Class Decorators Excercise in Python
has comment: http://stackoverflow.com/comment/83068026
downvote count: 0
has answer: http://stackoverflow.com/a/48049035
answer count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83068201
has body: I'm learning Python from the video course Python Programming Language by David Beazley. I got stuck in this program where the author tried to decorate the Holding class by @typed. Unfortunately, although I believe I copied the code verbatim, it didn't seem to work according to plan. I duplicated the code in the function typed, in the main() at the bottom. It worked like a charm. Can anyone enlighten me on this? Many thanks. from typing import Union, List, Iterator from pprint import pprint import csv # Changes # make Typed.__init__(self, name=None) # create def typed(cls) # decorate class Holding with @typed # no need for the argument in String(), Integer(), Float() class Typed: expected_type = object def __init__(self, name=None): self.name = name def __get__(self, instance, cls): return instance.__dict__[self.name] def __set__(self, instance, value): if not isinstance(value, self.expected_type): raise TypeError(f'Expected {self.expected_type}') instance.__dict__[self.name] = value class Integer(Typed): expected_type = int class Float(Typed): expected_type = float class String(Typed): expected_type = str def typed(cls): for key, obj in vars(cls).items(): if isinstance(obj, Typed): obj.name = key print('in typed():', obj.name) return cls @typed class Holding: """Use proxy __setattr__() to limit attributes to design""" name = String() shares = Integer() price = Float() def __init__(self, name, date, shares, price): self.name = name self.date = date self.shares = shares self.price = price def __setattr__(self, name, value): if name not in {'name', 'date', 'shares', 'price'}: raise AttributeError(f'No attribute {name}') super().__setattr__(name, value) @property def cost(self): return self.shares * self.price def __str__(self) -&gt; str: return f'{self.shares} shares of {self.name} at {self.price}' def __repr__(self) -&gt; str: return f'Holding({self.name}, {self.date}, {self.shares}, {self.price})' class Portfolio: def __init__(self): self.holdings: List[Holding] = []…
tagged with: python
tagged with: python-decorators

http://stackoverflow.com/comment/83026851
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48028394
score: 0
has text: ... why do you think there should exist a `.len()` method???

http://stackoverflow.com/a/48055499
has body: In case all lines have the same length, you could do it without the need to parse the whole file or load it to memory, using dd. You have to know the lines number, having already executed wc -l, and the precise byte length of each line, and of course to have test and ensure all lines really have the same length. Even wc will be slow as it will read the whole file. For example, if every line is 20000 bytes #!/bin/bash for i in `shuf -n 10000 -i 0-1799999 | sort -n` do dd if=file bs=20000 skip="$i" count=1 of=output status=none \ oflag=append conv=notrunc done This way we loop and run 10K processes, I am not sure if it could be done at once, so although dd is faster, using a language, like Python and seek() method, (as @tripleee says and @Mad Physicist hinted at with comments) will have the advantage of one process. #!/usr/bin/python3 import random randoms = random.sample(range(0, 1800000), 10000) randoms.sort() lsize = 20000 with open("file", "rb") as infile, open('output', 'wb') as outfile: for n in randoms: infile.seek(lsize * n) outfile.write(infile.read(lsize)) save some more seconds, if output is small enough, you can keep it in a bytearray and write it at once at the end. with open("file", "rb") as infile, open('output', 'wb') as outfile: buf = bytearray() for n in randoms: infile.seek(lsize * n) buf.extend(infile.read(lsize)) outfile.write(buf)
has comment: http://stackoverflow.com/comment/83084047
answers question: http://stackoverflow.com/q/48050639
downvote count: 0
has comment: http://stackoverflow.com/comment/83106317
has comment: http://stackoverflow.com/comment/83083860
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/a/48168535
has comment: http://stackoverflow.com/comment/83316525
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/83347051
has body: So by reading 1060301, Im assuming thats year:106, month:03, and day:01, so perform different operations on the different lengthed numbers with this: valuelist = [] value = '' date = '' file = open('testfile.txt','r+') filetowriteto = open('OUTPUTFILE','a+') for line in file: for char in line: if char == ' ': if len(value) == 6: date = value[0:2]+'/'+value[2:4]+'/'+value[4:] elif len(value)==7: date = value[:3]+'/'+value[3:5]+'/'+value[5:] valuelist.append(date) value = '' date = '' else: value += char continue for t in valuelist: filetowriteto.write(t+' ') file.close() filetowriteto.close() Please don't hesitate to comment about anything.
answers question: http://stackoverflow.com/q/48167807
has comment: http://stackoverflow.com/comment/83338347
score: 0
accepted answer of: http://stackoverflow.com/q/48167807

http://stackoverflow.com/q/48054569
has body: I'm using Codecademany (I'm a beginner.) and I came across a problem that had to do with naming parameters. Ther is no error and it does what I want it to but I noticed that in line 19 it names the parameter variance, a previously defined variable. What I want to know is, what happens when a function calls its parameter and a variable by the same name. Does it call the variable or the argument? How does it decide? And how can I choose which one? grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5] def print_grades(grades_input): for grade in grades_input: print grade def grades_sum(scores): return sum(scores) def grades_average(grades_input): return grades_sum(grades_input) / float(len(grades_input)) def grades_variance(scores): variance = 0 for score in scores: variance += (grades_average(scores) - score) ** 2 return variance / len(scores) def grades_std_deviation(variance): return variance ** 0.5
has comment: http://stackoverflow.com/comment/83081532
has answer: http://stackoverflow.com/a/48054663
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/83081520
tagged with: function
tagged with: variables
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48054643
tagged with: arguments
tagged with: python
tagged with: parameters
has answer: http://stackoverflow.com/a/48054648
type: Question
has title: Naming Parameters in Python

http://stackoverflow.com/comment/83055753
comment on: http://stackoverflow.com/q/48042559
has text: List comprehension is not for executing for loop in single line, you are doing it totally wrong. You should read more about comprehensions
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/83406069
type: Comment
type: QuestionComment
has text: Yes the first part is taken into account, separate clauses in the code for t = -1 vs 0 <= t < 24. And I am not sure how a dict would be faster in this case than an array of t-values, in either sense don't you need to iterate until t satisfies the equation? (Also really interesting point on security :P, I guess we can look at this conversation as a breach as well :) ) Maybe I will delete later :)
comment on: http://stackoverflow.com/q/48160974
score: 0

http://stackoverflow.com/comment/83262540
type: Comment
type: QuestionComment
has text: yeap, `regex` can be non deterministic.
comment on: http://stackoverflow.com/q/48142203
score: 0

http://stackoverflow.com/a/48029912
answers question: http://stackoverflow.com/q/48029800
score: 1
has comment: http://stackoverflow.com/comment/135184233
has comment: http://stackoverflow.com/comment/83031336
has comment: http://stackoverflow.com/comment/83030130
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83031119
has comment: http://stackoverflow.com/comment/83030966
type: Answer
has comment: http://stackoverflow.com/comment/83030138
has comment: http://stackoverflow.com/comment/83030105
has comment: http://stackoverflow.com/comment/83030979
has comment: http://stackoverflow.com/comment/83031301
downvote count: 0
has comment: http://stackoverflow.com/comment/135182983
accepted answer of: http://stackoverflow.com/q/48029800
has comment: http://stackoverflow.com/comment/83030950
has body: There are two ways I can think to deal with this: Instead of importing specific names from a module with from ... import ..., just import the module itself. For example, in windows.py, instead of writing from elements import Container just write import elements and then when you want to create a Container, do it like this: self.container1 = elements.Container(WindowTypes.TYPE_1) The advantage of this approach is that you don't actually force the elements module to have anything in it named Container at the time the module is imported, and that way you solve your circular import problem. I won't get too far into the details of why this works (unless you're interested, I can edit), but the gist is that the first step in the import process involves marking the module as already being imported, so that any further import statements referring to the same module won't result in loading the file all over again. So if you import A which imports B which imports A again, the second time that import A is encountered, it doesn't do anything and doesn't continue the loop. You can take advantage of this to allow what would otherwise be circular imports in many cases, though there are times it doesn't work. Or you can just move the window types to a separate module. The type enumeration is something that can exist independently of the Window class, and it's not a bad idea to have it completely separate so that code which wants to use the types doesn't have to bring in the full windows module. I see why you'd want to keep the types together with the Window implementation, since the type isn't really used for anything else, but I don't think that's so necessary that it should keep you from moving the enumeration to a separate module. The implementation of windows could definitely span several modules. You could even make it a subpackage if you like, i.e. have a structure like test/ |-- __init__.py |-- windows/ |-- __init__.py |-- types.py |-- window.py |-- elements.py |-- test.py (a…

http://stackoverflow.com/comment/83288380
type: Comment
has text: I don't really understand your question... what is `test`???
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48154619

http://stackoverflow.com/q/48124639
has answer: http://stackoverflow.com/a/48124725
upvote count: 2
answer count: 2
tagged with: pandas
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83226351
possible better answer: http://stackoverflow.com/a/48124830
type: AnsweredQuestion
score: 2
has body: I have a dataframe called "signal_data" that has data as below Pressure DateTime Temp 3025 2016-04-01 00:17:00 TTY 3019 2016-04-01 00:17:00 TTY 3019 2016-04-01 00:17:00 TTY ..... 3025 2016-05-01 10:17:00 TTY ..... I am trying to get unique values from DateTime column and convert to list. When I apply the following command, the datetime values are getting converted to int but not datetime. signal_data['DateTime'].unique().tolist() [1459469820000000000, 1459516620000000000, 1459527420000000000, ... 1462087020000000000] May I know why this is happening and how to resolve this issue?
has answer: http://stackoverflow.com/a/48124830
has title: Pandas DataFrame Date Series to List conversion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48124725
type: Question

http://stackoverflow.com/q/48065611
has title: Parsing human readable calendar in Python
has comment: http://stackoverflow.com/comment/83104647
tagged with: python
has comment: http://stackoverflow.com/comment/83104858
has body: Each train of a railway company travels between a given range of stations only on some dates and only on some days of the week. The railway company has published a calendar which, for each train, shows when it travels. Texts on this calendar are clearly computer-generated by some script which looks dates up in a database. Sentences generated this way are really hard to understand at first, but they follow some rigid syntactic rules, so parsing them shouldn't be difficult with regular expressions and some string manipulation. Things become complex when dates overlap or are specified in a counter-intuitive way. I need to write a script which parses this calendar and returns, for each train, the dates and the days of the week on which it travels. Let's assume this calendar is valid for the current year (2018). Here are some example texts and how they should be parsed. Example #1 Original text: From [origin] to [destination] this train does not travel between 2018-01-01 to 2018-06-30 on non-working days. Meaning (explained): This trains always travels in 2018, but before 07/01 it only travels on working days. Example parsed data: [{"from": "2018-01-01", "to": "2018-06-30", "days": (1, 1, 1, 1, 1, 1, 0)}, # (mon, tue, wed, thu, fri, sat, sun) {"from": "2018-07-01", "to": "2018-12-31", "days": (1, 1, 1, 1, 1, 1, 1)}] Example #2 Original text: From [origin] to [X] this train travels between 2018-01-01 and 2018-12-31 every day. From [X] to [destination] this trains travels between 2018-01-01 and 2018-08-04 every day, between 2018-08-26 and 2018-12-31 every day. It does not travel between 2018-01-01 and 2018-08-04 on Saturday, on 2018-12-31, between 2018-08-26 and 2018-12-30 on Saturday, on Sunday. Meaning (explained): From [origin] to [X] the train always travels in 2018. From [X] to [destination] the train travels like so: from 01/01 to 08/04 every day but Saturday from 08/05 to 08/25 never from 08/26 to 12/30 every day but Saturday and Sunday. on 12/31 never. As you can s…
has comment: http://stackoverflow.com/comment/83104617
favorite count: 0
tagged with: parsing
score: 2
answer count: 0
has comment: http://stackoverflow.com/comment/83105156
type: UnansweredQuestion
downvote count: 1
upvote count: 3
tagged with: date
type: Question
has comment: http://stackoverflow.com/comment/83105566
has comment: http://stackoverflow.com/comment/83104522

http://stackoverflow.com/comment/83211728
has text: you forgot `root.mainloop()` - without `mainloop()` program may not work.
comment on: http://stackoverflow.com/q/48117575
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/83003150
score: 0
type: Comment
type: QuestionComment
has text: what is your expected output?
comment on: http://stackoverflow.com/q/48016979

http://stackoverflow.com/comment/83138161
type: Comment
comment on: http://stackoverflow.com/q/48079736
type: QuestionComment
has text: @DanFarrell Thanks for your help, that worked! But I think I&#39;m not able to write websocket messages from the other process. Is that even possible?
score: 0

http://stackoverflow.com/q/48081655
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83140436
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/105824068
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/48084009
has comment: http://stackoverflow.com/comment/83138443
upvote count: 3
accepted answer: http://stackoverflow.com/a/48084009
tagged with: web-scraping
tagged with: urllib
tagged with: http-status-code-403
has title: Python Web Scrape - 403 Error
has comment: http://stackoverflow.com/comment/83138074
has body: I'm trying to open up this website using python beautifulsoup and urllib but I keep getting a 403 error. Can someone guide me with this error? My current code is this; from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = 'https://www.cubesmart.com/florida-self-storage/st--petersburg-self-storage/3337.html?utm_source=local&amp;utm_medium=organic&amp;utm_campaign=googlemybusiness&amp;utm_term=3337' uClient = uReq(my_url) but I get the 403 error. I searched around and tried using the approach below, but it too is giving me the same error. from urllib.request import Request, urlopen url="https://www.cubesmart.com/florida-self-storage/st--petersburg-self-storage/3337.html?utm_source=local&amp;utm_medium=organic&amp;utm_campaign=googlemybusiness&amp;utm_term=3337" req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) web_byte = urlopen(req).read() webpage = web_byte.decode('utf-8') Any help is appreciated.

http://stackoverflow.com/comment/83248175
has text: i have put a separate question. Here is a link- https://stackoverflow.com/questions/48135506/how-to-change-switch-windows-using-gtk-application-gtk3-glade-python
type: Comment
comment on: http://stackoverflow.com/a/48128655
score: 0
type: AnswerComment

http://stackoverflow.com/a/50630812
accepted answer of: http://stackoverflow.com/q/48143769
has body: Spacy has a max_length limit of 1,000,000 characters. I was able to parse a document with 450,000 words just fine. The limit can be raised. I would split the text into n chunks depending upon total size. The v2.x parser and NER models require roughly 1GB of temporary memory per 100,000 characters in the input. This means long texts may cause memory allocation errors. If you're not using the parser or NER, it's probably safe to increase the nlp.max_length limit. The limit is in number of characters, so you can check whether your inputs are too long by checking len(text). https://github.com/explosion/spaCy/blob/master/spacy/errors.py
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 13
score: 13
answers question: http://stackoverflow.com/q/48143769

http://stackoverflow.com/comment/83144239
type: Comment
type: QuestionComment
has text: Correct me if I'm wrong, but those are... iterators, aren't they?
comment on: http://stackoverflow.com/q/48084356
score: 0

api
tags question: http://stackoverflow.com/q/48052641
tags question: http://stackoverflow.com/q/48030017
tags question: http://stackoverflow.com/q/48087466
tags question: http://stackoverflow.com/q/48025594
tags question: http://stackoverflow.com/q/48094939
tags question: http://stackoverflow.com/q/48030773
type: Tag
tags question: http://stackoverflow.com/q/48031599
tags question: http://stackoverflow.com/q/48158027
tag name: api
tags question: http://stackoverflow.com/q/48163325
tags question: http://stackoverflow.com/q/48025758
tags question: http://stackoverflow.com/q/48071949
tags question: http://stackoverflow.com/q/48100719
tags question: http://stackoverflow.com/q/48062228
tags question: http://stackoverflow.com/q/48122916
tags question: http://stackoverflow.com/q/48154467

http://stackoverflow.com/comment/113356953
score: 1
comment on: http://stackoverflow.com/q/48015613
type: Comment
type: QuestionComment
has text: Having the same problem. Did you figure out how to clear the memory?

http://stackoverflow.com/a/48020212
has body: What you have right now is pretty good (in my books). Although, you could substitute the n[:-1] with n, because zip performs a "shortest possible zipping" - zips upto the shorter of the two lists - &gt;&gt;&gt; list(zip([1, 2, 3], [4, 5])) [(1, 4), (2, 5)] So, you could rewrite your expression as - list(zip([(i+1) for i in n], n[1:])) For conciseness. Drop the list(..) for python 2. An alternative (suggested by RoadRunner), would be to bring the list comprehension out, and the zip in - &gt;&gt;&gt; [(x + 1, y) for x, y in zip(n, n[1:])] [(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)] Or, you can get rid of zip completely (as suggested by splash58), by using positional based indexing - &gt;&gt;&gt; [(n[i] + 1, n[i + 1]) for i in range(len(n) - 1)] [(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)] Another way to do this is using the functional programming paradigm, with map - &gt;&gt;&gt; list(zip(map(lambda x: x + 1, n), n[1:])) [(1, 6), (7, 12), (13, 18), (19, 24), (25, 30), (31, 36), (37, 42), (43, 48)] Which does the same thing your list comp does, but probably slower! And finally, if you use pandas (my favourite library), then you can leverage the IntervalIndex API - &gt;&gt;&gt; pd.IntervalIndex.from_breaks(n, closed='right') IntervalIndex([(0, 6], (6, 12], (12, 18], (18, 24], (24, 30], (30, 36], (36, 42], (42, 48]] closed='right', dtype='interval[int64]')
answers question: http://stackoverflow.com/q/48020089
type: Answer
has comment: http://stackoverflow.com/comment/83011775
upvote count: 5
has comment: http://stackoverflow.com/comment/83009476
score: 5
accepted answer of: http://stackoverflow.com/q/48020089
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83112160
type: Comment
comment on: http://stackoverflow.com/q/48067726
score: 0
has text: I mean i want to group similar 'group_names' based on the data, and the predictions it has made.
type: QuestionComment

http://stackoverflow.com/comment/83050716
score: 0
type: Comment
type: QuestionComment
has text: @sstyvane this is wrong duplicate. OP is not updating `Gender` field using value of another field but the same field.
comment on: http://stackoverflow.com/q/48031026

http://stackoverflow.com/a/66182524
has body: from selenium import webdriver from django.urls import reverse import time class TestApiPages(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Chrome('functional_test/chromedriver.exe') def tearDown(self): self.browser.close() def test_api_list_displayed(self): self.browser.get(('%s%s' % (self.live_server_url, '/admin/')))
upvote count: 2
answers question: http://stackoverflow.com/q/48041841
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/83178188
type: Comment
has text: Thanks! The problem was ids. I made them unique by adding album's pk to their ending. Now it's working as expected.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48101399

http://stackoverflow.com/comment/83309793
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48165302
has text: have you considered running only one instance of the object in all of your scripts and using process communication to tell it what to write?

http://stackoverflow.com/a/48069055
has comment: http://stackoverflow.com/comment/83139149
answers question: http://stackoverflow.com/q/48068011
score: 0
has comment: http://stackoverflow.com/comment/83136563
type: Answer
has body: For me the easiest way would be to use the coordinate equations for a sphere and work from there. x = a * cos(u) * cos(v) y = b * cos(u) * sin(v) z = c * sin(u) You can construct these coordinates with np.meshgrid and then plot. a, b, c = 4, 8, 6 space = np.linspace(0, 2 * np.pi, 50) u, v = np.meshgrid(space) x = a * np.cos(u) * np.cos(v) y = b * np.cos(u) * np.sin(v) z = c * np.sin(u) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(x, y, z) fig.show() Update To get the interior coordinates of the sphere you would use the mask akin to your example, but with the ellipsoid implicit equation. x^2/a^2 + y^2/b^2 + z^2/c^2 = 1 a, b, c = 4, 8, 6 xs, ys, zs = np.mgrid[-a + 1:a + 1:15j, -b + 1:b + 1:15j, -c + 1:c + 1:15j] mask = xs**2/(a**2) + ys**2/(b**2) + zs**2/(c**2) &lt;= 1 xs[~mask] = 0 ys[~mask] = 0 zs[~mask] = 0 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(xs, ys, zs) fig.show()

http://stackoverflow.com/a/48084714
score: 0
type: Answer
has body: Here is some psuedo code to make a Kivy question widget. class Question(object): question_text = "" question_answer = "" question_widget = None def __init__(self, qtext): self.question_text = qtext def answer(self): # handle your answer class QuestionDisplay(GridLayout): def __init__(self, question_list, **kwargs): super(QuestionDisplay, self).__init__(**kwargs) self.rows = 6 self.spacing = 10 self.padding = 10 self._ql = question_list # keep a reference to your question list self.q_index = 0 self.q_id = Label(text='Question') self.q_txt = TextInput(text='') self.add_widget(self.q_id) self.add_widget(self.q_txt) self.get_next_question() def get_next_question(self): # after your button saves the answer, call this to load next question self.q_index += 1 # display the next question in the list self.q_txt.text = self._ql[self.q_index].question_text self._ql[self.q_index].widget = self # keep a reference to this widget in the question object; might be useful my_questions = [Question(''), Question('2+2'), Question('3+3')] # First question blank my_q_widget = QuestionDisplay(my_questions) This code is just an example of one way to do it. It doesn't handle your button clicks. It should give you an idea of how to organize your code to achieve this in and object oriented way.
answers question: http://stackoverflow.com/q/48083856

http://stackoverflow.com/q/48161673
tagged with: sqlalchemy
type: Question
has title: How to use SQLAlchemy core to select all table columns except 1 specific column in postgresql?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48162124
favorite count: 0
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
has body: I use mostly SQLAlchemy core(v.1.0.8) expression language with flask(0.12) to create API calls. For a particular case where the table has 20 columns, I wish to select all except 1 particular column. How can this be done in the 'select' clause? Is there anything like 'except' that can be used instead of explicitly selecting the columns by names?
score: 7
has comment: http://stackoverflow.com/comment/83302727
upvote count: 7

http://stackoverflow.com/comment/83114177
has text: If the previous developer left in good terms, I'd ask him. Really!! Also, to replicate complex environments in your laptop you can take a look to Docker and Docker-compose. Also, investigate how to create backups of your production data. And ask yourself: How important is that server? Are users using it as of now? Having `:8000` in a URL seems to indicate that the server is not really used?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48070008

http://stackoverflow.com/comment/83282709
score: 2
has text: Is there a reason you feel that using a dict to do something similar won't work?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48152140

http://stackoverflow.com/comment/83029533
has text: @StephenRauch Thanks for noticing, I corrected the example.
score: 0
comment on: http://stackoverflow.com/q/48029517
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83088806
has text: No I mean in https://www.digitalocean.com/community/tutorials/how-to-format-text-in-python-3 it is given \ itselp is escape character. It is used for new-line in muti line string
comment on: http://stackoverflow.com/a/48058288
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48017036
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/83004344
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48017009
has comment: http://stackoverflow.com/comment/83014932
answers question: http://stackoverflow.com/q/48017009
type: AcceptedAnswer
downvote count: 0
has body: According to the documentation here https://docs.python.org/2/library/subprocess.html it will return 1 when it fails, also check that there is a warning if you use the attribute shell=True

http://stackoverflow.com/comment/83158015
has text: I added 'user_id' column in profile model,
comment on: http://stackoverflow.com/q/48089545
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83210714
has text: @WarrenWeckesser 16GB of RAM...can the assignment operation be done incrementally for the given expression `1.5 - 0.5 * K * K` ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48116700

http://stackoverflow.com/comment/83260321
type: QuestionComment
has text: Can you send us the URL so we can try it out? Most likely problem is that the input box is not loading immediately, in which case you can put a few seconds' delay on your request.
comment on: http://stackoverflow.com/q/48141221
score: 0
type: Comment

http://stackoverflow.com/comment/83246478
has text: I doubt things like this can ever be done without for loops.
comment on: http://stackoverflow.com/a/48066870
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48133914
type: Question
score: 0
has answer: http://stackoverflow.com/a/48134056
has body: So, I have a dataframe with more that 10^6 lines in it and I am just doing a simple conversion of lat (degrees min) to lat (degrees only). Yet there are lines in my frame which have a string "p-" which kills my loop early on. I have tried a few things (below). Code: import pandas as pd import numpy as np import glob import matplotlib.pyplot as plt path = r'/home/engr/Documents/SchoolHR/Data/SFSU-Boat/SBE45m/2015/' allfiles_list = glob.glob(path + "/15*.hex") allfiles_list = sorted(allfiles_list) col = ["temp", "conduct", "salinity", "lat", "lon", "hms", "dmy"] big_frame = pd.DataFrame() for name in allfiles_list: df = pd.read_csv(name, skiprows=12, encoding="latin1", names=col, na_values=0, na_filter=False, engine="c") big_frame = big_frame.append(df) # TODO surgery on columns to convert to float for use on big_frame # regex \D to remove any non-digit characters -- hms &amp; dmy big_frame["hms"].replace(regex=True,inplace=True,to_replace=r'\D',value=r'') big_frame["dmy"].replace(regex=True,inplace=True,to_replace=r'\D',value=r'') big_frame["temp"].replace(regex=True,inplace=True,to_replace='(\D.\=)',value='') big_frame["conduct"].replace(regex=True,inplace=True,to_replace='(\D.\=)',value='') big_frame["salinity"].replace(regex=True,inplace=True,to_replace='(\D.\=)',value='') big_frame["lat"].replace(regex=True,inplace=True,to_replace='[lonat=]',value='') big_frame["lon"].replace(regex=True,inplace=True,to_replace='[lonat=]',value='') for index, row in big_frame.iterrows(): if row.lat[-1] == 'N': D = float(row.lat[1:3]) M = float(row.lat[4:10]) DD = D + float(M/60) row.lat = DD if row.lon[-1] == 'W': D1 = float(row.lon[1:4]) M1 = float(row.lon[5:12]) DD1 = D1 + float(M1/60) row.lon = -DD1 the code returns this error: ValueError: could not convert string to float: 'p-' I tried modifying the code by doing this and running the loop on the dataframe: big_frame['lon'] = big_frame.lon.str.replace('p-?' , '') big_frame['lat'] = big_frame.lat.str.replace('p-?' , '') big_fram…
has title: pandas ValueError: could not convert string to float: 'p-'
tagged with: pandas
answer count: 1
tagged with: geography
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83031765
comment on: http://stackoverflow.com/q/48030675
score: 0
has text: @furas I'm not worried about the server errors, I am more worried about the fact that it takes the same amount of time to load google or any other website.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83519069
has text: what is the x.name above referring to?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48107035

http://stackoverflow.com/q/48032545
has body: My code works and outputs the email to the console but I don't receive any email in my inbox. My settings: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'youremail@gmail.com' EMAIL_HOST_PASSWORD = 'yourpassword' EMAIL_PORT = 587
has answer: http://stackoverflow.com/a/48032747
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Email verification after signup code works but email is not sent
type: Question
linked to: http://stackoverflow.com/q/4642011
has answer: http://stackoverflow.com/a/48032612
score: 0
answer count: 2

http://stackoverflow.com/q/48061901
downvote count: 0
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51123810
linked to: http://stackoverflow.com/q/27885397
answer count: 3
linked to: http://stackoverflow.com/q/4750806
score: 1
has title: How to use pip to install .whl in python shell?
has body: I have downloaded a wheel file for Python module. The .whl file is now in the same folder where Scripts folder is located. C:/Python27. The name of the .whl file is shown as below: pandas-0.22.0-cp37-cp37m-win_amd64.whl Please tell me how to use pip for installing the .whl file in Python console (not the command line). Something similar to installing tweepy. C:\Python27\ArcGIS10.5&gt;python2.exe &gt;&gt;&gt; import pip &gt;&gt;&gt; pip.main(['install','tweepy'])
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/66978746
type: Question
has answer: http://stackoverflow.com/a/48170476

http://stackoverflow.com/comment/83069849
type: QuestionComment
has text: Sorry, but what is your aim here?
comment on: http://stackoverflow.com/q/48049133
score: 0
type: Comment

http://stackoverflow.com/comment/83155438
score: 0
comment on: http://stackoverflow.com/q/48077745
type: Comment
type: QuestionComment
has text: @MikhailGerasimov, thank you very much, the solution for me was in removing of the python 3.6.4 x32, removing of the virtual environment and recreating it with new python 3.6.4 x64

http://stackoverflow.com/comment/83245725
score: 0
type: Comment
has text: The function is `is_displayed()` not `.isdisplay()`.
type: AnswerComment
comment on: http://stackoverflow.com/a/48130710

http://stackoverflow.com/comment/83008189
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48019310
type: Comment
has text: `70` is really small, better is tets `1000` or more. But it depends of real data - number of rows and size of values in groups.

http://stackoverflow.com/comment/83158554
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48074018
has text: @majorcoder Aha! Sorry, I'd missed "1 row" in your question. I've updated my answer.
score: 0

http://stackoverflow.com/comment/83152960
type: Comment
type: QuestionComment
score: 1
has text: I really doubt that's what you wanna do... In any case, that'd depend on which terminal you're using and if it offers some kind of method to externally changing the directory. What is it you want to exaclty do? Usually, you `cd` in your spawned process, run whatever you need to run and capture its output
comment on: http://stackoverflow.com/q/48089135

http://stackoverflow.com/comment/83149135
score: 2
comment on: http://stackoverflow.com/q/48087036
has text: Pretty sure @jwodder is right... If right after the `import pickle` you add the line `print(pickle.__file__)` and run the code what do you see?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83115392
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48070598
has text: OK, in this case, you can only pass several arguments instead of only one list. Or you can unwrap list first `tri.point_inside(*[100,100,100])`
type: AnswerComment

http://stackoverflow.com/comment/83238093
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48087980
has text: Honestly (and without being an expert at all), I don't *think* you can do this in a single query using Django's 1.10 ORM... Subqueries are introduced in Django 1.11 and (as you said) window expressions are introduced in 2.0 **:-(**

http://stackoverflow.com/q/48119528
downvote count: 0
has comment: http://stackoverflow.com/comment/83215724
has title: python mysql syntax error - VALUES ('2' at line 1")
favorite count: 0
has comment: http://stackoverflow.com/comment/83215887
has comment: http://stackoverflow.com/comment/83215916
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83215718
has body: I am new in python . I try write skript for parsing to mysql. Part of my code : db = MySQLdb.connect(host="localhost", user="me", passwd="passwd", db="Data") with db: cursor = db.cursor() with open("my.log","rw") as f: next(f) for line in f: result = parser(line) resultS = parserS(result[3]) format = '[%a %b %d %H:%M:%S.%f %Y]' now = datetime.datetime.strptime(result[0], format) sql = ("INSERT INTO Data.table1 (time, level, id, error, file ,ip, request) VALUES (%s, %s, %s, %s, %s, %s, %s)") data = (now.strftime('%Y-%m-%d %H:%M:%S %f'), result[1], result[2], ' ' ,resultS[0],resultS[1],resultS[2]) cursor.execute(sql, data) f.close() db.close() When I try to run it give me that message : Traceback (most recent call last): File "parsingApacheErrorFrom.py", line 81, in &lt;module&gt; cursor.execute(sql, data) File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 226, in execute self.errorhandler(self, exc, value) File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-error (time, log_level, pid, error_status, file ,client_ip, message) VALUES ('2' at line 1") I try to find error in my sql syntax but it look fine for me. And I dont understood what mean : VALUES ('2' at line 1") ??? In mysql table, first column is type datetime, all others columns are varchar (255).
has comment: http://stackoverflow.com/comment/83216513
answer count: 0
has comment: http://stackoverflow.com/comment/83215992
has comment: http://stackoverflow.com/comment/83215430
tagged with: mysql
has comment: http://stackoverflow.com/comment/83215662
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83215781
has comment: http://stackoverflow.com/comment/83219178
score: 1
tagged with: syntax-error
has comment: http://stackoverflow.com/comment/83216106
linked to: http://stackoverflow.com/q/17951180
tagged with: sql

http://stackoverflow.com/comment/83111451
has text: @Ajax1234 That should work but it is not very readable.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48068576
type: Comment

http://stackoverflow.com/q/48073293
has title: slice a query result string field in annotation using Substr and negative values
linked to: http://stackoverflow.com/q/41105294
favorite count: 0
accepted answer: http://stackoverflow.com/a/48073478
tagged with: python
tagged with: annotate
upvote count: 2
tagged with: substr
tagged with: django
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48073478
type: Question
has body: I am trying to slice the last two characters of a field and annotate it to query result, using the method given in this post. Something like: Person.objects.all()\ .annotate( code = Substr('str', 1, -2), ) The above code returns an empty string as soon as I use negative values as the third argument. How can I achieve this?
answer count: 1
downvote count: 0

l-systems
type: Tag
tag name: l-systems
tags question: http://stackoverflow.com/q/48113662

http://stackoverflow.com/comment/83078052
comment on: http://stackoverflow.com/q/48052576
has text: Can you show the models?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/83177972
type: Comment
has text: how can `column` be equal to `p` when `p` is an integer and `column` is a list? That achieves nothing.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48100079

http://stackoverflow.com/q/48020149
upvote count: 2
type: UnansweredQuestion
score: 2
tagged with: performance
has title: Severe efficiency problems with generating combinations
has body: I'm trying to solve this question: Given a positive integral number n, return a strictly increasing sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n². If there are multiple solutions (and there will be), return the result with the largest possible value: Basically, a squared number deconstructed into smaller squares. However, my code only works for smalls numbers efficiently (20 being roughly the max for the first piece of code, 30~ for second) and is exponentially slower onwards. How can I develop the code? I don't know enough about efficiency in a language and be able to apply to my code and I tried optimising it by reducing the memory usage by setting comb to take out any bits of irrelevant data for the one below For the second piece of code I tried using recursion to solve my problem but it still is getting exponentially slower. Perhaps I need a new method? Much appreciated. import itertools as it from math import sqrt def decompose(n): squares = [i ** 2 for i in range(1, n) if (i ** 2)/2 &lt; n ** 2] comb = [list(i) for i in (reduce(lambda acc, x: acc + list(it.combinations(squares, x)), range(1, len(squares) + 1), [])) if sum(i) == n ** 2] print [int(sqrt(i)) for i in max(comb)] decompose(20) this was the first attempt, failed in efficiency so I tried this. from math import sqrt stuff = [] def decompose(a): def subset_sum(numbers, target, partial=[]): s = sum(partial) if s == target: stuff.append(partial) if s &gt;= target: return for i in range(len(numbers)): n = numbers[i] remaining = numbers[i+1:] subset_sum(remaining, target, partial + [n]) compare = 1 large = None subset_sum([x**2 for x in range(1, a)], a**2) for y in stuff: if compare &lt; y[-1]: compare = y[-1] large = y print [int(sqrt(o)) for o in large] decompose(30)
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/83010184
tagged with: python
has comment: http://stackoverflow.com/comment/83055747
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83009733

http://stackoverflow.com/comment/83308616
score: 0
type: Comment
has text: By change the reference to the list variable in the call to groupby I meant change it from `list` to `list1` in your third line where you're assigning to `list2`.
type: AnswerComment
comment on: http://stackoverflow.com/a/48164057

http://stackoverflow.com/a/48123430
answers question: http://stackoverflow.com/q/48122798
type: AcceptedAnswer
upvote count: 17
type: Answer
has comment: http://stackoverflow.com/comment/83234514
downvote count: 0
score: 17
has body: There have been several issues over the history of Python (most fixed in recent versions) reading more than 2-4 GB at once from a file handle (an unfixable version of the problem also occurs on 32 bit builds of Python, where they simply lack the virtual address space to allocate the buffer; not I/O related, but seen most frequently slurping large files). A workaround available for hashing is to update the hash in fixed size chunks (which is a good idea anyway, since counting on RAM being greater than file size is a poor idea). The most straightforward approach is to change your code to: with open(file, 'rb') as f: hasher = hashlib.sha256() # Make empty hasher to update piecemeal while True: block = f.read(64 * (1 &lt;&lt; 20)) # Read 64 MB at a time; big, but not memory busting if not block: # Reached EOF break hasher.update(block) # Update with new block print('SHA256 of file is %s' % hasher.hexdigest()) # Finalize to compute digest If you're feeling fancy, you can "simplify" the loop using two-arg iter and some functools magic, replacing the whole of the while loop with: for block in iter(functools.partial(f.read, 64 * (1 &lt;&lt; 20)), b''): hasher.update(block) Or on Python 3.8+, with the walrus operator, := it's simpler without the need for imports or unreadable code: while block := f.read(64 * (1 &lt;&lt; 20)): # Assigns and tests result in conditional! hasher.update(block)
accepted answer of: http://stackoverflow.com/q/48122798

http://stackoverflow.com/a/48030187
answers question: http://stackoverflow.com/q/48030116
type: Answer
score: 2
has body: You are finding the python version of freopen(). You can set the sys.stdin to a file object simply do the following: import sys sys.stdin = open("/path/to/file.txt", "r") text = input() print(text) The input() function will now read data from file instead of user input. More Usage Similarly, if you want to redirect the standard output or standard error to a file, just set the corresponding variables in sys: sys.stdout = open("stdout.txt", "w") sys.stderr = open("stderr.txt", "w")
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48030116
upvote count: 2

http://stackoverflow.com/q/48150823
has comment: http://stackoverflow.com/comment/83280606
tagged with: python
has comment: http://stackoverflow.com/comment/83283445
has comment: http://stackoverflow.com/comment/83281058
has answer: http://stackoverflow.com/a/48151215
has comment: http://stackoverflow.com/comment/83281126
has body: I am writing a simple client/server socket program where clients connect with server and communicate and then they send exit msg to server and then server closes the connection. The code looks like below. server.py import socket import sys from threading import Thread try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # This is to prevent the socket going into TIME_WAIT status and OSError # "Address already in use" sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except socket.error as e: print('Error occured while creating the socket {}'.format(e)) server_address = ('localhost', 50000) sock.bind(server_address) print('**** Server started on {}:{} ****'.format(*server_address)) sock.listen(5) def client_thread(conn_sock, client_add): while True: client_msg = conn_sock.recv(1024).decode() if client_msg.lower() != 'exit': print('[{0}:{1}] {2}'.format(*client_add, client_msg)) serv_reply = 'Okay ' + client_msg.upper() conn_sock.send(bytes(serv_reply, 'utf-8')) else: conn_sock.close() print('{} exitted !!'.format(client_add[0])) sys.exit() try: # Keep the server until there are incominmg connections while True: # Wait for the connctions to accept conn_sock, client_add = sock.accept() print('Recieved connection from {}:{}'.format(*client_add)) conn_sock.send( bytes('***** Welcome to {} *****'.format(server_address[0]), 'utf-8')) Thread(target=client_thread, args=( conn_sock, client_add), daemon=True).start() except Exception as e: print('Some error occured \n {}'.format(e)) except KeyboardInterrupt as e: print('Program execution cancelled by user') conn_sock.send(b'exit') sys.exit(0) finally: sock.close() client.py import socket import sys sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 50000) print('Connecting to {} on {}'.format(*server_address)) sock.connect(server_address) def exiting(host=''): print('{} exitted !!'.format(host)) sys.exit() while True: serv_msg = sock.recv(1024).decode() if serv_msg.lower()…
has comment: http://stackoverflow.com/comment/83281888
has comment: http://stackoverflow.com/comment/83281227
type: Question
has comment: http://stackoverflow.com/comment/83280468
has title: Closing clients sockets after server has exited
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/83281162
has comment: http://stackoverflow.com/comment/83280862
has comment: http://stackoverflow.com/comment/83281076
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83280242
tagged with: sockets
has comment: http://stackoverflow.com/comment/83280772
has comment: http://stackoverflow.com/comment/83280996

http://stackoverflow.com/q/48052487
tagged with: loops
has comment: http://stackoverflow.com/comment/83077136
type: Question
has title: Return True and stop if first item in list is matches, return false if no item matches
has comment: http://stackoverflow.com/comment/83077387
has comment: http://stackoverflow.com/comment/83077513
has comment: http://stackoverflow.com/comment/83077301
has answer: http://stackoverflow.com/a/48053742
has answer: http://stackoverflow.com/a/48052720
has answer: http://stackoverflow.com/a/48052882
answer count: 3
has comment: http://stackoverflow.com/comment/83077190
has comment: http://stackoverflow.com/comment/83077175
favorite count: 0
has comment: http://stackoverflow.com/comment/83077070
has comment: http://stackoverflow.com/comment/83077099
upvote count: 2
type: UnansweredQuestion
has body: I wrote a function to check a string based on the following conditions: Check if any word in the string is in list 1. If string in list 1, return position to see if the item next to it in the string is in list 2. If in list 1 and in list 2, return True. Else return False. The tricky part is that those lists are really long. So to be efficient, the first occurrence in list 2 will return True and move on to the next string. Below is the code that I have choked up but I doubt it is working as intended. Efficiency is really the key her as well. I tried creating a full combination of list 1 and list 2 and then loop through but it seems a bit insane looping over 100 million times per string. 1st Code: def double_loop(words): all_words = words.split() indices = [n for n,x in enumerate(allwords) if x in list1] if len(indices) != 0: for pos in indices[:-1]: if all_words[pos+1] in list2: return True #the purpose here is not to continue looking #through the whole list of indices, but end as soon as list2 contains an item 1 position after. break else: return False I am unsure whether the code above is working based on my logic above. In comparison; 2nd Code: def double_loop(words): all_words = words.split() indices = [n for n,x in enumerate(allwords) if x in list1] if len(indices) != 0: indices2 = [i for i in indices[:-1] if all_words[i+1] in list2] if len(indices2) != 0: return True else: return False else: return False has the same run time based on my test data. I guess the clearer question is, will my first code actually run till it finds the "first" element that meets its criteria and break. Or is it still running through all the elements like the second code.
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/83077610
has comment: http://stackoverflow.com/comment/83077127
has comment: http://stackoverflow.com/comment/83077422
score: 1

http://stackoverflow.com/comment/83087866
has text: I guess this one could improve the run-time by a tiny bit, so I'll be sure to add it. Thank you!
comment on: http://stackoverflow.com/a/48054236
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83170666
type: QuestionComment
type: Comment
has text: Indeed, even for very large ranges. And it can be even faster if changed to `any(i1 in range2 for i1 in range1)`
score: 0
comment on: http://stackoverflow.com/q/48095978

http://stackoverflow.com/comment/83179602
has text: So, those three functions all called `keyword` at the top? When the program executes, **only the last one of those** can get used. Each time you set up a new function with the same name, it _overwrites_ any previous function by that name.
comment on: http://stackoverflow.com/q/48102109
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/a/48030915
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48030702
has comment: http://stackoverflow.com/comment/83032220
downvote count: 0
has body: Here's a very different approach: action_tests = [ ('buy', lambda x: x &lt;= 5), ('hold', lambda x: (5 &lt; x &lt;= 7) and (x != 6)), ('short-sell', lambda x: x == 6), ] stock = [next((action for action, test in action_tests if test(i)), 'sell') for i in range(10)] The "else" condition is handled by the default value of next in the case that none of the tests return true for your action_tests. You really don't want to be squeezing all your complicated logic into a single line because it will make maintainability a nightmare - it will be hard to detect bugs, and even harder to add more logic down the line when the spec changes. This approach is an improvement over the original set if if statements in that it is easily extendable... simply add new functions to the action_tests in the appropriate priority order and the comprehension still works! Only a single line needs to be added when you want to add support for some new action down the road, rather than potentially having to rework your if branches.

http://stackoverflow.com/q/48029713
type: Question
answer count: 2
tagged with: lisp
has title: using the lisp application from AutoCAD with Python 3.5
score: 0
has answer: http://stackoverflow.com/a/48043101
tagged with: gml
has body: I have 6000+ .gml files that hold the informations about cadastrial particles. I also have a .lsp application for AutoCAD (I didn't write the code) which reads the .gml file and draws the particle in .dxf file. The problem is that the application can only take one .gml file as an input so it's too much of a job doing it manually. As I wrote the script to download those all .gml files from server in Python 3.5., I would like to know if there is a way to run the ACAD applications with Python, so I can loop through all the files and run the app? Thank you for reading.
tagged with: autocad
type: UnansweredQuestion
tagged with: autolisp
tagged with: python
has answer: http://stackoverflow.com/a/48030315

http://stackoverflow.com/comment/83240681
comment on: http://stackoverflow.com/a/48124665
score: 1
has text: I used matplotlib and was able to get my chart working, thanks for the recommendation.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83362170
comment on: http://stackoverflow.com/q/48161567
has text: Can you provide an audio clip with associated time stamps for extraction or removal?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/54429913
has body: it's an import issue: try changing the order of the imports: try: from django.contrib.auth.models import AbstractUser then: from django.db import models
upvote count: 0
score: -1
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48077112

http://stackoverflow.com/a/48144813
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83267783
has comment: http://stackoverflow.com/comment/83268417
type: Answer
has comment: http://stackoverflow.com/comment/83268121
answers question: http://stackoverflow.com/q/48144644
accepted answer of: http://stackoverflow.com/q/48144644
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/83267803
has body: That is because norm='l2' is the default setting. It means it is L2 normalizing the matrix so that all values lie between 0 and 1. You can turn that off by using norm=None and you will get the same values for Tfidf - doc = ["NAME LASTNAME DOB CITY", "NAME ADDRESS CITY", "NAME LASTNAME ADDRESS CITY", "NAME LASTNAME ADDRESS CITY PINCODE", "NAME ADDRESS PINCODE"] from sklearn.feature_extraction.text import TfidfVectorizer vec = TfidfVectorizer(norm=None) tf_idf = vec.fit_transform(doc) print(vec.get_feature_names()) print(tf_idf.todense()) Output ['address', 'city', 'dob', 'lastname', 'name', 'pincode'] [[ 0. 1.18232156 2.09861229 1.40546511 1. 0. ] [ 1.18232156 1.18232156 0. 0. 1. 0. ] [ 1.18232156 1.18232156 0. 1.40546511 1. 0. ] [ 1.18232156 1.18232156 0. 1.40546511 1. 1.69314718] [ 1.18232156 0. 0. 0. 1. 1.69314718]] P.S: It is always better to normalize your feature matrix UPDATE With L2 Norm, each number is divided with the square root of the sum of the squares of the rows. Example - For row 1:column 4, 1.40546511 will be divided by the square root of the sum of squares of row 1. Here is code that shows this - import math first_doc = tf_idf.todense()[0].tolist()[0] l2 = math.sqrt(sum([i*i for i in first_doc])) print(l2) print([i/l2 for i in first_doc]) Output 2.9626660243635254 [0.0, 0.39907351927997176, 0.7083526362438907, 0.4743920160255332, 0.3375338265523302, 0.0] In this case I just manually calculated what TfidfVectorizer would have done with norm='l2'. Notice how all values are between 0 and 1. This is one of the techniques to normalize your data. Normalization helps algorithms to converge quicker and have more accuracy. I hope this clears it up.

http://stackoverflow.com/a/48172667
has comment: http://stackoverflow.com/comment/83325133
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83325165
has body: pd.crosstab(df.index,df.CATZ)'AAA','BBB' Out[66]: CATZ AAA BBB row_0 0 1 0 1 0 1 2 1 0 3 0 0 4 0 1 5 0 0 6 0 0 7 0 0 pd.concat([df,pd.crosstab(df.index,df.CATZ)'AAA','BBB'],1) Out[68]: CATX CATY CATZ AAA BBB row_0 0 A G AAA 1 0 1 B H BBB 0 1 2 C I AAA 1 0 3 B J CCC 0 0 4 A G BBB 0 1 5 B H DDD 0 0 6 D K EEE 0 0 7 E L FFF 0 0
upvote count: 2
answers question: http://stackoverflow.com/q/48172529
type: Answer

http://stackoverflow.com/a/48071408
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/83116917
has comment: http://stackoverflow.com/comment/83116502
has comment: http://stackoverflow.com/comment/83116973
has comment: http://stackoverflow.com/comment/83116450
has body: You are trying to compare date1 with 0. That would not work since date1 is a datetime.date (See how you define it initially). So basically you are comparing a date with an int. You can compare only similar types.
upvote count: 1
answers question: http://stackoverflow.com/q/48071339
score: 0

http://stackoverflow.com/comment/83318323
score: 0
type: Comment
type: QuestionComment
has text: `matrix=np.array([[9,10,11,12],[8,7,6,5],[1,2,3,4]], dtype=object)` will do what you want but I do not think it is a good idea. The `X` seems to be a presentation detail, not a data item.
comment on: http://stackoverflow.com/q/48169184

http://stackoverflow.com/comment/83184908
comment on: http://stackoverflow.com/a/48104489
type: Comment
score: 0
type: AnswerComment
has text: `which in turn is implemented differently per class` - could you elaborate on this? I feel like there is something important packed inside this statement!

http://stackoverflow.com/q/48027878
favorite count: 0
has comment: http://stackoverflow.com/comment/83025607
score: 0
downvote count: 1
has title: Conversion of Python code to executable
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/16770267
has comment: http://stackoverflow.com/comment/83025824
linked to: http://stackoverflow.com/q/17907258
has body: How can you convert a python3 code to become executable. I am aware of py2exe program but its only for python2. Am asking if there is any program for python3 to exe
type: Question
has answer: http://stackoverflow.com/a/48027980
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83029273

http://stackoverflow.com/comment/83297803
type: Comment
comment on: http://stackoverflow.com/a/48158697
type: AnswerComment
score: 0
has text: i appreciate your help, but i need the row deleted if it matches this Curriculum Name,,Organization Employee Number,Employee Department,Employee Name,Employee Email,Employee Status,Date Assigned,Completion Date,Completion Status,Manager Name,Manager Email

http://stackoverflow.com/a/48154418
has body: Your problem appears to be with this line in on_message(), as pointed out in this comment: server = message.channel.server.id The traceback indicates that the discord.py library is trying to use the id attribute of the server you pass it; currently, you're passing it the ID, but you probably need to pass the whole server object. IOW, do this instead: server = message.channel.server Since invites_from is a coroutine, you'll also need to await it: invites = await bot.invites_from(server)
answers question: http://stackoverflow.com/q/48153414
has comment: http://stackoverflow.com/comment/83289537
score: 0
has comment: http://stackoverflow.com/comment/83288937
has comment: http://stackoverflow.com/comment/83296673
has comment: http://stackoverflow.com/comment/83295595
type: Answer

http://stackoverflow.com/comment/83252198
has text: I am not getting the first part ie. add parameter name for columns names and parse_date for datetimes to read_csv. Should I add manually? I have thousands of those files. Also I could not understand the first part of the code temp =u """ ... """ . I am beginner in python.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48126415
type: AnswerComment

http://stackoverflow.com/a/48028358
has body: I would use the non-hungry .*? expression with a trailing quote: import re string = """$deletedFields":["standardizedSkillUrn","standardizedSkill"],"entityUrn":"urn:li:fs_skill:(ACoAAAIv9SQBMzclPm3CZzL1QceTH5W0VrsdxbE,3)","name":"Finance","$type":"voyager.identity.profile.Skill"},{"$deletedFields":["standardizedSkillUrn","standardizedSkill"],"entityUrn":"urn:li:fs_skill:(ACoAAAIv9SQBMzclPm3CZzL1QceTH5W0VrsdxbE,22)","name":"Financial ["standardizedSkillUrn","standardizedSkill"],"entityUrn":"urn:li:fs_skill:(ACoAAAIv9SQBMzclPm3CZzL1QceTH5W0VrsdxbE,34)","name":"Due Diligence","name":"Strategy""" # With the leading double quote match = re.compile(r'"name"\:(".*?)["\[]') a = match.findall(string) print a # Stripping out the leading double quote match = re.compile(r'"name"\:"(.*?)["\[]') b = match.findall(string) print b And the final output is: ['"Finance', '"Financial ', '"Due Diligence'] ['Finance', 'Financial ', 'Due Diligence']
type: Answer
answers question: http://stackoverflow.com/q/48028258
score: 0

http://stackoverflow.com/comment/83103173
type: QuestionComment
has text: If your answer works, it's the best one.
comment on: http://stackoverflow.com/q/48064232
score: 0
type: Comment

http://stackoverflow.com/q/48105735
favorite count: 0
has body: I need to send a request from the backend I'm doing in Python to an API via URL. The method requests.get(URL) automatically makes the respective encoding to UTF-8. The problem is that the API page, when they are special characters, such as in Russian, German, Spanish, etc.... in the address goes the parameter (query, for example) and it is already sent encoded. For example, the Russian word "Бавария Мюнхен" in UTF-8 becomes: "%D0%91%D0%B0%D0%B2%D0%B0%D1%80%D0%B8%D1%8F%20%D0%9C%D1%8E%D0%BD%D1%85%D0%B5%D0%BD" but it turns out that the url when entering manually from the website, to each % adds a 25, that is, it remains as %25 plus the letter that follows in the query encoded. The website is RSS Dog. Questions: How do I manually add that "%25"? Is a coding method that does that in Python. Translated with www.DeepL.com/Translator :v
has comment: http://stackoverflow.com/comment/83187714
has comment: http://stackoverflow.com/comment/83188215
tagged with: encode
has title: How do I add characters to an encoded string? Python
tagged with: python
has answer: http://stackoverflow.com/a/48105824
tagged with: utf-8
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: encoding
accepted answer: http://stackoverflow.com/a/48105824
linked to: http://stackoverflow.com/q/16566069
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/83292593
type: AnswerComment
comment on: http://stackoverflow.com/a/48156696
type: Comment
has text: You're right about `zip_longest` but I think your `filter` does a little too much. That will drop 0 from the list, which is maybe safe here (all the sample data is positive integers) but I'd prefer not to get into the habit when working with numeric data. I like specifying the fill value as something that can never be the max, but `filter(lambda x: x is not None, i)` would be safer if you want to use the default behavior of filling with `None` and then filter that out.
score: 0

http://stackoverflow.com/comment/83263686
comment on: http://stackoverflow.com/q/48135506
score: 0
type: Comment
type: QuestionComment
has text: Ok, it seems like you are used to something different than Gtk. In Gtk, if you change windows, it will look exactly that. Now, like JoseFonte said in Gtk chat, you can switch widgets within a Gtk window. But a GtkApplication is not going to help you do that.

http://stackoverflow.com/comment/83087551
score: 0
comment on: http://stackoverflow.com/q/48057647
has text: it's an official workaround as the word `class` is reserved in Python.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83327153
comment on: http://stackoverflow.com/a/48163465
score: 1
type: AnswerComment
has text: in addition, in my settings.py i have already added 'anomaly' to my installed apps
type: Comment

http://stackoverflow.com/q/48084971
has answer: http://stackoverflow.com/a/48085151
type: AnsweredQuestion
score: 0
tagged with: excel
type: Question
has title: Search for specific string in multiple excel files
possible better answer: http://stackoverflow.com/a/48099707
accepted answer: http://stackoverflow.com/a/48085151
has answer: http://stackoverflow.com/a/48099707
answer count: 2
tagged with: pandas
has body: I'm new to python, so bear with me on this one. I want to make a script that searches within all excel files in a specific folder, to see if they contain an '@' sign. If it finds a match it should write to a log.txt files with the name of the excel file. I don't have the name of the excel files in advance. So far I'm stuck at just read in one file, and return true if it finds the string. What I got is import pandas as pd df = pd.read_excel(open('test.xlsx','rb'), sheetname=0) print(df) if '@' in df: print("true") else: print("false") This returns the content of sheet1 in the excel file correctly, but the search to find a match, doesn't seem to work. Any ideas? Maybe Im doing it all wrong.
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/a/48134756
has comment: http://stackoverflow.com/comment/83250069
score: 1
accepted answer of: http://stackoverflow.com/q/48134179
answers question: http://stackoverflow.com/q/48134179
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83247729
has comment: http://stackoverflow.com/comment/83247902
upvote count: 1
has body: As you are saying the model did well when there were less training iterations, I guess the pre-trained model could already detect the person object and your training set made the detection worse. The models seems to work great on pictures but not on videos If your single pictures are detected fine, then videos should work too. the only difference can be from video image resolution and quality. So, compare the image resolution and the video. Is that an overfitting? The images and the videos, you are talking about, If the images were used in training you should not use them to evaluate the model. If the model is over fitted it will detect the training images but not any other ones. As you are saying, the model detects too many detections, I think this is not because of overfitting, it can be about your dataset. I think You have too little amount of data to train. The network model is too big and complicated for the amount of data. Try smaller network like VGG, inception_v1(ssd mobile net) etc. The image resolution used in training set is very different from the evaluation images. Learning rate is important, but I think in your case it's fine. I think you can check carefully the dataset you used for training and use as many data as you can for the training. These are the things I generally experienced and wasted time.

http://stackoverflow.com/q/48158785
downvote count: 2
has comment: http://stackoverflow.com/comment/83297184
answer count: 1
has body: I have a stream of incoming RTP packet and I have two goals to accomplish which I am finding difficult in a high level language like Python. 1 ) Strip away the header from the rtp packet, i.e remove the redundant section of the rtp packet that isn't audio 2 ) Once I have the data, change it from big endian to little endian. Note : I have been told about struct.pack , but that deals with a section or one number. How do I change the entire data?
favorite count: 0
has comment: http://stackoverflow.com/comment/83297174
has title: Python - Packet handling and modification
tagged with: packet
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/83297269
accepted answer: http://stackoverflow.com/a/48178798
type: Question
has comment: http://stackoverflow.com/comment/83297393
has comment: http://stackoverflow.com/comment/83297431
score: -2
tagged with: rtp
tagged with: endianness
has answer: http://stackoverflow.com/a/48178798

http://stackoverflow.com/a/48024229
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48024167
has body: Indexing lists in Python works by [] not (). Try def printtack(self, index): self.stacks[index].printStack()
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83298204
comment on: http://stackoverflow.com/a/48159150
type: Comment
has text: at least I think that's the problem like I said I'm very new to this.when trying to run it tells me "TypeError: sequence item 0: expected str instance, int found"
score: 0
type: AnswerComment

http://stackoverflow.com/q/48150251
type: Question
has answer: http://stackoverflow.com/a/48150650
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/83278782
downvote count: 0
has title: Updating Redis hash safely
favorite count: 0
has comment: http://stackoverflow.com/comment/83278851
tagged with: redis
type: UnansweredQuestion
tagged with: python
score: 2
has body: I have a hash in redis. It has 20 key/value pairs. I want to update it hourly and remove old elements. What is the best way to remove HASH key's content and fill with with fresh values. Since HASH is part of an API, I don't want to cause any race condition when I am removing all elements from the HASH. I don't want to use EXPIRE because I want to have a control over schedule. I created following mock up. Assume that Faker() is my API that gets fresh values. I want to add new values to HASH and get rid of the old ones. import redis import json from faker import Faker try: r = redis.StrictRedis(host='localhost', port=6379, db=0) fake = Faker() for _ in range(20): userId = fake.uuid4() user = {"name":fake.name(),"address":fake.address(),"country":fake.country()} r.hset('users',userId,json.dumps(user)) except Exception as e: print ('Error',e)
has answer: http://stackoverflow.com/a/48154218

http://stackoverflow.com/a/48110529
type: Answer
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/48109264
downvote count: 0
has body: Here's my rough attempt... Hopefully this helps getting your brain flowing? import math def findpoints(lon, lat): radius = 1 N = 360 # generate points circlePoints = [] for k in range(N): angle = math.pi*2*k/N dx = radius*math.cos(angle) dy = radius*math.sin(angle) point = {} point['lat']= lat + (180/math.pi)*(dy/6371) #Earth Radius point['lon']= lon + (180/math.pi)*(dx/6371)/math.cos(lon*math.pi/180) #Earth Radius # add to list circlePoints.append(point) return circlePoints

http://stackoverflow.com/q/48072749
has comment: http://stackoverflow.com/comment/83119112
has answer: http://stackoverflow.com/a/48072960
has comment: http://stackoverflow.com/comment/83119917
linked to: http://stackoverflow.com/q/772922
has answer: http://stackoverflow.com/a/48072936
has comment: http://stackoverflow.com/comment/83120289
has body: I am using python and I am looking a way where I can arrange the words in a meaning full seance and can improve the readability. Sample words are H o w d o s m a l l h o l d e r f a r m e r s f i t i n t o t h e b i g p i c t u r e o f w o r l d f o o d p r o d u c t i o n Output How do small holder farmers fit into the big picture of world food production This one way to remover one time white spaces, where the line has two spaces it will keep the one. Can anyone suggest more ways . Edit See this text line Inn ovative b usines s m odels and financi ng m e chanisms for pv de ploym ent in em ergi ng regio ns This is my problem so I simply can't remove spaces. One Idea match every set of characters with dictionary and found the write words. May be
favorite count: 0
has comment: http://stackoverflow.com/comment/83119322
tagged with: python
has answer: http://stackoverflow.com/a/48073598
answer count: 4
has title: Remove spaces from words and generate exact words
has comment: http://stackoverflow.com/comment/83119213
upvote count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/83119202
type: Question
possible better answer: http://stackoverflow.com/a/48072859
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48072859
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83119143
accepted answer: http://stackoverflow.com/a/48073598
score: -1

http://stackoverflow.com/comment/83321425
comment on: http://stackoverflow.com/q/48170994
has text: add your code to the qusetion
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48017962
type: Question
score: 1
linked to: http://stackoverflow.com/q/2371436
possible better answer: http://stackoverflow.com/a/48018036
has comment: http://stackoverflow.com/comment/83005031
has comment: http://stackoverflow.com/comment/83005228
downvote count: 2
tagged with: sympy
has answer: http://stackoverflow.com/a/48026238
accepted answer: http://stackoverflow.com/a/48026238
has title: How to substitute values in mathematics equations in python?
has answer: http://stackoverflow.com/a/48018166
has body: I am getting data in form of dictionary from data base as: in_dict = {"x":2,"y":"x+2","z":"y+2"} and I am getting my maths equation in form of string as : eqn = "(x+2)*y/z" What is the easiest method to substitute values in equation and to give final solution? Note: One should be aware that values in dictionary come randomly.
upvote count: 3
has answer: http://stackoverflow.com/a/48018036
tagged with: python
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/83004988
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83012359
has answer: http://stackoverflow.com/a/48018086
tagged with: scipy

timing
tags question: http://stackoverflow.com/q/48075855
type: Tag
tag name: timing

http://stackoverflow.com/q/48134928
has title: Azure Batch Job Scheduling: Task doesn't run recurrently
has answer: http://stackoverflow.com/a/58085543
tagged with: python
tagged with: job-scheduling
type: UnansweredQuestion
tagged with: azure-batch
type: Question
score: 0
answer count: 2
has body: My objective is to schedule an Azure Batch Task to run every 5 minutes from the moment it has been added, and I use the Python SDK to create/manage my Azure resources. I tried creating a Job-Schedule and it automatically created a new Job under the specified Pool. job_spec = batch.models.JobSpecification( pool_info=batch.models.PoolInformation(pool_id=pool_id) ) schedule = batch.models.Schedule( start_window=datetime.timedelta(hours=1), recurrence_interval=datetime.timedelta(minutes=5) ) setup = batch.models.JobScheduleAddParameter( 'python_test_schedule', schedule, job_spec ) batch_client.job_schedule.add(setup) What I did is then add a task to this new Job. But the task seems to run only once as soon as it is added (like a normal task). Is there something more that I need to do to make the task run recurrently? There doesn't seem to be much documentation and examples of JobSchedule either. Thank you! Any help is appreciated.
has answer: http://stackoverflow.com/a/48176970
tagged with: azure

http://stackoverflow.com/q/48124409
tagged with: web-crawler
has title: Selenium click on a next-page link not loading the next page
score: 0
answer count: 2
favorite count: 0
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: xpath
has answer: http://stackoverflow.com/a/48125096
has answer: http://stackoverflow.com/a/48124455
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83225767
tagged with: selenium
upvote count: 1
downvote count: 1
has body: I'm new to selenium and webscraping and I'm trying to get information from the link: https://www.carmudi.com.ph/cars/civic/distance:50km/?sort=suggested Here's a snippet of the code I'm using: while max_pages &gt; 0: results.extend(extract_content(driver.page_source)) next_page = driver.find_element_by_xpath('//div[@class="next-page"]') driver.execute_script('arguments[0].click();', next_page) max_pages -= 1 When I try to print results, I always get (max_pages) of the same results from page 1. The "Next page" button is visible in the page and when I try to find elements of the same class, it only shows 1 element. When I try getting the element by the exact xpath and performing the click action on it, it doesn't work as well. I enclosed it in a try-except block but there were no errors. Why might this be?
type: Question
has comment: http://stackoverflow.com/comment/83226623

http://stackoverflow.com/comment/83297623
type: Comment
comment on: http://stackoverflow.com/a/48158940
score: 1
type: AnswerComment
has text: Still returning ``{"errno":"20'"}``. Do you think that the problem can be the device firmware?

http://stackoverflow.com/comment/83006176
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48018575
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ That's not in the stated "requirements". Also, it's commented with "to not *showing* duplicates" (emphasis my interpretation). And it's literally not their `result`.

http://stackoverflow.com/comment/83093785
type: Comment
score: 0
has text: I like the idea of that registration function.
type: AnswerComment
comment on: http://stackoverflow.com/a/48060413

http://stackoverflow.com/q/48144381
has body: I'm trying to convert my 32-bit floating point sampled WAVE file to 16-bit integer WAVE file. I want to generate 16-bit integer WAV file from ultrasonic sine wave which range from -1.414 to 1.414. In SciPy.io.wavfile, the output format is fixed according to type array which I generated. But I changed my 32-bit float format array to 16-bit by multiplying '32767' with casting to get integer format value, but the result frequency is not similar at all. Is there any way to change my from 32-bit floating point to 16-bit PCM using SciPy library?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83268511
has comment: http://stackoverflow.com/comment/83282529
tagged with: signals
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83268652
has title: Changing WAV format from 32-bit floating point to 16 bit PCM
has comment: http://stackoverflow.com/comment/83267708
favorite count: 0
has answer: http://stackoverflow.com/a/52757235
type: UnansweredQuestion
tagged with: python
tagged with: audio
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83267890
tagged with: scipy

http://stackoverflow.com/comment/83290740
comment on: http://stackoverflow.com/q/48155703
type: QuestionComment
type: Comment
score: 0
has text: Welcome to SO. Please take the time to read [ask] and the other links on that page. Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem.

http://stackoverflow.com/comment/83086524
type: AnswerComment
has text: Are you sure? Your error message says otherwise. If you want to install a package, either move and install it to a subdirectory (so it ends up getting installed as `/usr/local/lib/python3.5/dist-packages/myproject/config.py`), or, if it should be a top-level module, rename it to a unique name (`jaysconfig.py`).
type: Comment
comment on: http://stackoverflow.com/a/48057039
score: 0

http://stackoverflow.com/q/48103432
tagged with: python
has comment: http://stackoverflow.com/comment/83182747
tagged with: dlib
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83183576
has comment: http://stackoverflow.com/comment/83184099
has comment: http://stackoverflow.com/comment/83185702
has answer: http://stackoverflow.com/a/48104416
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/83183929
tagged with: image
has title: Unsupported image type error in dlib detector
score: 0
accepted answer: http://stackoverflow.com/a/48104416
answer count: 1
has body: I have images in my folder 'img/datasets/neutral', some images are gray and some are BGR, so when i tried to detect facial landmark using dlib i got error. Error detections = detector(image, 1) RuntimeError: Unsupported image type, must be 8bit gray or RGB image. I think this error is due some images are grayscale and others are BGR.I tried to use try and except but it does not work. How can i remove this error? python script emotions = ['neutral', 'sad', 'happy', 'anger'] data={} detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') clf = SVC(kernel='linear', probability=True, tol=1e-3) def get_files(emotion): files = glob.glob('img\\datasets\\%s\\*' %emotion) random.shuffle(files) training = files[:int(len(files)*0.8)] prediction = files[-int(len(files)*0.2)] return training, prediction def get_landmarks(image): detections = detector(image, 1) for k, d in enumerate(detections): # For all detected face instances individually shape = predictor(image, d) # Draw Facial Landmarks with the predictor class xlist = [] ylist = [] for i in range(1, 68): # Store X and Y coordinates in two lists xlist.append(float(shape.part(i).x)) ylist.append(float(shape.part(i).y)) xmean = np.mean(xlist) ymean = np.mean(ylist) xcentral = [(x - xmean) for x in xlist] ycentral = [(y - ymean) for y in ylist] landmarks_vectorised = [] for x, y, w, z in zip(xcentral, ycentral, xlist, ylist): landmarks_vectorised.append(w) landmarks_vectorised.append(z) meannp = np.asarray((ymean, xmean)) coornp = np.asarray((z, w)) dist = np.linalg.norm(coornp - meannp) landmarks_vectorised.append(dist) landmarks_vectorised.append((math.atan2(y, x) * 360) / (2 * math.pi)) data['landmarks_vectorised'] = landmarks_vectorised if len(detections) &lt; 1: data['landmarks_vestorised'] = "error" def make_sets(): training_data = [] training_labels = [] prediction_data = [] prediction_labels = [] for emotion in emotions: print("Working on %s emotion" %emotio…
has comment: http://stackoverflow.com/comment/83184384

http://stackoverflow.com/comment/83009868
score: 0
type: AnswerComment
has text: yes i tried this as well, but still returns an empty dataframe with col headings... i wonder if it has something to do with the data type?
type: Comment
comment on: http://stackoverflow.com/a/48020382

http://stackoverflow.com/a/48129456
upvote count: 36
score: 36
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48129222
type: Answer
has body: I tend to use the following template def plot_something(data, ax=None, **kwargs): ax = ax or plt.gca() # Do some cool data transformations... return ax.boxplot(data, **kwargs) Then you can experiment with your plotting function by simply calling plot_something(my_data) and you can specify which axes to use like so. fig, (ax1, ax2) = plt.subplots(2) plot_something(data1, ax1, color='blue') plot_something(data2, ax2, color='red') plt.show() # This should NOT be called inside plot_something() Adding the kwargs allows you to pass in arbitrary parameters to the plotting function such as labels, line styles, or colours. The line ax = ax or plt.gca() uses the axes you have specified or gets the current axes from matplotlib (which may be new axes if you haven't created any yet).
accepted answer of: http://stackoverflow.com/q/48129222

http://stackoverflow.com/a/48088539
has comment: http://stackoverflow.com/comment/83152461
has comment: http://stackoverflow.com/comment/83152574
type: Answer
answers question: http://stackoverflow.com/q/48087569
has comment: http://stackoverflow.com/comment/83152888
accepted answer of: http://stackoverflow.com/q/48087569
has body: The method is based on the comments by @noslenkwah and @skrubber. If you need most common row for each name as described df = pd.DataFrame({'Name': ['John', 'John', 'John', 'John', 'John', 'Sam', 'Sam', 'Sam', 'Sam'] , 'A': [1, 1, 1, 2, 2, 3, 3, 3, 3] , 'B': [1, 1, 2, 2, 2, 3, 4, 3, 3] , 'C': [2, 1, 1, 1, 1, 3, 3, 3, 3]}) df_count = df.groupby(["A", "B", "C"])['Name'].value_counts().reset_index(name="Count") l = list() for name in set(df_count.Name): freq = df_count[df_count.Name == name].Count.max() l.append(df_count[(df_count.Name == name) &amp; (df_count.Count == freq)].values.tolist()[0]) print(l) [[3, 3, 3, 'Sam', 3], [2, 2, 1, 'John', 2]] First the method group df by ["A", "B", "C"]. Then loop over names, and first calculate the most common rows' frequency within this name. Then filter out groups that have different frequncy and with different names in the query df_count[(df_count.Name == name) &amp; (df_count.Count == freq)]. A more general problem: finding rows with highest frequency regardless names, you can try df_count = df.groupby(["A", "B", "C"])['Name'].value_counts().reset_index(name="Count") max_freq = df_count["Count"].max() df_count[df_count["Count"] == max_freq] A B C Name Count 3 2 2 1 John 2 4 3 3 3 Sam 2 Reference Pandas: Selecting rows based on value counts of a particular column Selecting with complex criteria from pandas.DataFrame
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83152537

http://stackoverflow.com/q/48057299
has comment: http://stackoverflow.com/comment/83157078
has comment: http://stackoverflow.com/comment/83192786
type: Question
has comment: http://stackoverflow.com/comment/83136847
has comment: http://stackoverflow.com/comment/83156396
has comment: http://stackoverflow.com/comment/83087105
has comment: http://stackoverflow.com/comment/83086872
has comment: http://stackoverflow.com/comment/83156458
score: 0
has comment: http://stackoverflow.com/comment/83173508
accepted answer: http://stackoverflow.com/a/48057421
has body: Please bear with my as I am new to python and am learning by creating simple programs. Recently I started making my own program that generates a file and allows the user to choose things and store them in each file. In this example I was going for a song playlist generator. Although it was difficult I soldiered through until I came across this error that I couldn't fix. It was with the opening of a file. This is the Code cont = "0" log = 0 data = open("songs.txt", "r") songs = data.readlines() songs.sort() while log &lt; 20: cont = input("Do you want to make a playlist? [Yes or No]") while cont == "yes": print ("1. ", songs[0],"2. ", songs[1],"3. ", songs[2],"4. ", songs[3],"5. ", songs[4],"6. ", songs[5],"7. ", songs[6],"8. ", songs[7],"9. ", songs[8],"10. ", songs[9],"11. ", songs[10],"12. ", songs[11],"13. ", songs[12],"14. ", songs[13],"15. ", songs[14],"16. ", songs[15],"17. ", songs[16],"18. ", songs[17],"19. ", songs[18],"20. ", songs[19]) new = "playlist" + str(log) + ".txt" print(new) log = log + 1 cont = "no" choice = int(input("Please enter the first choice of song you would like in your playlist [Type the allocated number please]")) choice1 = choice - 1 "playlist" + str(log) + ".txt".append(songs[choice1]) However, my code is supposed to allow the user to choose songs from my print function and then add them to the playlist generatored and then repeat this for as many playlists they want. Now my code is giving me an error message. File "playlists.py", line 18, in &lt;module&gt; "playlist" + str(log) + ".txt".append(songs[choice1]) AttributeError: 'str' object has no attribute 'append' What is this Error stating and also how can I overcome it. Thanks in advance and anticipation!
answer count: 1
has title: Appending to a file error - PYTHON
has comment: http://stackoverflow.com/comment/83156413
has comment: http://stackoverflow.com/comment/83119901
tagged with: python
tagged with: append
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83119912
has answer: http://stackoverflow.com/a/48057421
tagged with: file

http://stackoverflow.com/comment/83346586
comment on: http://stackoverflow.com/q/48173238
score: 0
has text: @anderson may be due to a selected keyboard... i could choose GO Lite Keyboard and not default appium keyboard..But how do you do ?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48029901
score: 0
has comment: http://stackoverflow.com/comment/83030720
answer count: 0
tagged with: nasm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83030026
tagged with: python
has body: I am using ctypes to load a 64-bit DLL written in NASM. The command is: ThisDLL = ctypes.WinDLL(r"C:/Temp2/Test_Project_2/Std_Math_Formulas.dll") The error message is: OSError: [WinError 998] Invalid access to memory location In order to reduce the possibilities, I changed the code to an extremely simple, barebones DLL: ; Header Section [BITS 64] export SimpleTest section .data var1: dq 24 var2: dq 254 answer: dq 0 section .text SimpleTest: mov rax,[var1] mov rbx,[var2] add rax,rbx mov [answer],rax ret * * * * * Yet I still get "Invalid access to memory location." I have researched this for hours, and this message comes up in many different situations, but I haven't found any satisfactory answers. Any ideas would be most appreciated.
type: Question
tagged with: ctypes
has title: Python ctypes OSError: [WinError 998] Invalid access to memory location

http://stackoverflow.com/q/48051564
type: Question
score: 0
has body: This is my Ruby code. I want to convert this function to a Python 3 equivalent. files = { 'Input.txt' =&gt; 'Randy', 'Code.py' =&gt; 'Stan', 'Output.txt' =&gt; 'Randy' } def group_by_owners(files) files.each_with_object({}) { |(key, value), new_hash| (new_hash[value] ||= []) &lt;&lt; key } end puts group_by_owners(files) The Ruby result looks like this: {"Randy" =&gt; ["Input.txt", "Output.txt"], "Stan" =&gt; ["Code.py"]} Python would be: {"Randy": ["Input.txt", "Output.txt"], "Stan": ["Code.py"]} Here is what I have tried: def group_by_owners(files): new_dict = dict(zip(files.values(), (files.keys()))) print(new_dict) Then I was trying to append the keys to an array. def group_by_owners(files): keys_array = [] new_dict = dict(zip(files.values(), keys_array.append((files.keys())))) but I don't think that will work inside of a zip method.
has answer: http://stackoverflow.com/a/48051621
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/48051599
tagged with: python
tagged with: dictionary
tagged with: ruby
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83074892
downvote count: 2
linked to: http://stackoverflow.com/q/39980323
has answer: http://stackoverflow.com/a/48051934
has title: Reordering an "dict" Object and shoveling multiple keys into an array of values (swap key-values in dictionary) | Ruby to Python
has comment: http://stackoverflow.com/comment/83077088
has comment: http://stackoverflow.com/comment/83074876

http://stackoverflow.com/q/48015632
type: UnansweredQuestion
tagged with: python
tagged with: django
type: Question
tagged with: object
has title: Change Date Time Format in Django REST Object
score: 0
tagged with: sql
answer count: 1
has body: I've been trying to tackle this problem for quite a while now. please help if possible... I have a REST framework response where one of the datetime values is in UTC format. I want to change this format into a more friendly format. rest framework output: { "data": [ { "id": "1", "start_time": "2017-12-28T12:56:55-08:00", }, { "id": "2", "start_time": "2017-12-28T12:14:10-08:00", }, { "id": "3", "start_time": "2017-12-28T09:37:35-08:00", }, ] } views: (my code to change the start_time format in the display) serializer = ChangeLogSerializer(changelog['items'], many=True) for log in serializer.data: serializer.data[log]['start_time'] = log['start_time'].strftime('%Y-%m-%d %T') serializers.py class ChangeLogSerializer(serializers.ModelSerializer): """Serializer to map the Model instance into JSON format.""" class Meta: """Meta class to map serializer's fields with the model fields.""" start_time = serializers.DateField(format="%y-%m-%d %H:%M:%S") model = ChangeLog fields = ('id', 'sku', 'serial_num', 'mac', 'sw_ver', 'state', 'outcome', 'logfile', 'process', 'cm', 'site', 'port_num', 'term_srvr', 'start_time', 'end_time') read_only_fields = ('start_time', 'end_time') Observations: serializer.data[log] doesn't appear to be correct way to update this item gives error message: File "/root/venv/dashbaord/lib/python3.4/site-packages/rest_framework/utils/encoders.py", line 68, in default return super(JSONEncoder, self).default(obj) Tried in my serializers.py file to adjust the format: start_time = serializers.DateField(format="%y-%m-%d %H:%M:%S"), but it doesn't do anything
has answer: http://stackoverflow.com/a/48016016
tagged with: rest

http://stackoverflow.com/a/48086079
score: 2
has body: Here is a very simple not complicated at all way to accomplish this. time = "20170103154828" first = time[:4] + '-' + time[4:] second = first[:7] + '-' + first[7:] third = second[:10] + ' ' + second[10:] hour = third[:13] + ':' + third[13:] final = hour[:16] + ':' + hour[16:] print(final) Yields: 2017-01-03 15:48:28
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48085844
type: Answer

http://stackoverflow.com/comment/83292958
type: QuestionComment
comment on: http://stackoverflow.com/q/48143565
score: 1
has text: Note that (waiting after each send for a confirmation to be received from the remote peer) will drastically lower your throughput, since then your throughput will be strictly limited by the aggregate round-trip time of the network(s) between your program and the other program. If your goal is to maximize network throughput, you'll want to 'pipeline' the transfer of data as much as possible.
type: Comment

http://stackoverflow.com/comment/83320003
comment on: http://stackoverflow.com/q/48161117
score: 0
type: QuestionComment
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162820/discussion-between-davis-herring-and-jaysunn).

http://stackoverflow.com/q/48171679
has body: I am trying to login into the server via post with my python script, but it is not working although when i am doing the same POST via postman it is working fine. I believe my python script is not saving the authentication cookie information or may be i have to add some more fields in my payload. I am at very very beginner level of programming so please guide me how i can save that authentication cookie which i can further use in my next GET, POST requests. When i run this POST request via postman. I simply give username and password in the body and i got the following successful response { "ErrorCode": 0, "Data": { "role": "admin", "_id": "7c9e7mdf4d249212282480zb", "name": "test5" } } but when I run below mentioned Python script, I am getting &lt;!DOCTYPE HTML PUBLIC"-//IETF//DTD HTML 2.0//EN"&gt; 500 Internal Server error Please find below mentioned my python script import requests url = "http://172.125.169.21/api/user/login" payload = "{\"name\": \"test5\", \"password\": \"Hello123\"}" response = requests.request("POST", url, data=payload) print(response.text) print(response.headers)
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83323248
has comment: http://stackoverflow.com/comment/83323384
has answer: http://stackoverflow.com/a/48171911
has comment: http://stackoverflow.com/comment/83325273
has comment: http://stackoverflow.com/comment/83322880
tagged with: python
accepted answer: http://stackoverflow.com/a/48171911
type: AnsweredQuestion
has title: how to save authentication cookie while doing POST login into the server
type: Question

http://stackoverflow.com/comment/83248615
comment on: http://stackoverflow.com/a/48135609
type: AnswerComment
type: Comment
score: 0
has text: "Hack to learn, not learn to hack". this is basically a school project to learn more about sockets. nothing is going to be stolen.

http://stackoverflow.com/q/48062788
has comment: http://stackoverflow.com/comment/83098905
has comment: http://stackoverflow.com/comment/83098834
accepted answer: http://stackoverflow.com/a/48062975
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83099285
has title: Pandas - calculate row value based on previous calculated row value
has comment: http://stackoverflow.com/comment/83099099
score: 0
has comment: http://stackoverflow.com/comment/83103380
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83098560
has body: What is the most effective way to solve following problem with pandas?: Let's asume we have following df: v1 v2 index 0 1 2 1 5 6 2 7 3 3 9 4 4 5 1 Now we want to calculate a third value (v3) based on following function: if df.v1.shift(1) &gt; df.v3.shift(1): df.v3 = max(df.v2, df.v3.shift(1)) else: df.v3 = df.v2 The desired output should look like: v1 v2 v3 index 0 1 2 2 1 5 6 6 2 7 3 3 3 9 4 4 4 5 1 4 THX &amp; BR from Vienna
has answer: http://stackoverflow.com/a/48062975
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83124628
has comment: http://stackoverflow.com/comment/83098521
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83098343

http://stackoverflow.com/comment/83109622
type: AnswerComment
has text: actually i am trying to replicate deep net using LSTM that was previously training using Resnet... In which they took max size (18000) and masked short values with zeros that were less than 18000. I am still confused will that approach work in LSTM but i should try first. In this case i guess my input will become LSTM(128, 18000,1) for 128 being batch size and each timestep containing 18000 samples right?
comment on: http://stackoverflow.com/a/48065234
type: Comment
score: 0

http://stackoverflow.com/comment/83094508
comment on: http://stackoverflow.com/q/48061022
score: 0
has text: It's a [timestamp](https://docs.python.org/3.6/library/datetime.html#datetime.date.fromtimestamp)... `datetime.fromtimestamp(1508486400)` -> `datetime.datetime(2017, 10, 20, 9, 0)`
type: QuestionComment
type: Comment

http://stackoverflow.com/a/50246619
score: 2
answers question: http://stackoverflow.com/q/48037799
downvote count: 0
upvote count: 2
type: Answer
has body: There's apparently functionality that's been merged that will improve the situation here, see How do you add more x axis ticks and labels to datetime axis using Python&#39;s Bokeh? and https://github.com/bokeh/bokeh/issues/1668

http://stackoverflow.com/a/48085274
has comment: http://stackoverflow.com/comment/83145757
answers question: http://stackoverflow.com/q/48085236
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: import os os.system("shutdown.exe /h") Taken from Suspend / Hibernate pc with python (If someone can mark this question as a duplicate, that would be appreciated)
has comment: http://stackoverflow.com/comment/83145724

http://stackoverflow.com/comment/83104769
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48065637
type: Comment
has text: Question: you currently attempt to update the lists *in place*, so other references to the list will see the changes. How important is this? Is it okay to create a *new* list of lists of sets instead?

http://stackoverflow.com/a/48052529
score: 0
type: Answer
has body: After import turtle, you want to enter a variable name which is to call the turtle via that variable. Syntax: import turtle your_variable_name = turtle.Turtle() After that, you want to accessed into the turtle. your_variable_name.pencolor('blue')
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83081148
answers question: http://stackoverflow.com/q/48052478

http://stackoverflow.com/comment/83026748
has text: That's fair enough :) I just feel like every time I learn a combination of methods that might do what I want, I then stumble over a single method that does it all. I'll play catch-up, thanks for teaching me a new one :)
type: Comment
comment on: http://stackoverflow.com/a/48028128
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83248166
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48135506
score: 0
has text: I have multiple windows which reside in multiple glade files which are expected to be loaded as needed.

http://stackoverflow.com/q/48134408
has comment: http://stackoverflow.com/comment/83246121
downvote count: 1
type: Question
has body: I am trying to take data from a csv file do a calculation and add it back to the original file but I have no idea why my python code will not print me out my 'whip' calculation. Here's what I'm working with: import csv print('enter Start year ') startYear = input('start year: ') print('enter End year ') endYear = input('end year: ') with open('Pitching.csv', 'rb') as csv_file: csv_reader = csv.DictReader(csv_file) with open('new_stats.csv', 'w') as new_file: #headers = csv_reader.next() #headers.append("Whip") fieldnames = ['playerID', 'yearID', 'stint', 'teamID', 'lgID', 'W', 'L', 'G', 'GS', 'CG', 'SHO', 'SV', 'IPouts', 'H', 'ER', 'HR', 'BB', 'SO', 'BAOpp', 'ERA', 'IBB', 'WP', 'HBP', 'BK', 'BFP', 'GF', 'R', 'SH', 'SF', 'GIDP'] csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames) csv_writer.writeheader() for line in csv_reader: currentYear = line['yearID'] if int(currentYear) &gt;= int(startYear) and int(currentYear) &lt;= int(endYear): walks = line['BB'] hits = line['H'] inningsPitched = line['Ipouts'] innings = inningsPitched/3.0 add = walks + hits whip = add / innings whip2 = whip line.append(whip2) csv_writer.writerow(line) #csv_writer.write(line['Whip'])
upvote count: 0
has title: Python csv writer won't add my column
score: -1
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83246151
has answer: http://stackoverflow.com/a/48135521

http://stackoverflow.com/comment/83206638
score: 1
comment on: http://stackoverflow.com/q/48049478
type: QuestionComment
type: Comment
has text: have you thought to simply ask the makers of odoo?

inheritance
tags question: http://stackoverflow.com/q/48159459
tags question: http://stackoverflow.com/q/48025628
tags question: http://stackoverflow.com/q/48124894
tags question: http://stackoverflow.com/q/48044888
tag name: inheritance
tags question: http://stackoverflow.com/q/48122016
tags question: http://stackoverflow.com/q/48150871
tags question: http://stackoverflow.com/q/48129863
tags question: http://stackoverflow.com/q/48053797
tags question: http://stackoverflow.com/q/48015368
tags question: http://stackoverflow.com/q/48039361
type: Tag
tags question: http://stackoverflow.com/q/48021343
tags question: http://stackoverflow.com/q/48082893
tags question: http://stackoverflow.com/q/48160482
tags question: http://stackoverflow.com/q/48093653
tags question: http://stackoverflow.com/q/48144150
tags question: http://stackoverflow.com/q/48025515

http://stackoverflow.com/comment/83131026
comment on: http://stackoverflow.com/q/48078566
score: 0
type: Comment
type: QuestionComment
has text: What part of the message are you having problems understanding? An integer was expected, but it got a float. You're passing a float (a number with a decimal point and numbers to the right of it) where it's expecting you to pass an integer. Depending on how you declared `food`, those values may be floats. `curses.ACS_PI` definitely is a float. Fix the code by not passing a float where an integer is expected. You have the type definitions and code right in front of you.

http://stackoverflow.com/comment/83115548
has text: my preference is to solve it by proxying all traffic using flask - that makes most sense. Nginx basic auth means the user has to auth twice - flask login and then nginx auth, i want to avoid this. I sort of get how your catch all snippet works (very clever), however, when I set kibana_server_baseurl = staticIP:5601, flask still does not catch it. Flask catches any staticIP/path but not staticIP:5601. It still opens up Kibana. The @app.route begins with "/path", not sure how to set it up with ":5601/. Is this the issue? Thoughts?
comment on: http://stackoverflow.com/a/48039246
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48119806
has comment: http://stackoverflow.com/comment/83216805
type: Question
tagged with: ipython
has comment: http://stackoverflow.com/comment/83216157
has comment: http://stackoverflow.com/comment/83217066
score: 2
has comment: http://stackoverflow.com/comment/83216260
answer count: 1
downvote count: 0
has title: Pausing an IPython script with a shell command?
favorite count: 0
has body: I have a cpu intensive script I'm running in ipython that will take several days to finish. As I'm using my computer over these days, I would ideally like to be able to pause this script using some ipython shortcut (something along the lines of ctrl+c or ctrl+z) to temporarily reclaim full computing power. Is there any way this might be done? I'm running IPython directly in the terminal in Ubuntu 16.04. Thanks!
tagged with: python
tagged with: shell
tagged with: unix
has answer: http://stackoverflow.com/a/48120162
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/48105448
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I made simple HTTP Server using BaseHTTPRequestHandler. The problem is, that when I want to post some data using requests from client, I get ConnectionError. I did simple request from requests lib documentation. Also interesting thing is, that HTTP Server will receive data from client and print it to console. I don't understand how its possible. Client: def post_data(): """Client method""" json_data = { 'sender': 'User', 'receiver': 'MY_SERVER', 'message': 'Hello server! Sending some data.'} data_headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} data_payload = json.dumps(json_data) try: post = requests.post('http://localhost:8080/post', data=data_payload, headers=data_headers) print(post.status_code) except ConnectionError as e: print("CONNECTION ERROR: ") print(e) HTTP Server: def do_POST(self): """Server method""" self.send_response(200) print("Receiving new data ...") content_length = int(self.headers['Content-Length']) post_data = self.rfile.read(content_length) print(post_data) Server result: C:\Users\mypc\Projects\PythonFiles\httpserver&gt;python server.py Fri Jan 5 01:09:12 2018: HTTP Server started on port 8080. 127.0.0.1 - - [05/Jan/2018 01:09:21] "POST /post HTTP/1.1" 200 - Receiving new data ... b'{"sender": "User", "receiver": "MY_SERVER", "message": "Hello server! Sending some data."}' Client result: C:\Users\mypc\Projects\PythonFiles\httpserver&gt;python client.py CONNECTION ERROR: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) C:\Users\mypc\Projects\PythonFiles\httpserver&gt; Error without exception block: Traceback (most recent call last): File "C:\Python36\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen chunked=chunked) File "C:\Python36\lib\site-packages\urllib3\connectionpool.py", line 387, in _make_request six.raise_from(e, None) File "&lt;string&gt;", line 2, in raise_from File "C:\Python36\lib\site-packages\urllib3\connectionpool.py", line 383, in _make_reque…
possible better answer: http://stackoverflow.com/a/69027586
tagged with: error-handling
has answer: http://stackoverflow.com/a/69027586
accepted answer: http://stackoverflow.com/a/48105794
tagged with: httpserver
tagged with: python-requests
type: Question
linked to: http://stackoverflow.com/q/31371166
score: 49
has answer: http://stackoverflow.com/a/48105794
linked to: http://stackoverflow.com/q/66778586
has comment: http://stackoverflow.com/comment/83187142
answer count: 2
upvote count: 49
has title: Python HTTP Server/Client: Remote end closed connection without response error

http://stackoverflow.com/a/48875545
downvote count: 0
has body: I think I see why it is going forever. While attempting to import pyautogui raised an ImportError for me, I did import the threading module. Here's the docstring from threading.timer: Call a function after a specified number of seconds: t = Timer(30.0, f, args=None, kwargs=None) t.start() t.cancel() # stop the timer's action if it's still waiting so the problem is (probably) that a single call to your autoclick function causes it to loop infinitely a THAT point, not in the while loop. So, I'd recommend replacing your autoclick function with this: def click(): pyautogui.click(1230, 618) def autoclick(): threading.Timer(0.1, click).start() or this: def autoclick(): threading.Timer(0.1, pyautogui.click, args=(1230, 618)) Aside: Where did you get the pyautogui module? Nevermind; also, pip is a much more powerful tool than I realized.
answers question: http://stackoverflow.com/q/48084397
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/48049291
score: 0
answers question: http://stackoverflow.com/q/48049133
type: Answer
has body: When you use a for loop in python, it creates an iterator on the object on which you are looping. In this case the object is Sentence The below code demonstrates what happens if the list is modified Sentence = ['abc', 'bcd', 'cde', 'dea', 'eab', 'abc'] sentence_iterator = iter(Sentence) print(sentence_iterator.__next__()) # This will print 'abc' Sentence.remove('abc') # This will modify the list to ['bcd', 'cde', 'dea', 'eab', 'abc'] # This below code will print 'cde' not 'bcd' as the list is modified. # and the sentence_iterator has already seen the first element print(sentence_iterator.__next__())

http://stackoverflow.com/q/48093358
has answer: http://stackoverflow.com/a/48093667
upvote count: 1
has answer: http://stackoverflow.com/a/48093473
type: Question
tagged with: opencv
score: 1
possible better answer: http://stackoverflow.com/a/48093473
tagged with: image-processing
tagged with: face-recognition
answer count: 3
accepted answer: http://stackoverflow.com/a/48093667
downvote count: 0
has body: Hi,Everyone We are working on a face recognition application when ı run the code below, as you can see in the photo it works only in one face(red square) it doesnt scan other faces in the traning-data ı guess my predict function only run one time. dont in the loop. Processed Image : LINK # coding: utf-8 import cv2 import os import numpy as np suclular = ["Bilinmeyen", "Veli Eroglu", "Ali Eroglu"] def detect_face(img): # ALGORİMA için Gri Yapıyoruz. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # yüz tanımlama için geereken haarcascade face_cascade = cv2.CascadeClassifier( 'opencv-files/lbpcascade_frontalface.xml') faces = face_cascade.detectMultiScale( gray, scaleFactor=1.2, minNeighbors=5) # YÜZ TANIMLAMA for (x, y, w, h) in faces: img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) if (len(faces) == 0): return None, None # Yuz bulunamazsa... (x, y, w, h) = faces[0] return gray[y:y + w, x:x + h], faces[0] face_recognizer = cv2.face.LBPHFaceRecognizer_create() face_recognizer.train(faces, np.array(labels)) def draw_rectangle(img, rect): (x, y, w, h) = rect cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2) def draw_text(img, text, x, y): cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 0, 255), 2) def predict(test_img): img = test_img.copy() face, rect = detect_face(img) label, confidence = face_recognizer.predict(face) print(confidence) label_text = suclular[label] if confidence &gt; 42 and confidence &lt; 70: label_text = "Tespit Edilemedi." print(label_text) elif confidence &gt; 70: label_text = "Bilinmiyor" draw_rectangle(img, rect) draw_text(img, label_text, rect[0], rect[1] - 5) return img print("Predicting images...") test_img1 = cv2.imread("test-data/test8jpg.jpg") predicted_img1 = predict(test_img1) print("Prediction complete") cv2.imshow("SONUC", cv2.resize(predicted_img1, (400, 500))) cv2.waitKey(0) cv2.destroyAllWindows() cv2.waitKey(1) cv2.destroyAllWindows()
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/15529365
has title: OpenCV Python face recognition only one face recognition
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77253808

http://stackoverflow.com/comment/83232410
has text: Yes I understand that. Because the current structure of scikit will have base classes in some other submodules, which can be seen in the imports on the top of MLPClassifier file](https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/neural_network/multilayer_perceptron.py). You need all of them in addition to numpy and scipy libraries.
score: 1
comment on: http://stackoverflow.com/q/48114750
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83267541
type: QuestionComment
score: 1
has text: Maybe try `results_row.extend(x)` instead of `results_row.append(x)`. It's hard to tell what this code is doing.
comment on: http://stackoverflow.com/q/48144690
type: Comment

http://stackoverflow.com/a/48051482
accepted answer of: http://stackoverflow.com/q/48051390
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83075810
has body: You're basically multiplying two matrices (arrays). In order to multiply two matrices A and B, A must be of dimension m x n and B must be of dimension n x k, the result C will be of dimension m x k (m rows and k columns). The result C of A x B in your case is : C(1, 1) = 14 = 2 * 1 + 4 * 3 C(1, 2) = 48 = 2 * 6 + 4 * 9 C(1, 3) = 22 = 2 * 7 + 4 * 2 C(2, 1) = 24 = 3 * 1 + 7 * 3 C(2, 2) = 81 = 3 * 6 + 7 * 9 C(2, 3) = 35 = 3 * 7 + 7 * 2 C(3, 1) = 8 = 5 * 1 + 1 * 3 C(3, 2) = 39 = 5 * 6 + 1 * 9 C(3, 3) = 37 = 5 * 7 + 1 * 2 where the matrix C looks like: |C(1, 1) C(1, 2) C(1, 3)| C = |C(2, 1) C(2, 2) C(2, 3)| |C(3, 1) C(3, 2) C(3, 3)| Most people get confused about the difference between the dot product and the element-wise multiplication. Explanation of element-wise multiplication Suppose we have to matrices of the same shape (i.e. both of dimension m*k) A and B resulting in a matrix D, then: D(1, 1) = A(1, 1) * B(1, 1) D(1, 2) = A(1, 2) * B(1, 2) D(1, 3) = A(1, 3) * B(1, 3) D(2, 1) = A(2, 1) * B(2, 1) and so on.
has comment: http://stackoverflow.com/comment/83075270
has comment: http://stackoverflow.com/comment/83074943
has comment: http://stackoverflow.com/comment/83077883
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48051390

http://stackoverflow.com/comment/83293868
type: QuestionComment
has text: Ya actually regarding dead thread I would have rather ask how to re-start the dead thread,since thread.start() raises exception :)
comment on: http://stackoverflow.com/q/48157208
score: 0
type: Comment

http://stackoverflow.com/comment/83312749
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48166760
has text: Yes the second solutions works ! Thank you very much !:)
score: 0

http://stackoverflow.com/a/48130431
has body: Another list comprehension solution: n = 'what is the boarding time in bangalore station' print(' '.join(word[::-1] if ind % 2 == 1 else word.upper() for ind, word in enumerate(n.split()))) Output: 'WHAT si THE gnidraob TIME ni BANGALORE noitats' Another solution: upper_words = [item.upper() for item in n.split()[0::2]] reverse_words = [item[::-1] for item in n.split()[1::2]] print(' '.join(word[0] + ' ' + word[1] for word in zip(upper_words, reverse_words))) Output: 'WHAT si THE gnidraob TIME ni BANGALORE noitats'
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48130286
has comment: http://stackoverflow.com/comment/83238009
type: Answer

http://stackoverflow.com/q/48036452
linked to: http://stackoverflow.com/q/46525786
type: Question
has comment: http://stackoverflow.com/comment/83043803
duplicate of: http://stackoverflow.com/q/46525786
has comment: http://stackoverflow.com/comment/83073163
tagged with: dataframe
score: 6
tagged with: pandas
has title: Merge two dataframes with interval data in one of them
has answer: http://stackoverflow.com/a/48036743
answer count: 1
downvote count: 0
favorite count: 0
has body: As input I have two dataframes: data1 = [{'code':100}, {'code':120}, {'code':110}] data1 = pd.DataFrame(data1) code 0 100 1 120 2 110 data2 = [{'category':1, 'l_bound':99, 'r_bound':105},{'category':2, 'l_bound':107, 'r_bound':110},{'category':3, 'l_bound':117, 'r_bound':135}] data2 = pd.DataFrame(data2) category l_bound r_bound 0 1 99 105 1 2 107 110 2 3 117 135 I want to get in the end the following dataframe, with additional column in the first dataframe as a category number if the code lies in the corresponding interval: code category 0 100 1 1 120 3 2 110 2 Intervals are random and the original dataframes are pretty big. Looping with itertuples is too slow. Any pythonic solutions?
has comment: http://stackoverflow.com/comment/83043191
tagged with: python
upvote count: 6
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48036743

http://stackoverflow.com/q/48027558
tagged with: selenium
upvote count: 7
possible better answer: http://stackoverflow.com/a/64689293
type: Question
has answer: http://stackoverflow.com/a/64689293
score: 5
accepted answer: http://stackoverflow.com/a/48027604
tagged with: javascript
has title: Selenium: How to scroll in inner div using selenium in python
favorite count: 0
answer count: 5
downvote count: 2
has answer: http://stackoverflow.com/a/48027604
tagged with: python
has body: Want to scroll the chats in web.whatsapp.com. Have shared the pseudo-code below: recentList = driver.find_elements_by_xpath("//div[@class='_2wP_Y']") driver.execute_script("window.scrollTo(0, 500);") Looking forward for a solution so as to scoll in web.whatsapp.com till the last chat. Thanks in advance!
has answer: http://stackoverflow.com/a/68029689
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/68461131
has answer: http://stackoverflow.com/a/76745877

http://stackoverflow.com/a/48028060
score: 1
answers question: http://stackoverflow.com/q/48025095
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48025095
type: Answer
has body: You may use re.compile(r'\[[^]\\]*(?:\\.[^]\\]*)*]', re.DOTALL) See the regex demo. Details \[ - a [ char [^]\\]* - 0 or more chars other than ] and \ (?: - start of a non-capturing group matching a sequence of: \\. - a \ char followed with any char [^]\\]* - 0 or more chars other than ] and \ )* - zero or more repetitions of the patterns inside the non-capturing group ] - a ] char. The regex follows the unroll-the-loop principle. Depending on the input it may work much, even 10+ times faster than the non-unrolled version, r'\[(?:\\.|[^]\\])*]', that is based on an infinitely quantified alternation group, causing lots of redundant backtracking steps. Note that the regex above can fail when the initial [ is preceded with a backslash. In those cases, you will need r'(?&lt;!\\)(?:\\{2})*(\[[^]\\]*(?:\\.[^]\\]*)*])' See this regex demo The main difference here is (?&lt;!\\)(?:\\{2})*, a (?&lt;!\\) negative lookbehind that fails the match if the current position is preceded with a \ char, and (?:\\{2})* that matches 0+ repetitions of two literal backslashes. The rest of the pattern is enclosed with capturing parentheses, and when a match is found, you just need to access match.group(1) to get the right value.
upvote count: 1

http://stackoverflow.com/q/48114531
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/4440010
tagged with: many-to-many
has title: unique_together with a field from a foreign key in a through table for a ManyToMany relation
type: Question
score: 0
answer count: 1
tagged with: python-3.x
has body: I am developing a Django 2.0 project app. It has a (non-working) models.py file, which looks something like this: from django.db import models from django.utils import timezone class Computer(models.Model): name = models.CharField(max_length=25) def __str__(self): return "Computer {}".format(self.name) class Software(models.Model): name = models.CharField(max_length=25) description = models.CharField(max_length=1024, blank=True) def __str__(self): return self.name class SoftwareVersion(models.Model): software = models.ForeignKey(Software, on_delete=models.CASCADE, related_name="versions") version = models.CharField(max_length=100) released_at = models.DateTimeField(default=timezone.now) def __str__(self): return "{} {}".format(self.software, self.version) class ComputerSoftwareBundle(models.Model): computer = models.ForeignKey(Computer, on_delete=models.CASCADE, related_name="bundles") installed_at = models.DateTimeField(default=timezone.now) versions = models.ManyToManyField(SoftwareVersion, through="BundleSoftwareVersion", related_name="bundles") class BundleSoftwareVersion(models.Model): bundle = models.ForeignKey(ComputerSoftwareBundle, on_delete=models.CASCADE) version = models.ForeignKey(SoftwareVersion, on_delete=models.CASCADE) class Meta: unique_together = (("bundle", "version__software"),) The app tracks software bundles currently or previously installed on computers. The thing here is that a bundle should not contain more than one version of the same software. Also, SoftwareVersion should contain a reference to Software, because the same version string has a different meaning for different pieces of software. The code does not work as described in this Stackoverflow answer. I left the unique_together line in to illustrate what I am trying to achieve. I've tried to work around this limitation of Django (not being able to use fields referred to via a foreign key in unique_together) by overriding the save and validate_unique methods in BundleSoftwareVersion …
tagged with: django-orm
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48225475

http://stackoverflow.com/comment/83352857
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48157284
type: Comment
has text: *** Error: Terminating simulation in C:\Users\Toshiba\AppData\Local\Temp\tmp-simulator-Toshiba-jc8_w4r0\Buildings. *** Error: Killing simulation in C:\Users\Toshiba\AppData\Local\Temp\tmp-simulator-Toshiba-jc8_w4r0\Buildings. *** Error: Killed process as it computed longer than 240 seconds. *** Error: Simulation failed in 'C:\Users\Toshiba\AppData\Local\Temp\tmp-simulator-Toshiba-jc8_w4r0\Buildings' Exception: File C:\Users\Toshiba\AppData\Local\Temp\tmp-simulator-Toshiba-jc8_w4r0\Buildings\simulator.log does not exist. You need to delete the directory manually.

http://stackoverflow.com/comment/83143952
type: Comment
comment on: http://stackoverflow.com/q/48084325
has text: Put it in a function.
type: QuestionComment
score: 8

http://stackoverflow.com/a/48146359
has comment: http://stackoverflow.com/comment/83271075
answers question: http://stackoverflow.com/q/48145027
has body: Point 1 There are several ways to preserve the string-ness of the '[UPC]' column. Use dtype as mentioned in other posts Use converters Perform the conversion afterwards with pd.Series.str.zfill Setup Let's begin by setting up some files. I'm using Jupyter Notebook and I can use the handy %%writefile magic. %%writefile nielson_sku_fact01.csv [All Markets],[All Periods],[UPC],A,B 1,2,0001,3,4 1,3,2000,7,8 %%writefile nielson_sku_fact02.csv [All Markets],[All Periods],[UPC],C,D 1,4,0001,3,4 1,3,3000,7,8 %%writefile nielson_sku_fact03.csv [All Markets],[All Periods],[UPC],B,D 1,4,0002,10,11 1,2,2000,8,8 Let's use OP's code to get some vars import glob import os import pandas as pd from functools import reduce files = glob.glob('nielson_sku_fact*.csv') sch_inx = [ '[All Markets]', '[All Periods]', '[UPC]' ] Now let's show how the three conversions work: pd.read_csv('nielson_sku_fact01.csv', dtype={'[UPC]': str}) [All Markets] [All Periods] [UPC] A B 0 1 2 0001 3 4 1 1 3 2000 7 8 pd.read_csv('nielson_sku_fact01.csv', converters={'[UPC]': str}) [All Markets] [All Periods] [UPC] A B 0 1 2 0001 3 4 1 1 3 2000 7 8 Using pd.Series.str.zfill pd.read_csv('nielson_sku_fact01.csv')['[UPC]'].astype(str).pipe( lambda s: s.str.zfill(s.str.len().max())) [All Markets] [All Periods] [UPC] A B 0 1 2 0001 3 4 1 1 3 2000 7 8 Point 2 If you want elegance, There is no need to use a lambda that takes two arguments when pd.DataFrame.combine_first is already a function that takes two arguments. In addition, you can use map with a prepared reading function to make it nice and clean: def read(filename): return pd.read_csv( filename, converters={'[UPC]': str} ).set_index(sch_inx) reduce(pd.DataFrame.combine_first, map(read, files)) A B C D [All Markets] [All Periods] [UPC] 1 2 0001 3.0 4.0 NaN NaN 2000 NaN 8.0 NaN 8.0 3 2000 7.0 8.0 NaN NaN 3000 NaN NaN 7.0 8.0 4 0001 NaN NaN 3.0 4.0 0002 NaN 10.0 NaN 11.0 Point 3 I think you should reconsider using pd.DataFrame.combine_first because the nature of…
has comment: http://stackoverflow.com/comment/83271159
type: Answer
has comment: http://stackoverflow.com/comment/83271172
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/83232291
comment on: http://stackoverflow.com/q/48127849
has text: No, it is not clear. You just have a standard class definition and two instances here.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48134979
tagged with: python
has answer: http://stackoverflow.com/a/48159704
score: -1
has comment: http://stackoverflow.com/comment/83247312
downvote count: 1
has answer: http://stackoverflow.com/a/48136549
type: Question
has comment: http://stackoverflow.com/comment/83248566
upvote count: 0
has title: Halite Al python. my bot can't run
answer count: 3
has comment: http://stackoverflow.com/comment/83247999
has comment: http://stackoverflow.com/comment/83248735
favorite count: 0
has body: this is my code for the bot. i want the bot to dock on the nearest planet not on the center planet of the map.so i find the distances in arr_distances() and it return dict that its keys is a planet.id and its values are the distances and then i ordered it based on values """ Welcome to your first Halite-II bot! This bot's name is Settler. It's purpose is simple (don't expect it to win complex games :) ): 1. Initialize game 2. If a ship is not docked and there are unowned planets 2.a. Try to Dock in the planet if close enough 2.b If not, go towards the planet Note: Please do not place print statements here as they are used to communicate with the Halite engine. If you need to log anything use the logging module. """ # Let's start by importing the Halite Starter Kit so we can interface with the Halite engine import hlt # Then let's import the logging module so we can print out information import logging from collections import OrderedDict import math # GAME START # Here we define the bot's name as Settler and initialize the game, including communication with the Halite engine. game = hlt.Game("Settler") # Then we print our start message to the logs logging.info("Starting my Settler bot!") def arr_distances(ship, game_map): p_distances = {} for planet in game_map.all_planets(): distance = math.sqrt((float(planet.x) - float(ship.x)) ** 2.0 + (float(planet.y) - float(ship.y)) ** 2.0) p_distances[planet.id] = distance p_distances = OrderedDict(sorted(p_distances.items(), key = lambda t: t[1])) return p_distances while True: # TURN START # Update the map for the new turn and get the latest version game_map = game.update_map() # Here we define the set of commands to be sent to the Halite engine at the end of the turn command_queue = [] # For every ship that I control for ship in game_map.get_me().all_ships(): distances = arr_distances(ship, game_map) # If the ship is docked if ship.docking_status != ship.DockingStatus.UNDOCKED: # Skip this ship continue # For each planet in…
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48143311

http://stackoverflow.com/comment/83269568
type: QuestionComment
has text: your task is to get the exact strings and regexes that are not matching as you expect (at least all the time) and show them to us
comment on: http://stackoverflow.com/q/48142203
score: 0
type: Comment

http://stackoverflow.com/a/48031611
has comment: http://stackoverflow.com/comment/83043586
downvote count: 0
has body: The first merge statement you perform should get you halfway there, but unfortunately, it's the second half of a two-step process. It sounds like you want to merge the sales data onto the visits data after summing the visits by Date/upc. You actually have to do a sum first (the merge command does not do this by itself). Try: df2_sum = df2.groupby(["Date", "upc"])["visits"].sum().reset_index() Then left-merge this onto the sales data: df3 = pd.merge(df1, df2_sum, on=["Date", "upc"], how="left")
has comment: http://stackoverflow.com/comment/83039985
has comment: http://stackoverflow.com/comment/83043466
type: Answer
answers question: http://stackoverflow.com/q/48031445
score: 4
has comment: http://stackoverflow.com/comment/83040719
upvote count: 4

http://stackoverflow.com/a/48122003
upvote count: 2
has comment: http://stackoverflow.com/comment/116527452
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48117693
answers question: http://stackoverflow.com/q/48117693
type: Answer
has comment: http://stackoverflow.com/comment/83221785
score: 2
has body: This is because of... Keep-Alive Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection! Note that connections are only released back to the pool for reuse once all body data has been read; be sure to either set stream to False or read the content property of the Response object. When you use a session, it sends a Connection: keep-alive header and will hang onto the connection which causes it to use the previously established circuit in Tor. As mentioned in the docs, you can set stream=False to get around it: http.get("https://httpbin.org/ip", timeout=(5, 5), proxies=proxies, stream=False)

http://stackoverflow.com/comment/83717460
type: Comment
comment on: http://stackoverflow.com/a/48135838
type: AnswerComment
has text: @jmh please could you file an issue for this on the python extension repo. If like to get to the bottom of this and help you get this working. https://github.com/Microsoft/vscode-python/issues/new
score: 0

mechanicalsoup
tag name: mechanicalsoup
type: Tag
tags question: http://stackoverflow.com/q/48032426
tags question: http://stackoverflow.com/q/48155877

http://stackoverflow.com/q/48059289
answer count: 2
upvote count: 0
favorite count: 0
tagged with: elasticsearch
has answer: http://stackoverflow.com/a/48060212
tagged with: python
type: AnsweredQuestion
tagged with: elasticsearch-dsl-py
possible better answer: http://stackoverflow.com/a/48059481
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48059481
accepted answer: http://stackoverflow.com/a/48060212
has body: When using elasticsearch-dsl python api ,is there any way to pass a variable as key in filter . Please have a look in the code below. from elasticsearch import Elasticsearch from elasticsearch_dsl import Search es_client = Elasticsearch(['http://10.220.3.40'], port='9200') param1 = 'xyz' s = Search(using=es_client, index="index1", doc_type="sampledoc").filter("term", Key=param1) print("Query 1 :"+str(s.to_dict())) key_varialble_name = 'Key2' s = Search(using=es_client, index="index1", doc_type="sampledoc").filter("term", key_varialble_name=param1) print("Query 2 :"+str(s.to_dict())) Here ,the variable named 'key_varialble_name' has a value assigned as 'Key2'. But when used inside the filter,that value is not getting replaced and as a result the term key is containing the variable name (i.e. 'key_varialble_name' ) instead of the variable value (i.e. 'Key2' ). I do not have much knowledge on python. Can anybody let me know if there is anyway to pass the variable value as key here ?
score: -1
tagged with: elasticsearch-dsl
has comment: http://stackoverflow.com/comment/83091064
has title: Using variable for filter term key in elasticsearch-dsl-py

http://stackoverflow.com/comment/83284321
has text: I was answering your question "why the multi-process API I used included in the `multiprocessing` library". E.g. I was explaining a use case for spawning a single child process. "All spawned processes do `crawling`". That's true but as I said, in your case you spawn 1 child process, that crawls all the sites sequentially while the parent process waits for it to finish. That's why it's the same speed as the single process version - you essentially haven't parallelised anything.
comment on: http://stackoverflow.com/q/48150315
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48127811
upvote count: 2
tagged with: machine-learning
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/48127962
answer count: 1
downvote count: 0
has title: How to get the class probabilities during the evaluation of CIFAR-10 in TensorFlow?
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48127962
has body: I try to modify the code from the Convolutional Neural Network TensorFlow Tutorial to get the single probabilities for each class from each test-images. What alternative to tf.nn.in_top_k can I use? Because this method returns only one boolean tensor. But I want to preserve the individual values. I use Tensorflow 1.4 and Python 3.5, I think lines 62-82 and 121-129 / 142 are probably the lines to be modified. Somebody have a hint for me? Lines 62-82: def eval_once(saver, summary_writer, top_k_op, summary_op): """Run Eval once. Args: saver: Saver. summary_writer: Summary writer. top_k_op: Top K op. summary_op: Summary op. """ with tf.Session() as sess: ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: # Restores from checkpoint saver.restore(sess, ckpt.model_checkpoint_path) # Assuming model_checkpoint_path looks something like: # /my-favorite-path/cifar10_train/model.ckpt-0, # extract global_step from it. global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1] else: print('No checkpoint file found') return Lines 121-129 + 142 [....] images, labels = cifar10.inputs(eval_data=eval_data) # Build a Graph that computes the logits predictions from the # inference model. logits = cifar10.inference(images) # Calculate predictions. top_k_op = tf.nn.in_top_k(logits, labels, 1) [....]
tagged with: python
type: AnsweredQuestion
score: 2
tagged with: conv-neural-network

http://stackoverflow.com/a/48053531
has comment: http://stackoverflow.com/comment/83080290
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48053512
answers question: http://stackoverflow.com/q/48053512
type: Answer
has comment: http://stackoverflow.com/comment/83080112
score: 4
has body: Try MonthDict[month_int] - to access a dict's values you need to use square brackets, not round ones.
has comment: http://stackoverflow.com/comment/83079956

http://stackoverflow.com/comment/83120495
has text: i can't find where pip is installing your packages, can you show me where is it in your computer
comment on: http://stackoverflow.com/a/48072680
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/83236755
comment on: http://stackoverflow.com/q/48122238
type: Comment
has text: Although I suggested a change to argtypes, your original code still worked for me.The `/entry` was the problem that prevented things working for me.
score: 0
type: QuestionComment

http://stackoverflow.com/q/48151172
has title: Getting the distance and the direction of the nearest detected obstacle
tagged with: pepper
has body: Is there a way to get the distance and the direction of the nearest detected obstacle? I have tried with this "Navigation/AvoidanceNavigator/ObstacleDetected" event, but it never triggers event if I position the robot next to the wall and tell him to go 5 meters long in the wall direction.
upvote count: 3
answer count: 2
tagged with: nao-robot
favorite count: 0
tagged with: python
downvote count: 0
possible better answer: http://stackoverflow.com/a/48182819
has answer: http://stackoverflow.com/a/48182819
tagged with: choregraphe
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48154876
score: 3
accepted answer: http://stackoverflow.com/a/48154876

http://stackoverflow.com/comment/83253047
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48137664
has text: @AnttiHaapala I was just quickly prototyping, and will definitely clean up this mess. I think it is not related to the problem, right?
score: 0

http://stackoverflow.com/a/48026188
has comment: http://stackoverflow.com/comment/138469402
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/83022073
has comment: http://stackoverflow.com/comment/83022089
score: 6
has body: The recommended way to use subprocess in Python 3.5+ is with the run function. proc = s.run(['python',filename], stdout=s.PIPE, stderr=s.PIPE, check=False) stdout_v, stderr_v, = proc.stdout, proc.stderr return_code = proc.return_code Set check=True to throw an error if the return code is non-zero (which is an indication of some error happening). In older versions of Python, I usually preferred to use the check_output or call functions. Check_output will throw an error if it detects a non-zero exit code, whereas the call function will continue normally.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48025875
has comment: http://stackoverflow.com/comment/83022039
accepted answer of: http://stackoverflow.com/q/48025875

http://stackoverflow.com/comment/83153679
type: AnswerComment
type: Comment
has text: Thanks for the help Hue
comment on: http://stackoverflow.com/a/48089028
score: 0

http://stackoverflow.com/q/48099928
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
has body: I'm trying to add an ImageField to a django model but I'm getting an error telling ImageField does not exist: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 78, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 200, in build_graph self.load_disk() File "/home/trie/Desktop/django/venv/lib/python3.5/site-packages/django/db/migrations/loader.py", line 109, in load_disk migration_module = import_module("%s.%s" % (module_name, migration_name)) File "/home/trie/Desktop/django/venv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlo…
has answer: http://stackoverflow.com/a/64088178
has comment: http://stackoverflow.com/comment/83174963
type: Question
has comment: http://stackoverflow.com/comment/83175306
has title: module 'models' has no attribute 'ImageField'
has answer: http://stackoverflow.com/a/48100283
answer count: 3
possible better answer: http://stackoverflow.com/a/53466175
has answer: http://stackoverflow.com/a/53466175
accepted answer: http://stackoverflow.com/a/48100283
has comment: http://stackoverflow.com/comment/83174991
tagged with: model

http://stackoverflow.com/comment/115394367
type: AnswerComment
comment on: http://stackoverflow.com/a/56135413
score: 0
type: Comment
has text: @HockeyStick it should, but I remember it being significantly slower in my tests.

http://stackoverflow.com/comment/83207903
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48115869
has text: You should be able to pipe the standard output of your program (i.e. the result of `print` statements) to the input of the server program writing something like `python myProgram.py | serverProgram` in your terminal. However that requires that `myProgram.py` generates _all_ the input that the server program needs.

http://stackoverflow.com/comment/83263537
comment on: http://stackoverflow.com/q/48142682
score: 0
type: Comment
has text: Hello Aiven. Thanks for your reply. But in this case, how can you identify the mime-type if the content is embedded?
type: QuestionComment

http://stackoverflow.com/q/48070823
upvote count: 1
has comment: http://stackoverflow.com/comment/83115374
tagged with: if-statement
has title: Not able to use a list in a if-statement
has comment: http://stackoverflow.com/comment/83116876
type: Question
has comment: http://stackoverflow.com/comment/83115377
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48070895
tagged with: python
has body: I'm trying to make a loop that allowed me to retrieve tokenized data values in a list, check if there's stop words inside the tokenized cell value and append it to a new list. # Importing the packages to be used import xlrd from nltk.tokenize import word_tokenize from nltk.corpus import stopwords # Declaration of file path of the data and opening of workbook and worksheet file_path = "C:/Users/L31101/Documents/Data/Copy_1.xlsx" workbook = xlrd.open_workbook(file_path) worksheet = workbook.sheet_by_name("ConsolidateModuleQnComment") # Grabs the numbers of rows and columns of the worksheet rowcount = worksheet.nrows columncount = worksheet.ncols # Prints the number of row and columns print("\nRow count: %d" % rowcount) print("Column count: %d" % columncount) # Grabbing the cell values and placing them inside an array named data_value data_value = [] for rowindex in range(2, rowcount): # print("\nCurrent row number: %d" % rowindex) # print(worksheet.cell_value(rowindex, 6)) data_value.append(worksheet.cell_value(rowindex, 6)) # Grabbing the values inside data_value cell and tokenizes them, and then adds them into the data_tokenized array data_tokenized = [] for valueindex in range(0, len(data_value)): data_tokenized.append(word_tokenize(data_value[valueindex])) # Grabbing the tokenized values from the data_tokenized array and removing the stopwords stop_words = set(stopwords.words("english")) data_stopword_removed = [] for tokenizedindex in range(0, len(data_tokenized)): if data_tokenized[tokenizedindex] not in stop_words: data_stopword_removed.append(data_tokenized[tokenizedindex]) print("\nNumber of records: %d" % len(data_stopword_removed)) It gives the following error message C:\Users\L31101\PycharmProjects\Year3\venv\Scripts\python.exe C:/Users/L31101/PycharmProjects/Year3/SentimentAnalysis.py Row count: 5792 Column count: 7 Traceback (most recent call last): File "C:/Users/L31101/PycharmProjects/Year3/SentimentAnalysis.py", line 47, in &lt;module&gt; if test_vari…
tagged with: list
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/83115350

http://stackoverflow.com/a/48131908
has body: with open('dictionaryFile.txt','r') as filein: dict_from_file = eval(filein.read())
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48131837
type: Answer

pca
tag name: pca
tags question: http://stackoverflow.com/q/48019843
type: Tag
tags question: http://stackoverflow.com/q/48138557

http://stackoverflow.com/a/48026936
has comment: http://stackoverflow.com/comment/83175098
has comment: http://stackoverflow.com/comment/83023642
has comment: http://stackoverflow.com/comment/83023871
has comment: http://stackoverflow.com/comment/83023792
has comment: http://stackoverflow.com/comment/83169766
type: Answer
has body: In this case i think we have to apply the principle Simple is better than complex, why don't just do: def foo(lst, r = 0): print r, len(lst) As it is been said, there is no way of doing what you want in Python, that is all...
answers question: http://stackoverflow.com/q/48026545
score: 0

http://stackoverflow.com/comment/83107271
type: AnswerComment
score: 0
has text: This option appears simple. But I'm worried about efficiency. Interestingly, for OP's sample data, this is the slowest. May change for different sized inputs though.
type: Comment
comment on: http://stackoverflow.com/a/48066980

http://stackoverflow.com/q/48054761
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50026086
has body: As per the Django documentation, its possible to use multiple conditions with the When clause. When( registered_on__gt=date(2014, 1, 1), registered_on__lt=date(2015, 1, 1), then='account_type' ) However, I am unable to use the same when using the Case clause. Case( When( registered_on__gt=date(2014, 1, 1), registered_on__lt=date(2015, 1, 1), then='account_type' ), default='default' ) I end up getting the following error: TypeError: __init__() got multiple values for keyword argument 'then' Is there some way I can achieve this? Am I missing something here?
type: Question
has answer: http://stackoverflow.com/a/48054994
upvote count: 15
answer count: 2
downvote count: 0
score: 15
possible better answer: http://stackoverflow.com/a/48054994
favorite count: 0
has title: Using multiple conditions in Django's Case When expressions
tagged with: python
has answer: http://stackoverflow.com/a/50026086
tagged with: django-orm
tagged with: django

http://stackoverflow.com/a/63224269
has body: As of Aug, 2020 SqlAlchemy supports IBM_db and I am able to successfully connect and retrieve data on Z/OS from sqlalchemy import Column, Integer, String, MetaData from sqlalchemy import create_engine engine = create_engine("db2+ibm_db://userId:password@host:port/db") #create a database engine from sqlalchemy.ext.declarative import declarative_base metadata = MetaData(schema='schemaName') Base = declarative_base(bind=engine, metadata=metadata) class Customers(Base): __tablename__ = 'tableName' CLIENT_ID = Column(Integer, primary_key=True) CLIENT_NAME = Column(Integer) CREATED_BY = Column(String) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session() result = session.query(Customers).limit(2) for row in result: print (row.CLIENT_NAME )
type: Answer
answers question: http://stackoverflow.com/q/48158410
score: 0

http://stackoverflow.com/comment/119111452
type: QuestionComment
has text: Does this answer your question? [Iterating through list of list in Python](https://stackoverflow.com/questions/6340351/iterating-through-list-of-list-in-python)
comment on: http://stackoverflow.com/q/48058197
score: 0
type: Comment

http://stackoverflow.com/a/48119644
has comment: http://stackoverflow.com/comment/83284521
answers question: http://stackoverflow.com/q/48110334
has comment: http://stackoverflow.com/comment/83288909
has comment: http://stackoverflow.com/comment/83280027
score: 0
has body: You can eventually create your classes dynamically with type() There is many ways to do it, but you can do something as follows: class SomeParentClass: pass NewClass = type('NewClass', (SomeParentClass,), {'new_method': lambda self: 'foo' } ) new_class_instance = NewClass() print(new_class_instance.new_method()) So you can create models dynamically, with a different name, inherit from a different class, new methods... You can then use globals()[variable_name_to_store_class] to assign newly created classes to a dynamic variable name. Hope its relavant for your problem.
type: Answer

http://stackoverflow.com/comment/83099275
type: QuestionComment
type: Comment
has text: Your theory seems to be correct. Seems that python interpreter normalises your unicode variable already when assigning it. If you put `print(dir(a))` after `a` has been assigned, you can see there is no trace of U+1D70F character in the class. Your second print statement would then work for the same reason (gets normalised), while your dictionary access fails as dictionaries can take anything as keywords and there would be no reason to normalise or do anything else to them as it is a string in parentheses.
comment on: http://stackoverflow.com/q/48063082
score: 1

http://stackoverflow.com/comment/83959040
score: 0
has text: can you try removing shell=True?
type: QuestionComment
comment on: http://stackoverflow.com/q/48028520
type: Comment

http://stackoverflow.com/comment/83070358
type: AnswerComment
type: Comment
has text: thank you, tried it, nothing happened elem = driver.find_elements_by_tag_name('a') for e in elem: element = e.getAttribute("src"); if(element.contains("/pics/button_downsize_27x27px.gif")): print element e.click() break
comment on: http://stackoverflow.com/a/48048924
score: 0

http://stackoverflow.com/q/48110779
has comment: http://stackoverflow.com/comment/83198311
has comment: http://stackoverflow.com/comment/83205413
has comment: http://stackoverflow.com/comment/83198372
has comment: http://stackoverflow.com/comment/83199198
score: 0
tagged with: python
favorite count: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83197104
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83197569
has body: How to parse a big file (50-100GB) into my database using SQLAlchemy? Let's say I have two tables. import collections import re import Bio.SeqIO import sqlalchemy from sqlalchemy import ForeignKey, UniqueConstraint from sqlalchemy import Column, Float, Integer, String, Text, DateTime from sqlalchemy.sql import func from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.sql.expression import ClauseElement Base = declarative_base() class Protein_sequence(Base): __tablename__ = 'protein_sequence' prot_seq_id = Column(Integer, primary_key=True) prot_seq = Column(Text, unique=True) protein_annotation = relationship('Protein', back_populates='protein_sequence') class Protein(Base): __tablename__ = 'protein_annotation' prot_id = Column(Integer, primary_key=True) prot_seq_id = Column(Integer, ForeignKey('protein_sequence.prot_seq_id')) prot_acc = Column(Text, unique=True) prot_name = Column(Text) protein_sequence = relationship('Protein_sequence', back_populates='protein_annotation') def parse_fasta(path, prot_db='unknown', taxon_name=None, taxon_id=None): """Parsing a fasta file (UniProt or NCBInr).""" prot = collections.OrderedDict() for record in Bio.SeqIO.parse(path, 'fasta'): prot['seq'] = str(record.seq) desc = record.description gi_num = re.findall('^gi\|([0-9]+)(?:\||\s|$)', desc) if gi_num: prot['prot_gi'] = gi_num[0] desc = re.sub('^gi\|([0-9]+)(?:\||\s|$)', '', desc) prot_db = re.findall('^([^|]+)\|', desc) if prot_db: prot_db = prot_db[0] prot['prot_db'] = prot_db prot_acc = re.findall('^[^|]+\|([^ ]+)', desc)[0] prot['prot_acc'] = prot_acc prot['prot_name'] = re.findall('^[^ ]+ (.+)', desc)[0] yield prot def prot_db_from_fasta(): """Create tables in SQLite database. Input fasta file.""" db = 'sqlite:///proteomic.db' engine = sqlalchemy.create_engine(db) Base.metadata.create_all(engine) Session = sqlalchemy.orm.sessionmaker(bind=engine) session = Session() conn = engine.connect() p = 'prot.fasta' for prot …
tagged with: sqlalchemy
has title: SQLAlchemy parse a large file
has comment: http://stackoverflow.com/comment/83205539
has comment: http://stackoverflow.com/comment/83197824
has comment: http://stackoverflow.com/comment/83198117

http://stackoverflow.com/comment/83064393
score: 0
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/help/mcve
comment on: http://stackoverflow.com/q/48046252

http://stackoverflow.com/a/48071938
type: Answer
has comment: http://stackoverflow.com/comment/83117560
score: 0
has comment: http://stackoverflow.com/comment/83117606
answers question: http://stackoverflow.com/q/48071858
has body: def oddTuples(aTup): rTup = () for i,t in enumerate(aTup): if i%2==0: rTup += (t,) return rTup

http://stackoverflow.com/q/48026589
type: Question
score: 0
tagged with: mongodb
answer count: 1
has answer: http://stackoverflow.com/a/48032312
type: UnansweredQuestion
tagged with: gridfs
tagged with: python
has body: For writing large files in gridFS using put(), is it necessary to use context manager with ? Looking at the documentation for put() here, calling put() is equivalent to doing, try: f = new_file(**kwargs) f.write(data) finally: f.close() Does that mean open and close for file is done automatically and hence do not require without explicit need to?
has title: GridFS: For writing files using 'put', is explicit 'with' block necessary?
tagged with: pymongo

http://stackoverflow.com/comment/83276951
has text: @JackNicholson Yes if it matched with both file
comment on: http://stackoverflow.com/q/48149249
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83190121
has text: My guess is you want `any` at some point if you want an if statement
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48107235

http://stackoverflow.com/q/48095351
type: Question
tagged with: python
score: 0
has title: rq queue always empty
tagged with: django
answer count: 1
has body: I'm using django-rq in my project. What I want to achieve: I have a first view that loads a template where an image is acquired from webcam and saved on my pc. Then, the view calls a second view, where an asynchronous task to process the image is enqueued using rq. Finally, after a 20-second delay, a third view is called. In this latter view I'd like to retrieve the result of the asynchronous task. The problem: the job object is correctly created, but the queue is always empty, so I cannot use queue.fetch_job(job_id). Reading here I managed to find the job in the FinishedJobRegistry, but I cannot access it, since the registry is not iterable. from django_rq import job import django_rq from rq import Queue from redis import Redis from rq.registry import FinishedJobRegistry redis_conn = Redis() q = Queue('default',connection=redis_conn) last_job_id = '' def wait(request): #second view, starts the job template = loader.get_template('pepper/wait.html') job = q.enqueue(processImage) print(q.is_empty()) # this is always True! last_job_id = job.id # this is the expected job id return HttpResponse(template.render({},request)) def ceremony(request): #third view, retrieves the result template = loader.get_template('pepper/ceremony.html') print(q.is_empty()) # True registry = FinishedJobRegistry('default', connection=redis_conn) finished_job_ids = registry.get_job_ids() #here I have the correct id (last_job_id) return HttpResponse(template.render({},request)) The question: how can I retrieve the result of the asynchronous job from the finished job registry? Or, better, how can I correctly enqueue the job?
type: UnansweredQuestion
tagged with: django-rq
tagged with: python-rq
has answer: http://stackoverflow.com/a/48099011

http://stackoverflow.com/a/48147473
has comment: http://stackoverflow.com/comment/83412078
has comment: http://stackoverflow.com/comment/83646092
has comment: http://stackoverflow.com/comment/83291364
upvote count: 1
answers question: http://stackoverflow.com/q/48141626
has body: I'm not sure why this has been downvoted, seems a reasonable question. However, matplotlib is not intended to be a solution for fast plotting (see this answer) and has limited support for 3D, so certainly consider another library for this. That said, if you are only using 6 balls then I think you can make this work. I'd suggest cleaning up your code using functions for repeated code, for example defining, def draw_ball(x, y, z, label="", color=(0,0,1,1)): u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) xP1 = x+ 0.4 * np.outer(np.cos(u), np.sin(v)) yP1 = y+ 0.4 * np.outer(np.sin(u), np.sin(v)) zP1 = z+ 0.4 * np.outer(np.ones(np.size(u)), np.cos(v)) # Plot the surface b = ax1.plot_surface(xP1, yP1, zP1, color= color) #mark it t = ax1.text(x, y, z, '%s' % label, size=20, color='k') return b, t would allow you to set everything up with just, players = [] for i in range(6): players.append(draw_ball(1+i*1.5, 1, 4, label=str(i+1))) That said, you'll find that drawing spheres with plot surface/text is too slow, instead I'd recommend using a scatter plot, with some transparency, and changing the data each time as follows, #Instead, get all positions and plot as a single scatter collection pos = [] for i in range(6): pos.append([1+i*1.5, 1, 4]) #Define numpy array which is faster to work with pos = np.array(pos) s = ax1.scatter(pos[:,0], pos[:,1], pos[:,2], s=100, alpha = 0.5) where pos is a 6 by 3 array for all players ball locations. This can then be updated as follows, from this answer, when pos changes, s._offsets3d = juggle_axes(pos[:,0], pos[:,1], pos[:,2], 'z') It should be more efficient to update the whole collection (6 players by 3) all in one go. Adding annotation can be done following the excellent example by @Luchko. To give you an idea how this all works together, try running the following code, from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import matplotlib.axes as axs import numpy as np import math from mpl_toolkits.…
has comment: http://stackoverflow.com/comment/83602696
has comment: http://stackoverflow.com/comment/83411833
has comment: http://stackoverflow.com/comment/83412004
has comment: http://stackoverflow.com/comment/83291155
has comment: http://stackoverflow.com/comment/83622320
has comment: http://stackoverflow.com/comment/83441486
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/83031808
score: 0
type: QuestionComment
type: Comment
has text: if server has problems and gives error then you can't load this page fast. Do you have problem to load Google too ? Then you have totally different problem and it has nothing to do with your current question.
comment on: http://stackoverflow.com/q/48030675

http://stackoverflow.com/q/48022187
answer count: 2
has answer: http://stackoverflow.com/a/66792459
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/48022399
favorite count: 0
upvote count: 8
has body: SVM: http://scikit-learn.org/stable/modules/svm.html#classification SGD: http://scikit-learn.org/stable/modules/sgd.html#classification seem to do pretty much the same to my eyes,as they write "an SGD implements a linear model". Can someone explain the differences between them?
accepted answer: http://stackoverflow.com/a/48022399
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: 7
has title: scikit-learn: what is the difference between SVC and SGD?
tagged with: svm
possible better answer: http://stackoverflow.com/a/66792459
type: Question

http://stackoverflow.com/comment/83266575
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48141022
has text: Thanks; this rhymes well with Charles' comments to another answer on this page, though it must be regarded as undocumented behavior which could well change in a future version.

http://stackoverflow.com/q/48087004
tagged with: pip
has comment: http://stackoverflow.com/comment/83158110
upvote count: 17
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50071486
has title: Installing Pip on Msys
has comment: http://stackoverflow.com/comment/83150671
type: Question
possible better answer: http://stackoverflow.com/a/58593545
downvote count: 0
tagged with: msys
has answer: http://stackoverflow.com/a/58593545
has body: I have built a simple PyGTK app using Python 3.5.2 and Msys but I need some modules not in the default installation, and although I could use setup.py install to get them I would much rather use pip. I looked around and found this but it relates to Python 2 and gave an error when attempting to follow the instructions given: $ python3 getpip.py Collecting pip Downloading pip-9.0.1-py2.py3-none-any.whl (1.3MB) Collecting setuptools Using cached setuptools-38.2.5-py2.py3-none-any.whl Collecting wheel Using cached wheel-0.30.0-py2.py3-none-any.whl Installing collected packages: pip, setuptools, wheel Exception: Traceback (most recent call last): File "C:\Users\Simon\AppData\Local\Temp\tmpoumuod3r\pip.zip\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Users\Simon\AppData\Local\Temp\tmpoumuod3r\pip.zip\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "C:\Users\Simon\AppData\Local\Temp\tmpoumuod3r\pip.zip\pip\req\req_set.py", line 784, in install **kwargs File "C:\Users\Simon\AppData\Local\Temp\tmpoumuod3r\pip.zip\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "C:\Users\Simon\AppData\Local\Temp\tmpoumuod3r\pip.zip\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "C:\Users\Simon\AppData\Local\Temp\tmpoumuod3r\pip.zip\pip\wheel.py", line 462, in move_wheel_files generated.extend(maker.make(spec)) File "C:\Users\Simon\AppData\Local\Temp\tmpoumuod3r\pip.zip\pip\_vendor\distlib\scripts.py", line 372, in make self._make_script(entry, filenames, options=options) File "C:\Users\Simon\AppData\Local\Temp\tmpoumuod3r\pip.zip\pip\_vendor\distlib\scripts.py", line 276, in _make_script self._write_script(scriptnames, shebang, script, filenames, ext) File "C:\Users\Simon\AppData\Local\Temp\tmpoumuod3r\pip.zip\pip\_vendor\distlib\scripts.py", line 212, in _write_script launcher = self._get_launcher('t') File "C:\Users\Simon\A…
accepted answer: http://stackoverflow.com/a/50071486
answer count: 3
tagged with: python
favorite count: 0
score: 17
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49737790

http://stackoverflow.com/comment/83009203
comment on: http://stackoverflow.com/q/48020089
type: Comment
type: QuestionComment
score: 2
has text: If you use pandas, this is as simple as `pd.IntervalIndex.from_breaks(n, closed='left')`.

http://stackoverflow.com/q/48095895
has answer: http://stackoverflow.com/a/48096374
has comment: http://stackoverflow.com/comment/83167852
favorite count: 0
has comment: http://stackoverflow.com/comment/83167480
has body: My program doesn't enter the searcholdvalue() function. My code, Edit: filename = Date + 'counter.json' if not os.path.isfile(filename): outfile = open(filename, "w") counter_value = 1 with open(filename, 'a') as feedjson: json.dump('counter_value : ' + str(counter_value), feedjson) json.dump('timestamp : ' + time_now , feedjson) json.dump('\n', feedjson,) feedjson.write('\n') def energy_consumption_per_hour(): if counter_value == 1: actual_time= time_now actual_val= counter_value old_time= datetime.today() - timedelta(hours=1) def search_old_value(): json_data = json.load(open(filename).read()) for i in json_data: if i['timestamp'] == old_time: search_old_value = i['counter_value'] break old_value= search_old_value energy_consumption_per_hour= ((actual_val- old_value)/(actual_time-old_time)) test= energy_counsuption_per_hour JSON file looks like this: "counter_value : 20""timestamp : 2018-01-04 12:44:05""\n" "counter_value : 10""timestamp : 2018-01-04 12:44:07""\n" The Result should be 10kWh. Question: Why isn't my code entering the searcholdvalue() function?
type: Question
has answer: http://stackoverflow.com/a/48096074
has answer: http://stackoverflow.com/a/48096129
tagged with: python
has comment: http://stackoverflow.com/comment/83167722
has comment: http://stackoverflow.com/comment/83166611
has title: why is my second function not being excecuted
has comment: http://stackoverflow.com/comment/83166637
answer count: 3
has comment: http://stackoverflow.com/comment/83168575
upvote count: 0
has comment: http://stackoverflow.com/comment/83167688
type: UnansweredQuestion
score: -4
downvote count: 4
has comment: http://stackoverflow.com/comment/83166569

http://stackoverflow.com/comment/83002791
score: 0
comment on: http://stackoverflow.com/q/48016441
type: QuestionComment
type: Comment
has text: It's not clear how the code you posted relates to the traceback you posted (it is best to include the actual text of the traceback in the question instead of a link).

http://stackoverflow.com/q/48158628
type: UnansweredQuestion
has title: Catching Exceptions on Python Flask RestPlus
tagged with: flask-restful
has answer: http://stackoverflow.com/a/51086606
tagged with: flask-restplus
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/56364555
tagged with: flask
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/68284087
tagged with: python
has body: I am struggling with finding a way to return a response when a call to one of my APIs does not return any result. I am using flask_restplus, and tried to use the @api.errorhandler annotation with no success and then I resorted to try a plain try/except block in my class. In this particular issue, I am trying to call the endpoint, where the GUID is a non-existent user in the database. http://localhost:5000/api/users/b3d8e86b-f2ad-4b6a-b768-e7adc1d94ced The user end point has been defined as following: import logging from flask import Response from flask_restplus import Resource, fields from neomodel.core import DoesNotExist from app.api.restplus import api from app.models import User log = logging.getLogger(__name__) ns = api.namespace('users', description='Users') user = api.model('user', { 'id': fields.Integer(readOnly=True, description='The internal id of of a user'), 'user_id': fields.String(required=True, description='The user unique identifier')} ) @ns.route('/') @api.response(404, 'Users not found.') class UsersList(Resource): @api.marshal_list_with(user) def get(self): """ Returns a list of all users :return: list_of_users """ try: users = User.nodes list_of_users = list(users) return list_of_users # return json.dumps(dict(users = [user.serialize for user in list_of_users])) except DoesNotExist: return Response(('{"No Content": "No user nodes found"}'), status = 200, mimetype = 'application/json') @ns.route('/&lt;string:user_id&gt;') class UserItem(Resource): @api.marshal_with(user) def get(self, user_id): """ Returns a user with the given user_id :param id: user_id :return: user """ try: user = User.nodes.get(user_id=user_id) return user except User.DoesNotExist: return Response({'message': 'Could not locate a user with the user_id provided.'}, 404) My initialization is done in app/init.py: import logging.config from flask import Flask, Blueprint from neomodel import clear_neo4j_database from neomodel import db from app.config import Configuration from app.w…
has answer: http://stackoverflow.com/a/64164044
answer count: 3
has comment: http://stackoverflow.com/comment/104025918
upvote count: 1

http://stackoverflow.com/q/48066585
has comment: http://stackoverflow.com/comment/83106506
has comment: http://stackoverflow.com/comment/83124537
has comment: http://stackoverflow.com/comment/83130417
linked to: http://stackoverflow.com/q/43288550
has title: IOPub data rate exceeded error in Jupyter Notebook
tagged with: python-2.7
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83107144
tagged with: jupyter
favorite count: 0
tagged with: jupyter-notebook
tagged with: python-3.x
has body: I was trying to make cufflinks offline, but it is showing an error in the Jupyter Notebook. Jupyter was able to execute every cell except the last line of code (cf.go_offline()). Can anyone fix it? For the first time, I am trying out this cufflinks library. Is there any issue with the version of the package, or is it any other issue? Input: from plotly import __version__ from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot init_notebook_mode(connected=True) import cufflinks as cf cf.go_offline() Output: warning message- IOPub data rate exceeded.The notebook server will temporarily stop sending output to the client in order to avoid crashing it. To change this limit, set the config variable`--NotebookApp.iopub_data_rate_limit
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83124439
has comment: http://stackoverflow.com/comment/83107194
tagged with: python
type: Question

http://stackoverflow.com/comment/83081594
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48054583
has text: The error message you omitted should point to `lista_caminhos[1:]`, which is invalid because functions cannot be subscripted.

http://stackoverflow.com/a/48038404
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48038335
type: Answer
upvote count: 1
has body: By default the interactivity is set to only print out last expression. You can change it by changing this setting - http://ipython.readthedocs.io/en/stable/config/options/terminal.html#configtrait-InteractiveShell.ast_node_interactivity You can do it like this from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all"

http://stackoverflow.com/a/48031064
has body: You want 76 digits right? from decimal import * getcontext().prec = 76 Decimal(1)/Decimal(3) Output Decimal('0.3333333333333333333333333333333333333333333333333333333333333333333333333333')
answers question: http://stackoverflow.com/q/48031020
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/83032575
accepted answer of: http://stackoverflow.com/q/48031020
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/48059815
tagged with: python
accepted answer: http://stackoverflow.com/a/48060814
type: AnsweredQuestion
score: 3
tagged with: metaclass
upvote count: 3
linked to: http://stackoverflow.com/q/13126727
has answer: http://stackoverflow.com/a/48060694
type: Question
has title: Auto instantiation of class after import in Python
tagged with: python-2.7
answer count: 3
has answer: http://stackoverflow.com/a/48060814
downvote count: 0
has answer: http://stackoverflow.com/a/48060413
favorite count: 0
has body: I want to automatically instantiate some classes in Python just after their modules have been imported, so there is no need to direct instantiation call. My setup can be stripped down to following code: class MetaTest(type): _instances = {} def __init__(cls, name, bases, attrs): super(MetaTest, cls).__init__(name, bases, attrs) MetaTest._instances[name] = cls() class Foo(object): __metaclass__ = MetaTest def __init__(self): super(Foo, self).__init__() class Bar(Foo): def __init__(self): super(Bar, self).__init__() But the instantiation fails on the super with: super(Foo, self).__init__() NameError: global name 'Foo' is not defined By any chance, could there be the way how to do this?
possible better answer: http://stackoverflow.com/a/48060413

http://stackoverflow.com/q/48173192
has title: how to run javascript in console similar to execute_script
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/48173622
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/48189070
type: UnansweredQuestion
tagged with: selenium
type: Question
answer count: 2
has body: I have a python selenium script to update date from datefield. script = """ var date = 'input[id="date"]'; return date.value = {}; """.format('2018-01-09') value = self.driver.execute_script(script) But how do I verify this works in browser console. I'm using Safari. In the console I can run document.getElementById('date').value = '2018-01-09' to change the date. But how can I verify execute_script works in console. I tried this in cosnsole but doesn't work $(function($){ var date = 'input[id="date"]'; return date.value = '2018-01-09'; });
tagged with: javascript
tagged with: console

http://stackoverflow.com/comment/83256188
comment on: http://stackoverflow.com/a/48139344
has text: @Basj [`cl` optimization flags](https://learn.microsoft.com/en-us/cpp/build/reference/o-options-optimize-code). A basic one would be `cl /O2 helloworld1.cpp`, though by default I'm pretty sure it already uses `/Ot`, which uses a set of speed optimizations.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83078640
score: 4
type: Comment
type: QuestionComment
has text: Add the two values `np.mean(lst) + np.std(lst)` and `np.mean(lst) - np.std(lst)`. If this were the Mathematics Stack Exchange site I would elaborate. Note this is true for the population standard deviation, which is what you are using. The sample standard deviation would be different.
comment on: http://stackoverflow.com/q/48052844

http://stackoverflow.com/comment/83118398
type: QuestionComment
comment on: http://stackoverflow.com/q/48062895
has text: Made an edit to answer these questions; I guess it would be possible to update my database to include a field for the 6 month average and compute it afterwards; the statements aren't changing after all, but I can't imagine that being the best solution :/
score: 0
type: Comment

http://stackoverflow.com/comment/83300431
type: Comment
has text: Thanks, Now my way is just remove these special characters, please see my answer
comment on: http://stackoverflow.com/a/48152974
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83128875
type: Comment
score: 0
has text: @MarcoBartel, it should work now with the last key moved to the beginning.
type: AnswerComment
comment on: http://stackoverflow.com/a/48075818

http://stackoverflow.com/comment/83479909
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48202688
has text: If your steps do not have the specific order. Then you need to use different intents to capture different responses.

http://stackoverflow.com/comment/83277359
score: 0
has text: I would guess you mean `axes.plot([], [], 'r-')` instead of `plt.plot([], [], 'r-')`. Apart the code looks ok.
comment on: http://stackoverflow.com/q/48123231
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48144210
answer count: 2
accepted answer: http://stackoverflow.com/a/48153773
score: 14
has title: Speeding up pyautogui screenshot() with region
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 14
tagged with: screenshot
tagged with: pyautogui
type: Question
has answer: http://stackoverflow.com/a/71946454
has answer: http://stackoverflow.com/a/48153773
possible better answer: http://stackoverflow.com/a/71946454
has body: I'm trying to speed up the screenshot function in pyautogui since I only need a small portion of the screen. The region variable is supposedly the way to this a.k.a. pyautogui.screenshot(region=(0,0,400,300)). However after doing some testing I found that no matter the size of the region it always takes the same amount of time to take the screenshot (~250ms). Also when saving the screenshot to a file pyautogui.screenshot('dummy.png', region=(0,0,400,300)) the region variable does not seem to matter and the whole screen is saved regardless. Any ideas on why this is not working properly? Running this on OS X

http://stackoverflow.com/a/48043805
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48043754
has body: Read up on operator-precedence - some operators bind stronnger then others - to get your desired logical output you should use ( ) to structure your logical conditions. Summarization: Operator Description lambda Lambda expression if – else Conditional expression or Boolean OR and Boolean AND not x Boolean NOT in, not in, is, is not, &lt;, &lt;=, &gt;, &gt;=, !=, == Comparisons, including membership tests and identity tests | Bitwise OR ^ Bitwise XOR &amp; Bitwise AND &lt;&lt;, &gt;&gt; Shifts +, - Addition and subtraction *, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder [5] +x, -x, ~x Positive, negative, bitwise NOT ** Exponentiation [6] await x Await expression x[index], x[index:index], x(arguments...), x.attribute Subscription, slicing, call, attribute reference (expressions...), [expressions...], {key: value...}, {expressions...} Binding or tuple display, list display, dictionary display, set display The ealier the operator the higher it binds. Please see the linked doku for subscription context
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/83122391
type: Comment
type: QuestionComment
has text: Aha! This error is occurring because the VP account didn't exist at the time I'm asking for it. It must have been made after midnight on inauguration day.
comment on: http://stackoverflow.com/q/48073335
score: 0

http://stackoverflow.com/comment/83031600
type: Comment
comment on: http://stackoverflow.com/q/48030571
score: 0
type: QuestionComment
has text: yep the development server should not been used in the production, but i want to test the functionality locally. Do you want me to use any other servers like uwsgi or gunicorn?

http://stackoverflow.com/comment/83140478
has text: Thank you Willem , xNinjaKitty, Ekhumoro for your time.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48082725

http://stackoverflow.com/q/48173168
favorite count: 0
has answer: http://stackoverflow.com/a/48174220
accepted answer: http://stackoverflow.com/a/48174220
tagged with: python
score: 11
type: AnsweredQuestion
has title: Use both sample_weight and class_weight simultaneously
has answer: http://stackoverflow.com/a/54265630
downvote count: 0
tagged with: tensorflow
type: Question
upvote count: 11
answer count: 2
possible better answer: http://stackoverflow.com/a/54265630
has body: My dataset already has weighted examples. And in this binary classification I also have far more of the first class compared to the second. Can I use both sample_weight and further re-weight it with class_weight in the model.fit() function? Or do I first make a new array of new_weights and pass it to the fit function as sample_weight? Edit: TO further clarify, I already have individual weights for each sample in my dataset, and to further add to the complexity, the total sum of sample weights of the first class is far more than the total sample weights of the second class. For example I currently have: y = [0,0,0,0,1,1] sample_weights = [0.01,0.03,0.05,0.02, 0.01,0.02] so the sum of weights for class '0' is 0.11 and for class '1' is 0.03. So I should have: class_weight = {0 : 1. , 1: 0.11/0.03} I need to use both sample_weight AND class_weight features. If one overrides the other then I will have to create new sample_weights and then use fit() or train_on_batch(). So my question is, can I use both, or does one override the other?
tagged with: keras

http://stackoverflow.com/q/48126156
favorite count: 0
upvote count: 0
downvote count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48126249
has answer: http://stackoverflow.com/a/48126369
score: -5
tagged with: if-statement
has title: How to use Boolean variable as the if conditon in Python
has body: I feel confused about the code as follows: define this findmin function to find the smallest number in alist, O(n^2) def findMin(alist): overallmin=alist[0] for i in alist: issmallest=True for j in alist: if i>j: issmallest=False if issmallest: overallmin = i return overallmin I can't understand: why the author set "issmallest = True" below the first for loop? Commonly when we feel like to use boolean values like this situation(such as assign boolean value to a variable at the beginning of the code or put the boolean values as the if-statement conditions)? Thanks!
linked to: http://stackoverflow.com/q/3754620
type: Question
tagged with: boolean
answer count: 2
has comment: http://stackoverflow.com/comment/83229043
has comment: http://stackoverflow.com/comment/83229030

http://stackoverflow.com/comment/83274573
score: 0
type: Comment
type: AnswerComment
has text: No, if you have a desktop app, I would say it only makes sense to run it from X session startup -- else there is no sense -- what display can the app show upon, if there is no active X session anywhere. I think others may have assumed, like me, that it was a server/console app (as is more frequently the case when we talk about app connecting to another computer on its own).
comment on: http://stackoverflow.com/a/48092266

http://stackoverflow.com/q/48111728
has comment: http://stackoverflow.com/comment/83265387
has title: Python Tkinter to create a dialog just like VC++ DoModel()
has comment: http://stackoverflow.com/comment/83258729
score: 0
has body: I am trying to create a dialog just like VC++ dlg.DoModal() did. I have created a parent dialog for my main UI with a 'button_A' on it. After I click on the 'button_A' on main UI, it will create a child dialog. Now I have 2 dialog, parent and child. My problem is the child dialog will be covered by parent dialog if I click on parent dialog. Is there any way to make child dialog always on top event I click on parent dialog? # python 2.7 import Tkinter as tk import tkFont from Tkinter import IntVar from Tkinter import * class MyGUI(): def __init__(self, master): self.master = master ## Set the focus on dialog window (needed on Windows) master.focus_set() ## Make sure events only go to our dialog master.grab_set() def start_test(): handle = tk.Toplevel(root) my_login_dialog = MyGUI(handle) handle.wait_window(handle) root = tk.Tk() root.title('') root.geometry('1024x768') ft1 = tkFont.Font(size = 10,weight = 'bold') tk.Button(root,text = 'Button_A',bg = 'white',height = 1,width = 8,font = ft1, command = start_test).place(x = 50,y = 10) root.mainloop()
has comment: http://stackoverflow.com/comment/83199332
tagged with: python
tagged with: tkinter-entry
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/83230982
type: QuestionComment
comment on: http://stackoverflow.com/q/48127152
has text: @tripleee: True, but a CSV file is not usually called an Excel file, since many other programs also work with such files. I wanted the OP to explain the CSV file, of course.
score: 0
type: Comment

http://stackoverflow.com/a/48098644
downvote count: 0
answers question: http://stackoverflow.com/q/48098415
type: Answer
has body: There is no such a thing. But you can achieve the same with: name = 'DATE' dataframe[name] = pd.to_datetime(dataframe[name]) No need for .loc Some methods support an inplace=True keyword argument. For example, sorting a dataframe gives you new one: &gt;&gt;&gt; df = pd.DataFrame({'DATE': [10, 7, 1, 2, 3]}) &gt;&gt;&gt; df.sort_values() &gt;&gt;&gt; df.sort_values('DATE') DATE 2 1 3 2 4 3 1 7 0 10 The original remains unchanged: &gt;&gt;&gt; df DATE 0 10 1 7 2 1 3 2 4 3 Setting inplace=True, modifies the original df: &gt;&gt;&gt; df.sort_values('DATE', inplace=True) &gt;&gt;&gt; df DATE 2 1 3 2 4 3 1 7 0 10
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83173142
has comment: http://stackoverflow.com/comment/83173621
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48098415

http://stackoverflow.com/comment/83264291
type: Comment
type: QuestionComment
has text: K-means is a very poor choice for product recommendation. And this data is not suitable for kmeans either. Why would you use it?
comment on: http://stackoverflow.com/q/48136738
score: 0

http://stackoverflow.com/a/48139067
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48138978
has comment: http://stackoverflow.com/comment/83326811
answers question: http://stackoverflow.com/q/48138978
upvote count: 3
has body: Unless you know something of the structure of the list (for instance ordered by price, or only three items can have such price), we can not make the algorithm faster than O(n) (linear time). So somehow we will have to loop. List comprehension We can use list comprehension like for instance: [d for d in l if d.get('price') == 50] (this will also filter out dictionaries that do not have a price attribute). Pandas We can also use pandas. Pandas is an efficient library for dataframes, that tends to outperform Python loops given the data is huge. In that case we can load the dictionaries in a datframe, perform filtering on it, and then retrieve a list of dictionaries. Note that these will be different dictionaries (i.e. other objects containing the same data). So the data is "copied". import pandas as pd df = pd.DataFrame(l) result = list(df[df.price == 50].T.to_dict().values()) So here we filter with df.price == 50. Note that behind the curtains there is however some loop involved to do the filtering. This is also a more declarative approach: the code explains more what it is doing, instead of how. How pandas does the filtering is not much of your problem, and the syntax shows rather elegantly that you are filtering data.
score: 3

http://stackoverflow.com/q/48152049
type: Question
score: 1
has answer: http://stackoverflow.com/a/48152181
tagged with: django-queryset
upvote count: 1
answer count: 1
has body: I have a model called LeaveEntry: class LeaveEntry(models.Model): date = models.DateField(auto_now=False, auto_now_add=False) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, limit_choices_to={'is_active': True}, unique_for_date='date' ) half_day = models.BooleanField(default=False) I get a set of LeaveEntries with the filter: LeaveEntry.objects.filter( leave_request=self.unapproved_leave ).count() I would like to get an aggregation called total days, so where a LeaveEntry has half_day=True then it is half a day so 0.5. What I was thinking based on the django aggregations docs was annotating the days like this: days = LeaveEntry.objects.annotate(days=&lt;If this half_day is True: 0.5 else 1&gt;)
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 0
tagged with: django
has title: How to run a custom aggregation on a queryset?

http://stackoverflow.com/q/48035785
tagged with: python
has comment: http://stackoverflow.com/comment/83042256
has comment: http://stackoverflow.com/comment/83042576
favorite count: 0
has comment: http://stackoverflow.com/comment/83042287
upvote count: 0
has comment: http://stackoverflow.com/comment/83042348
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83041721
has comment: http://stackoverflow.com/comment/83042379
has comment: http://stackoverflow.com/comment/83041881
type: Question
has body: I'm using python to create a program that involves me creating a CSV file and storing details in this file. I also need the program to read from the file and print the specified details. The following code shows how I have implemented the CSV file and how I make the program read from it. with open("SpeedTracker.csv", "a", newline="") as csvfile: writeToFile=csv.writer(csvfile) writeToFile.writerow([("Reg: ",RegistrationPlate),('First Camera Time:',FirstCameraTime),("Second Camera Time:",SecondCameraTime),("Average Speed:",AverageSpeed2,"MPH"),]) with open('SpeedTracker.csv', newline='') as csvfile: SpeedDetails = csv.reader(csvfile, delimiter=',') for Reg, Average in SpeedDetails: print(Reg, Average) However, when ever I run the code and follow the instructions as a user, I get an error that I can't understand. The error looks like this: Traceback (most recent call last): File "main.py", line 24, in &lt;module&gt; for Reg, Average in SpeedDetails: ValueError: too many values to unpack (expected 2) exited with non-zero status I don't know what I'm supposed to do to correct this. Can someone please show me where I'm going wrong and teach me the right method so that I know what to do in the future? Thanks a lot for the help, Mohammed.
has comment: http://stackoverflow.com/comment/83041946
score: -1
has comment: http://stackoverflow.com/comment/83042490
has comment: http://stackoverflow.com/comment/83042511
answer count: 1
has comment: http://stackoverflow.com/comment/83041729
has title: Python: CSV Traceback Error
has comment: http://stackoverflow.com/comment/83041620
has answer: http://stackoverflow.com/a/48035908
has comment: http://stackoverflow.com/comment/83041604
has comment: http://stackoverflow.com/comment/83042306
tagged with: http://stackoverflow.com/tag/csv
downvote count: 1

http://stackoverflow.com/q/48082523
type: AnsweredQuestion
has title: Pandas: Split large file into seperate files by Date, preserving original ordering.
type: Question
score: 5
possible better answer: http://stackoverflow.com/a/48082790
upvote count: 5
has answer: http://stackoverflow.com/a/48082790
has answer: http://stackoverflow.com/a/48082788
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
favorite count: 0
has body: I have a very large dataframe, with a date Index , that covers a period of multiple years by day. With each day containing multiple values. Date (DT_index) Description Value1 1 2015-01-12 stringvalue 10 2 2015-01-12 stringvalue 12 3 2015-01-12 stringvalue 14 4 2015-02-12 stringvalue 16 5 2015-02-12 stringvalue 348 6 2015-09-12 stringvalue 1 7 2015-09-12 stringvalue 9 (.....) 8456 2017-11-03 stringvalue 10 8457 2017-11-03 stringvalue 111 8458 2017-11-04 stringvalue 29 What I want is to split this csv into seperate files, based on month/year. (So a files like: 12-2015.csv, 01-2016.csv, 02-2016.csv) I've loaded the large csv into a pandas df and grouped it by month like so dfgp = df.groupby(pd.TimeGrouper(freq='M')) But the only operations available to me seem things like 'sum' or 'avg'. Which I do not want, I want to slice the large DF by month, not perform .apply operations that changes or aggregates the data. I've also tried this code: dfgp = [group[1] for group in df.groupby(df.index.date)] for x in result: name = str(x.index.date.month.year) x.to_csv(name, sep=';') This method came very close. I had 2 issues with it. 1. My naming method did not work: 'numpy.ndarray' object has no attribute 'month' When I remove my name method it iterates over the files. But the groups were made by day (example: 2015-12-13, with 6 entries, rather than 2015-12-alldays with 238 entries) I to correct the last issue with this code: result = [group[1] for group in df.groupby(df.index.date.month)] But that just threw the same error as before: 'numpy.ndarray' object has no attribute 'month' Does anyone know what I am doing wrong?
has comment: http://stackoverflow.com/comment/83139689
accepted answer: http://stackoverflow.com/a/48082788
tagged with: python

http://stackoverflow.com/comment/111790145
has text: This doesn't provide O(1) lookup: `item in list` is O(n).
type: AnswerComment
comment on: http://stackoverflow.com/a/63218975
type: Comment
score: 3

http://stackoverflow.com/a/48057676
has body: Do you have more than 18 events each day? If so up your max events This is what I have (in swift) and it returns events that are on days other than today let query = GTLRCalendarQuery_EventsList.query(withCalendarId: "primary") query.maxResults = 30 query.timeMin = GTLRDateTime(date: Date()) query.singleEvents = true query.orderBy = kGTLRCalendarOrderByStartTime service.executeQuery( query, delegate: self, didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:)))
type: Answer
answers question: http://stackoverflow.com/q/48047667
has comment: http://stackoverflow.com/comment/83093729
score: 0

http://stackoverflow.com/comment/84340693
has text: The only reason for using nearest neighbor is that it doesn't introduce new labels but it will make aliasing artifacts worse. Possibly treat the segmentation image as a real valued image instead of binary and use any other interpolator followed by thresholding to get a binary image back. Also, smooth the image when going to coarser resolution. This is just mitigating the issue, not solving it. For future discussions please use https://discourse.itk.org/ (simpleitk tag), the stackoverflow character limit on comments is restrictive.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48065819
type: AnswerComment

http://stackoverflow.com/comment/83065971
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48047184
has text: Possible duplicate of [How to install PyQt4 in anaconda?](https://stackoverflow.com/questions/21637922/how-to-install-pyqt4-in-anaconda)

http://stackoverflow.com/comment/83213234
has text: sorry, forgot to put t in there. Please see update. Its basically just a set
comment on: http://stackoverflow.com/q/48118386
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48016843
type: Answer
has comment: http://stackoverflow.com/comment/83027208
has body: A possible approach is to use the dateutil library. It contains many of the commonest datetime formats and can automagically detect these formats for you. &gt;&gt;&gt; from dateutil.parser import parse &gt;&gt;&gt; d1 = "12/29/2017" &gt;&gt;&gt; d2 = "2017-12-31" &gt;&gt;&gt; parse(d1) datetime.datetime(2017, 12, 29, 0, 0) &gt;&gt;&gt; parse(d2) datetime.datetime(2017, 12, 31, 0, 0) NOTE: dateutil is a 3rd party library so you may need to install it with something like: pip install python-dateutil It can be found on pypi: https://pypi.python.org/pypi/python-dateutil/2.6.1 And works with Python2 and Python3. Alternate Examples: Here are a couple of alternate examples of how well dateutil handles random date formats: &gt;&gt;&gt; d3 = "December 28th, 2017" &gt;&gt;&gt; parse(d3) datetime.datetime(2017, 12, 28, 0, 0) &gt;&gt;&gt; d4 = "27th Dec, 2017" &gt;&gt;&gt; parse(d4) datetime.datetime(2017, 12, 27, 0, 0)
answers question: http://stackoverflow.com/q/48016382
score: 0

http://stackoverflow.com/q/48045155
type: Question
possible better answer: http://stackoverflow.com/a/48045254
tagged with: object
type: AnsweredQuestion
tagged with: oop
has body: I am learning OOP (normally used to functional programming). This small script here runs, but I am not sure how to permanently save data values in the object (in this case the object's instance is named count, and I am trying to store self.count into the instance). #! /usr/bin/python3 class WordCounter: def __init__(self, count = 0): self.__count = count def set_count(self, path): try: nfile = open(path, "r") except: print("Could not open file") fileList = [] lowerCaseList = [] line = nfile.read() fileList.append(line.split()) nfile.close lowerCaseList = [word.lower() for word in fileList[0]] print(lowerCaseList) self.count = len(lowerCaseList) def get_word_count(self): return self.count def __str__(self): return "Total word count is: " + str(self.__count) if __name__ == "__main__": count = WordCounter() print(count) count.set_count("/home/swim/Desktop/word_counter.txt") print(count.get_word_count()) print(count) And here is the output: Total word count is: 0 ['here', 'is', 'a', 'bunch', 'of', 'text.', 'hopefully', 'all', 'of', 'this', 'gets', 'counted', 'correctly.', 'here', 'it', 'goes.'] 16 Total word count is: 0 I can see that my get and set methods are working correctly. But how do I get that self.count variable to be stored in the count object? print(count) evaluates to 0 before and after the get/set. I was hoping the str method would print 16 as well after the line count.set_count("/path/to/my/text/file") Any advice? Thank you
has comment: http://stackoverflow.com/comment/83061493
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/83061423
has comment: http://stackoverflow.com/comment/83061421
has title: How to correctly store values in an object's instance?
has answer: http://stackoverflow.com/a/48045280
accepted answer: http://stackoverflow.com/a/48045280
has answer: http://stackoverflow.com/a/48045254
tagged with: python
has comment: http://stackoverflow.com/comment/83063738
has comment: http://stackoverflow.com/comment/83065404
has answer: http://stackoverflow.com/a/48045377

http://stackoverflow.com/q/48056265
possible better answer: http://stackoverflow.com/a/48057800
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48057800
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83084760
favorite count: 0
has answer: http://stackoverflow.com/a/48057573
accepted answer: http://stackoverflow.com/a/48057573
tagged with: python
tagged with: excel
type: AnsweredQuestion
tagged with: dataframe
has body: I have a simple dataframe with one column and with header DD as given below. I want to create a new data-frame out of df as follows. Name &gt; &lt;NR-AR&gt; &gt; &lt;NR-AR-LBD&gt; &gt; &lt;NR-AhR&gt; &gt; &lt;NR-ER&gt; &gt; &lt;NR-ER-LBD&gt; &gt; &lt;NR-PPAR-gamma&gt; &gt; &lt;SR-ARE&gt; NCGC00261443-01 0 0 0 0 0 0 0 So the pattern should be like above.
type: Question
answer count: 2
has title: How to copy specific values in one pandas data frame into another?

http://stackoverflow.com/q/48158027
accepted answer: http://stackoverflow.com/a/48161071
has comment: http://stackoverflow.com/comment/83295919
has comment: http://stackoverflow.com/comment/83295860
has answer: http://stackoverflow.com/a/48159406
answer count: 2
tagged with: api
has body: I'm new to Python and using APIs and would love some help! Using the URL: http://api.worldbank.org/v2/countries?format=xml I want to gather each country's "iso2Code" and "name". I want to be able to output the data in a cleaner XML file format or an array (but would love the knowledge on how to do both!). I can currently write it to a file and make use of it there, but I am trying to sort it without that extra step. I haven't got much so far at all, but here it is: import requests url = ("http://api.worldbank.org/v2/countries?format=xml") r = requests.get(url) with open(('testcase.xml'), 'w') as f: f.write(r.text) test = r.text print(test) This is the data I receive upon printing. I want to gather the first two parts. Thanks for the help in advance!
has comment: http://stackoverflow.com/comment/83295994
downvote count: 0
possible better answer: http://stackoverflow.com/a/48159406
favorite count: 0
has comment: http://stackoverflow.com/comment/83295608
has answer: http://stackoverflow.com/a/48161071
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has title: How can I take specific data from an API and export it without writing the data to a file?
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/83295826

http://stackoverflow.com/q/48025614
has comment: http://stackoverflow.com/comment/83021222
has comment: http://stackoverflow.com/comment/83021599
downvote count: 0
has comment: http://stackoverflow.com/comment/83020979
favorite count: 0
has comment: http://stackoverflow.com/comment/83021177
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I have several statements if people like a product or not I have anonymized the comments, and used other names. As the classification problem is very similar to those of movie reviews, I relied totally on the tutorial from http://www.nltk.org/book/ch06.html. Section 1.3. from nltk.corpus import movie_reviews documents = [(list(movie_reviews.words(fileid)), category) for category in movie_reviews.categories() for fileid in movie_reviews.fileids(category)] random.shuffle(documents) all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words()) word_features = list(all_words)[:2000] [1] def document_features(document): [2] document_words = set(document) [3] features = {} for word in word_features: features['contains({})'.format(word)] = (word in document_words) return features featuresets = [(document_features(d), c) for (d,c) in documents] train_set, test_set = featuresets[100:], featuresets[:100] classifier = nltk.NaiveBayesClassifier.train(train_set) So far so good. My concern is that my data are organized in following way. sex;statement;income_dollar_year "m";"I REALLY like milk. It taste soo good and is healthy. Everyone should drink it";40000 "f";"Milk itself is tasty, but I don't like how cows are kept in huge stables";30000 "m";"I don't like milk, I have intolerance against lactose, so my stomach pains";35000 I just want to have labels that say that statement one and two are positive and third one is negative. I also know that I have to remove all words that are not in the dataset, otherwise I would have Zeros and that would make me into trouble. As I do not have an idea about how the data in movies_review are exactly organized, I don't come to a solution. my idea is to get a csv like this: sex;statement;income_dollar_year;class "m";"I REALLY like milk. It taste soo good and is healthy. Everyone should drink it";40000;"pos" "f";"Milk itself is tasty, but I don't like how cows are kept in huge stables";30000;"pos" "m";"I don't like milk, I have intolerance …
has comment: http://stackoverflow.com/comment/83020883
answer count: 0
score: 1
has title: How to use comments in csv table to get a text classification?
upvote count: 1
has comment: http://stackoverflow.com/comment/83021910
type: Question
has comment: http://stackoverflow.com/comment/83021086
tagged with: nltk

mongodb
tags question: http://stackoverflow.com/q/48059406
tags question: http://stackoverflow.com/q/48031026
tags question: http://stackoverflow.com/q/48166336
tags question: http://stackoverflow.com/q/48065435
tags question: http://stackoverflow.com/q/48112019
tags question: http://stackoverflow.com/q/48123581
tag name: mongodb
tags question: http://stackoverflow.com/q/48021748
tags question: http://stackoverflow.com/q/48107682
tags question: http://stackoverflow.com/q/48145215
tags question: http://stackoverflow.com/q/48161009
tags question: http://stackoverflow.com/q/48095268
tags question: http://stackoverflow.com/q/48090385
type: Tag
tags question: http://stackoverflow.com/q/48055888
tags question: http://stackoverflow.com/q/48114083
tags question: http://stackoverflow.com/q/48060354
tags question: http://stackoverflow.com/q/48135071
tags question: http://stackoverflow.com/q/48168329
tags question: http://stackoverflow.com/q/48161525
tags question: http://stackoverflow.com/q/48026589
tags question: http://stackoverflow.com/q/48127261
tags question: http://stackoverflow.com/q/48150070
tags question: http://stackoverflow.com/q/48055354
tags question: http://stackoverflow.com/q/48158277
tags question: http://stackoverflow.com/q/48070863
tags question: http://stackoverflow.com/q/48073980
tags question: http://stackoverflow.com/q/48028180
tags question: http://stackoverflow.com/q/48148776
tags question: http://stackoverflow.com/q/48030298
tags question: http://stackoverflow.com/q/48028493
tags question: http://stackoverflow.com/q/48059662
tags question: http://stackoverflow.com/q/48161770

http://stackoverflow.com/comment/83127193
type: Comment
type: QuestionComment
has text: Why would it be more Pythonic to use assert? On the contrary, using exceptions is the right way.
score: 2
comment on: http://stackoverflow.com/q/48076764

http://stackoverflow.com/comment/83211586
type: Comment
has text: Under what account have you started X11? E.g., I start it under local user `phd`; when I need to run commands as root I use `sudo` or run a new terminal (I use `rxvt`) and login as root.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48105487

http://stackoverflow.com/comment/83077055
type: Comment
comment on: http://stackoverflow.com/a/48052480
score: 1
type: AnswerComment
has text: @Саша-Черных You can read more about it here https://www.computerhope.com/jargon/f/flag.htm

http://stackoverflow.com/comment/83146462
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48085455
type: Comment
has text: Did you forget the `return aScore` at the end of the 2 function?

http://stackoverflow.com/a/48142429
score: 2
answers question: http://stackoverflow.com/q/48142400
has body: You return result of function inside loop. And don't need to increment m because for m in range(...) do it for you. for m in range(len(coeffWaterDensity)): densityH2O = densityH2O + coeffWaterDensity[m] * tDegC ** (4 - m) return densityH2O
downvote count: 0
has comment: http://stackoverflow.com/comment/83264834
upvote count: 2
type: Answer

http://stackoverflow.com/comment/83226352
score: 0
comment on: http://stackoverflow.com/q/48124647
type: QuestionComment
type: Comment
has text: Have you looked at what is in the result of `open("Memory.txt", 'r').readlines()`?

http://stackoverflow.com/comment/83004148
has text: I'll do that. I'm new to python so I appreciate the advice. I don't really understand what you meant by" no fragile/hard to error check/non-portable external program usage."
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48017009
score: 0

http://stackoverflow.com/comment/83137068
comment on: http://stackoverflow.com/q/48081412
type: Comment
type: QuestionComment
has text: So, the posted loopy code works, but isn't clean enough?
score: 0

http://stackoverflow.com/comment/83298156
type: QuestionComment
has text: It may help if you provide the code for your model/serializer.
score: 1
comment on: http://stackoverflow.com/q/48158309
type: Comment

http://stackoverflow.com/comment/83065288
has text: @ArunRamachandran I updated the response to show how you might proxy traffic to the kibaba server. You could then use a firewall rule and, depending on your topology, limit the bind interface to restrict access to the kibana server.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48039246

http://stackoverflow.com/comment/83243587
comment on: http://stackoverflow.com/a/48121884
has text: hey thanks for getting back to me. Yea I actually skipped that part of the book and was just getting back to it now, lol, anyway I have been running the code on my raspberry pi, simply because that is the main thing i have been working on lately. (for a school project) will the code need to change in the raspberry pi.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48108697
tagged with: python
answer count: 4
tagged with: generator
accepted answer: http://stackoverflow.com/a/48109106
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48109160
has comment: http://stackoverflow.com/comment/83192599
type: Question
has title: Confusion on how Python generator works
has comment: http://stackoverflow.com/comment/83192793
possible better answer: http://stackoverflow.com/a/48109003
has answer: http://stackoverflow.com/a/48109003
downvote count: 0
favorite count: 0
has body: Below is a copy from a Python book, the explanation on how generator works is not clear to me at all. gen.send.py def counter(start=0): n = start while True: result = yield n # A print(type(result), result) # B if result == 'Q': break n += 1 c = counter() print(next(c)) # C print(c.send('Wow!')) # D print(next(c)) # E print(c.send('Q')) # F And the output of the above is: $ python gen.send.py 0 &lt;class 'str'&gt; Wow! 1 &lt;class 'NoneType'&gt; None 2 &lt;class 'str'&gt; Q Traceback (most recent call last): File "gen.send.py", line 14, in &lt;module&gt; print(c.send('Q')) # F StopIteration Learning Python. . VitalBook file. Explanation from book: We start the generator execution with a call to next (#C). Within the generator, n is set to the same value of start. The while loop is entered, execution stops (#A) and n (0) is yielded back to the caller. 0 is printed on the console. #Q1: At this point, n=1, right? because n+=1 should be executed since print(type(result), result) is executed. We then call send (#D), execution resumes and result is set to 'Wow!' (still #A), then its type and value are printed on the console (#B). result is not 'Q', therefore n is incremented by 1 and execution goes back to the while condition, which, being True, evaluates to True (that wasn't hard to guess, right?). Another loop cycle begins, execution stops again (#A), and n (1) is yielded back to the caller. 1 is printed on the console. Q2: 'Wow!' is sent to who? n, start, or result? and how? If n='Wow!' and what is the consequence of n+=1 then? At this point, we call next (#E), execution is resumed again (#A), and because we are not sending anything to the generator explicitly, Python behaves exactly like functions that are not using the return statement: the yield n expression (#A) returns None. Q3: Why None? whose value (start, n, result) exactly is suspended in this generator result therefore is set to None, and its type and value are yet again printed on the console (#B). Execution…
has answer: http://stackoverflow.com/a/48109208
linked to: http://stackoverflow.com/q/1756096
upvote count: 2
has answer: http://stackoverflow.com/a/48109106

http://stackoverflow.com/q/48100058
type: Question
has comment: http://stackoverflow.com/comment/83175126
has title: What happens under the hood in if statement?
accepted answer: http://stackoverflow.com/a/48104142
has comment: http://stackoverflow.com/comment/83175149
has comment: http://stackoverflow.com/comment/83175488
answer count: 2
score: 2
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83175385
has answer: http://stackoverflow.com/a/48100185
has comment: http://stackoverflow.com/comment/83175373
tagged with: python
has answer: http://stackoverflow.com/a/48104142
possible better answer: http://stackoverflow.com/a/48100185
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83175368
has comment: http://stackoverflow.com/comment/83175544
upvote count: 2
has comment: http://stackoverflow.com/comment/83175219
has body: What goes on under the hood in if statement? For example: list_ = [1, 2, 3] str_ = '' if str_ or list_: # do something Can we say that implicitly something like this happens? if bool(str_ or list_) is True: # do something
has comment: http://stackoverflow.com/comment/83175995

http://stackoverflow.com/a/48083918
accepted answer of: http://stackoverflow.com/q/48079362
type: AcceptedAnswer
has body: You can first convert your distance matrix into a numpy array if it isn't already so, and then df['dist'] = dm.mean(axis = 0) to save the row-wise average distances as a column, and then df[df.dist == min(df.dist)] is going to give you the row with minimum average distance to others. To get the index, you can select only the first column like so: df[df.dist == min(df.dist)].iloc[:,0]
upvote count: 2
answers question: http://stackoverflow.com/q/48079362
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/83566778
comment on: http://stackoverflow.com/a/48242260
score: 0
type: Comment
has text: I am part of the team that is building the Python extension for HELICS. I was involved in putting together that example repo as well. I'm fairly sure that what you have described isn't the problem. In fact, I was able to create a minimal working example here - https://stackoverflow.com/questions/48289858/fatal-error-in-extension-pythreadstate-get-no-current-thread-when-using-swig-w so others can test to see if they have this error, even without installing helics.
type: AnswerComment

http://stackoverflow.com/comment/83009605
has text: so you are literally linking to the same page and asking if he saw it?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48018835
score: 0

http://stackoverflow.com/q/48147088
tagged with: python
upvote count: 4
answer count: 0
has body: I was trying to use TensorRT Python API to convert a model. An error occured while defining a concatenation layer, the code is: concatLayer = network.add_concatenation([conv1.get_output(0),conv2.get_output(0)],2) The error info is: TypeError: in method 'NetworkDefinition_add_concatenation', argument 2 of type 'nvinfer1::ITensor *const *' 'conv1.get_output(0)' will return an ITensor* variable, how should I convert it to the type of ITensor *const* ? Seems that the TensorRT python API was wrapped from its C++ version with SWIG, the API reference of add_concatenation() is: addConcatenation(ITensor *const *inputs, int nbInputs)=0 -> IConcatenationLayer * add a concatenation layer to the network Parameters: inputs (*) – the input tensors to the layer nbInputs (*) – the number of input tensors also (See) – Returns: the new concatenation layer, or null if it could not be created **Warning** (All tensors must have the same dimensions for all dimensions except for channel.)
type: Question
tagged with: swig
score: 4
tagged with: tensorrt
has title: TensorRT 3 Python API: add_concatenation
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/48069469
has body: If the objects are all of similar types, you might have more success isolating a single example in the image and then using feature matching to detect them. A full solution would be out of scope for Stack Overflow, but my suggestion for progress would be to first somehow find one or more "correct" examples using your current rectangle retrieval method. You could probably look for all your samples that are of the expected size, or that are accurate rectangles. Once you have isolated a few positive examples, use some feature matching techniques to find the others. There is a lot of reading up you probably need to do on it but that is a potential solution. A general summary is that you use your positive examples to find "features" of the object you want to detect. These "features" are generally things like corners or changes in gradient. OpenCV contains many methods you can use. Once you have the features, there are several algorithms in OpenCV you can look at that will search the image for all matching features. You’ll want one that is rotation invariant (can detect the same features arranged in different rotation), but you probably don’t need scale invariance (can detect the same features at multiple scales). My one concern with this method is that the items you are searching for in your images are quite small. It might be difficult to find good, consistent features to match on.
answers question: http://stackoverflow.com/q/48069356
downvote count: 0
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/q/48155269
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83290942
has comment: http://stackoverflow.com/comment/83290286
has answer: http://stackoverflow.com/a/48156129
has title: Tensorflow queues hang
has body: This Cifar10 model, altered somewhat from the Cifar10 tutorial, seems to spike and then hang, never returning control of the program to the interpreter. It has been suggesting that it is on account of having not called .start_queue_runners. However, there doesn't seem to be any code in the original Cifar10 tutorial that calls .start_queue_runners, and it runs just fine. (I'm using the single-GPU training code cifar10_train.py... the multiple-GPU code DOES call that method) import os import tensorflow as tf import functools from urllib.request import urlretrieve import zipfile import tarfile import sys # Process images of this size. Note that this differs from the original CIFAR # image size of 32 x 32. If one alters this number, then the entire model # architecture will change and any model would need to be retrained. IMAGE_SIZE = 24 # Global constants describing the CIFAR-10 data set. NUM_CLASSES = 10 NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 50000 NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 10000 def maybe_download_and_extract(): main_directory = "../data/" cifar_10_directory = main_directory+"cifar_10/" if not os.path.exists(main_directory): os.makedirs(main_directory) if not os.path.exists(cifar_10_directory): url = "http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz" filename = url.split('/')[-1] file_path = os.path.join(main_directory, filename) zip_cifar_10 = file_path file_path, _ = urlretrieve(url=url, filename=file_path, reporthook=print_download_progress) print() print("Download finished. Extracting files.") if file_path.endswith(".zip"): zipfile.ZipFile(file=file_path, mode="r").extractall(main_directory) elif file_path.endswith((".tar.gz", ".tgz")): tarfile.open(name=file_path, mode="r:gz").extractall(main_directory) print("Done.") os.rename(main_directory+"cifar-10-batches-bin", cifar_10_directory) os.remove(zip_cifar_10) return ( [os.path.join(cifar_10_directory, 'data_batch_{}.bin'.format(i)) for i in range(1,6)], [os.path.join(cifar_10_directory, 'test_batch.bin…
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48156036
tagged with: python
score: 0
tagged with: tensorflow

hex
tags question: http://stackoverflow.com/q/48147975
tags question: http://stackoverflow.com/q/48069247
tags question: http://stackoverflow.com/q/48068116
tags question: http://stackoverflow.com/q/48059157
tag name: hex
tags question: http://stackoverflow.com/q/48025710
tags question: http://stackoverflow.com/q/48146012
tags question: http://stackoverflow.com/q/48127757
type: Tag

http://stackoverflow.com/a/61678194
answers question: http://stackoverflow.com/q/48160554
type: Answer
has body: I just got round a similar problem by reading Michael Crenshaw's answer above. Here's what worked for me: Load the page you want to scrape. Go to inspect and select network. Now click the show more button. You should now see in the network tab the exact url where the request is being made to. It's a lot easier if you don't open the network tab until the page has already loaded - that way the only information in the tab is the request it makes when you click show more. I then just added a few lines to my code like this: page_source = response.text if "Show More" in page_source: And then after this I added my scraping function to that while getting it to iterate through the url structure. There's a good post on how to do that on scrapy here - https://blog.scrapinghub.com/2016/06/22/scrapy-tips-from-the-pros-june-2016. Hope this helps.
score: 0

http://stackoverflow.com/comment/83018815
has text: Why even use ascii? See this [SO post](https://stackoverflow.com/questions/8365660/python-mysql-unicode-and-encoding).
type: QuestionComment
comment on: http://stackoverflow.com/q/48023567
score: 0
type: Comment

http://stackoverflow.com/q/48124108
has comment: http://stackoverflow.com/comment/83302286
answer count: 1
tagged with: shell
favorite count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48173703
has title: using workflow tool to structure shell scripts
score: 0
type: Question
has body: I have a bunch of shell scripts and I want to sequence them. I can write a master shell script. But I'm not so good at shell scripting. I heard about drake as a job control flow tool. I want to see if it can used for creating/running the shell scripts in an integrated fashion Example: nohup run shell_script_1.ksh Once this is successfully complete run next else exit with error code 1 nohup run shell_script_2.ksh &amp; nohup run shell_script_3.ksh Once both the scripts run successfully, move to next else exit with error code 2 nohup ksh shell_script_4.ksh&amp; nohup ksh shell_script_5.ksh&amp; nohup ksh shell_script_6.ksh&amp; Once the above 3 scripts complete, move to next else exit with error code3 finally execute nohup ksh shell_script_4.ksh Alternatively, If I arrange thethe rules for running these scripts in a YAML file, is there any master shell script generator that I can use? Thanks Pari
tagged with: workflow

http://stackoverflow.com/comment/83030048
type: QuestionComment
has text: Possible duplicate of [how to make tkinter <Enter> event work when <button-1> is pressed?](https://stackoverflow.com/q/47944322/7032856).
score: 0
comment on: http://stackoverflow.com/q/48029920
type: Comment

http://stackoverflow.com/q/48143769
tagged with: spacy
has comment: http://stackoverflow.com/comment/83413331
has body: The following question is about the Spacy NLP library for Python, but I would be surprised if the answer for other libraries differed substantially. What is the maximum document size that Spacy can handle under reasonable memory conditions (e.g. a 4 GB VM in my case)? I had hoped to use Spacy to search for matches in book-size documents (100K+ tokens), but I'm repeatedly getting crashes that point to memory exhaustion as the cause. I'm an NLP noob - I know the concepts academically, but I don't really know what to expect out of the state of the art libraries in practice. So I don't know if what I'm asking the library to do is ridiculously hard, or so easy that must be something I've screwed up in my environment. As far as why I'm using an NLP library instead of something specifically oriented toward document search (e.g. solr), I'm using it because I would like to do lemma-based matching, rather than string-based.
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83454437
type: Question
has title: Spacy NLP library: what is maximum reasonable document size
score: 10
upvote count: 10
answer count: 1
has answer: http://stackoverflow.com/a/50630812
tagged with: nlp
accepted answer: http://stackoverflow.com/a/50630812
favorite count: 0

http://stackoverflow.com/comment/83283209
score: 1
type: Comment
comment on: http://stackoverflow.com/a/48152369
has text: I want to group by three columns not all columns.
type: AnswerComment

http://stackoverflow.com/a/57558548
has body: You should consider re-indexing it based on axis 0 (indexes) new_order = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] df1 = df.reindex(new_order, axis=0)
type: Answer
score: 16
upvote count: 16
answers question: http://stackoverflow.com/q/48042915
downvote count: 0

http://stackoverflow.com/comment/83073162
has text: @MadPhysicist but how is that different? I'd either have to load the entire file into memory, which is unfeasible with a 40gb file, or still scann a file on disk which is what sed does?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48050639

http://stackoverflow.com/comment/83184870
has text: `in` is faster in a set than a list, but what does it show regarding short-circuiting?
type: Comment
comment on: http://stackoverflow.com/a/48104545
score: 0
type: AnswerComment

http://stackoverflow.com/comment/125621886
type: AnswerComment
type: Comment
has text: Well without a [mcve] it is hard to tell. But your error says that this object does not accept StringIO and expect bytes. Maybe you will get success with a `io.BytesIO` object.
comment on: http://stackoverflow.com/a/48021404
score: 0

http://stackoverflow.com/q/48087665
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/66919800
tagged with: graphql
tagged with: python
score: 3
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/55402280
tagged with: graphene-python
type: Question
tagged with: object
has title: is there possible chance to pass array of objects (json) as input field for mutation? graphene-python
has answer: http://stackoverflow.com/a/48096296
has body: I am trying to pass json field as input for my graphql mutation. I have been trying and searching but just no luck. I can pass array fine with I know by defining graphene.List(graphene.String) would work for passing array of strings. I figured there's a type named graphene.JSONstring() which I thought would work if I use it with graphene.List(graphene.JSONstring) but no luck, still getting errors saying type is not right. I have something like this during the mutation mutation { create(data:{ field1: [ { "first": "first", "last": "last" }, { "first":"first1", "last":"last1" } ] }) } as for input class class NameInput(graphene.InputObjectType): # please ignore the same field names, just listing what I have tried field1 = graphene.JSONString() field1 = graphene.List(graphene.JSONString) field1 = graphene.List(graphene.String) Does anyone has an idea how this would work? Thanks in advance
answer count: 3
downvote count: 0

http://stackoverflow.com/q/48051028
tagged with: python
type: AnsweredQuestion
has title: Convert a string to date Format: DD-MMM-YYYY to date time in Python
has body: I have a pandas dataframe with a column containing strings like follows 01-May-2012 16:44:55.113 01-Jun-2012 18:49:57.466 01-May-2012 14:64:45.119 01-May-2012 14:23:55.113 and I want to convert it to following format. 2012-05-01 16:44:55.113 2012-06-01 18:49:57.466 2012-05-01 14:64:45.119 2012-05-01 14:23:55.113 I tried using pandas.to_datetime(df['date time']) but I get the error unknown string value. I also tried splitting the string into two columns and convert only the date part but faced similar errors
linked to: http://stackoverflow.com/q/26763344
has comment: http://stackoverflow.com/comment/83073885
type: Question
has answer: http://stackoverflow.com/a/48051116
duplicate of: http://stackoverflow.com/q/26763344
tagged with: dataframe
tagged with: date
accepted answer: http://stackoverflow.com/a/48051116
score: 0
has comment: http://stackoverflow.com/comment/83073853
tagged with: pandas
answer count: 1
tagged with: string
linked to: http://stackoverflow.com/q/46941452
duplicate of: http://stackoverflow.com/q/46941452

http://stackoverflow.com/comment/83270825
score: 0
type: Comment
has text: Therefore you can look at the Levenshtein distance [wiki](https://en.wikipedia.org/wiki/Levenshtein_distance) [python](https://www.python-course.eu/levenshtein_distance.php)
comment on: http://stackoverflow.com/a/48115626
type: AnswerComment

http://stackoverflow.com/q/48085319
has body: I'm trying to read a csv file the its header contains foreign characters and I'm having a lot of problems with this. first of all, I'm reading the file with a simple csv.reader filename = 'C:\\Users\\yuval\\Desktop\\בית ספר\\עבודג\\new\\resources\\mk'+ str(mkNum) + 'Data.csv' raw_data = open(filename, 'rt', encoding="utf8") reader = csv.reader(raw_data, delimiter=',', quoting=csv.QUOTE_NONE) x = list(reader) header = x[0] data = np.array(x[1:]).astype('float') The var header should be an array that contains the file headers, but the array it returns to me is ['\ufeff"dayPart"', '"length"', '"ifPhoto"', '"ifVideo"', '"ifAlbum"', '"לא"', '"הוא"', '"בכל"', '"אותם"', '"זה"', '"הם"', '"כדי"', '"את"', '"יש"', '"לי"', '"היא"', '"אני"', '"רק"', '"להם"', '"על"', '"עם"', '"של"', '"המדינה"', '"כל"', '"גם"', '"הזה"', '"אם"', '"ישראל"', '"לכל"', '"מי"', '"ל"', '"אמסלם"', '"לנו"', '"אבל"', '"זו"', '"אין"', '"שבת"', '"שלום"', '"כ"', '"שלנו"', '"היום"', '"ומבורך"', '"ח"', '"דודי"', '"ר"', '"הפנים"', '"מה"', '"כי"', '"ה"', '"אחד"', '"ולא"', '"יותר"'] and I don't know why it adds the \ufeff in the first object and double quotation marks. After that, I need to write to another csv file and use foreign characters in the header as well. I was trying to do this like that, but it wrote the characters as weird symbols. with open('C:\\Users\\yuval\\Desktop\\בית ספר\\עבודג\\new\\variance reduction 1\\mk'+ str(mkNum) + 'Data.csv', 'w', newline='', encoding='utf8') as csvFile: csvWriter = csv.writer(csvFile, delimiter=',') csvWriter.writerow(newHeader) Does any one know how to fix this problem and work with utf8 encoding in the csv file's header?
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83145898
tagged with: http://stackoverflow.com/tag/csv
has title: Python - Reading and writing csv files with utf-8 encoding
tagged with: python
tagged with: utf-8
score: 12
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83146774
type: Question
tagged with: export-to-csv
tagged with: encoding
has comment: http://stackoverflow.com/comment/83145586
has answer: http://stackoverflow.com/a/48085864
upvote count: 12

http://stackoverflow.com/q/48085291
score: -1
has body: import re score = 0 capital_letters = r'[A-Z]' a = re.compile(capital_letters) lowercase_letters = r'[a-z]' b = re.compile(lowercase_letters) def increase_score (aValue, aScore): aScore += aValue return aScore def upper_score(test_string, aScore): if re.match(a, test_string): aScore = increase_score(5, aScore) print (aScore) print("UPPERCASE") else: print("The password needs capital letters for a higher score") def lower_score(test_string, aScore): if re.match(b, test_string): aScore = increase_score(5, aScore) print (aScore) print("LOWERCASE") else: print("The password needs lowercase letters for a higher score") password = input("Enter a password to check") upper_score(password, score) lower_score(password, score) If I input all upper case letters I get this output: 5 UPPERCASE The password needs lowercase letters for a higher score If I input all lower case letters I get this output: The password needs capital letters for a higher score 5 LOWERCASE When i mix upper case annd lowercase i get this output: 5 UPPERCASE 5 LOWERCASE Even though there are both uppercase and lowercase letters the score is still 5 instead of 10. I want the score to be cumulative and build ontop of each other.
has comment: http://stackoverflow.com/comment/83145884
tagged with: function
upvote count: 0
answer count: 1
tagged with: variables
favorite count: 0
tagged with: scope
has title: how to increase value of a variable integer in python
accepted answer: http://stackoverflow.com/a/48085455
tagged with: python
type: AnsweredQuestion
downvote count: 1
linked to: http://stackoverflow.com/q/291978
type: Question
tagged with: overriding
has answer: http://stackoverflow.com/a/48085455
duplicate of: http://stackoverflow.com/q/291978

http://stackoverflow.com/q/48129540
has comment: http://stackoverflow.com/comment/83236319
has comment: http://stackoverflow.com/comment/83236924
has answer: http://stackoverflow.com/a/48130441
has comment: http://stackoverflow.com/comment/83236354
tagged with: sql
tagged with: sqlite
has comment: http://stackoverflow.com/comment/83236634
has comment: http://stackoverflow.com/comment/83236597
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/83236164
tagged with: python-3.x
has body: sql database SQL database attached as photo. The maximum allowed quantity for item_id 12 is 7 at any given moment. I want to write a program that will take a user's order and check the database to see if the desired quantity is available at the time that they want it. the user will input a start date, end date and quantity. I have tried many ways but my code seems to only check orders starting on the same exact dates as the user, instead of all orders of the same item that have overlapping time-frame. This is the code I made so far: Any help would be appreciated, need to add this feature to my end of year program. lines = ["EACKAH",12] conn = sqlite3.connect("accounts.sqlite3") cur = conn.cursor() cur.execute("SELECT start_date,end_date,duration,quantity FROM hirers WHERE item_id=?", (str(lines[1]),)) data = cur.fetchall() print(data) cur.execute("SELECT quantity FROM on_sale WHERE item_id=?", (str(lines[1]),)) max_qty = cur.fetchall() item_max = int(max_qty[0][0]) cur.close() duration = [0.5,1,1.5,2.5,3] #load the desired quantity by the user qty_num = 0 if (self.qty_entry.get()).isdigit() == True and int(self.qty_entry.get()) &lt; 100: qty_num = int(self.qty_entry.get()) else: qty_num = 0 print("i..........", qty_num) #duration the user wants to hire the tool for self.index_duration = int(self.duration_list.curselection()[0]) end_num = int(round(duration[self.index_duration],0)) print("The user wants it for", end_num) check_count = 0 if len(data) == 0: print("All Good") else: for i in data: lst = i print(lst) in_between = [] counter = 0 dur = int(lst[2]) sql_qty = lst[3] date_check = [] while counter != dur: date_1 = datetime.datetime.strptime(str(lst[0]), "%d-%m-%Y") end_date = date_1 + datetime.timedelta(days=counter) date_check.append(end_date.strftime('%d-%m-%Y')) counter = counter + 1 print(date_check) print("..........") for i in date_check: #load the current date d = datetime.datetime.strptime(str(self.date_entry.get()), "%d-%m-%Y") end = d + datetime.timed…
has comment: http://stackoverflow.com/comment/83236045
tagged with: python
has comment: http://stackoverflow.com/comment/83236851
has comment: http://stackoverflow.com/comment/83236811
accepted answer: http://stackoverflow.com/a/48130441
has comment: http://stackoverflow.com/comment/83237061
type: AnsweredQuestion
downvote count: 1
type: Question
has title: How would i check to see if the item in this database is available (sqlite3)
has comment: http://stackoverflow.com/comment/83246366
has comment: http://stackoverflow.com/comment/83236122
has comment: http://stackoverflow.com/comment/83236730
upvote count: 0
answer count: 1
tagged with: python-3.6

http://stackoverflow.com/q/48155967
type: Question
has comment: http://stackoverflow.com/comment/83292374
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/83291487
tagged with: random
has comment: http://stackoverflow.com/comment/83292622
has body: I've started using Django 2.0 and Python 3.6.3 to develop a website which will display customized "Posts", as in a blog Post. I want the user to be able to click a button that basically says "Random Post". This button will take them to a template which loads a random blog post. Here's my Post model: class Post(models.Model): post_id = models.AutoField(primary_key=True) ... other fields ... other fields def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Here are some relevant views: class PostListView(ListView): model = Post template_name = 'blog/post_list.html' class PostDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' Here is my problematic view: import random def random_post(request): post_ids = Post.objects.all().values_list('post_id', flat=True) random_obj = Post.objects.get(post_id=random.choice(post_ids)) context = {'random_post': random_obj,} return render(request, 'blog/random_post.html', context) Here I am trying to create a Values List of all post_id values for the Post model. Then I'm trying to get a random choice from this Values List, which would be a random id. Then I'm trying to create a context and render a template using this logic. Here are relevant urlpatterns: urlpatterns = [ path('post/&lt;int:pk&gt;/', views.PostDetailView.as_view(),name='post_detail'), path('post/random/&lt;int:pk&gt;', views.random_post, name='random_post'), Needless to say this is not working. If I leave off the "int:pk" it renders a blank template with no data - no blog Post. If I include the , it causes an error - No Arguments Found. I assume that no data is being queried in the view, or the data isn't being properly sent from the view to the template. I am new to Django. I appreciate your help!
has answer: http://stackoverflow.com/a/48157213
tagged with: url
has title: Allow user to select random blog bost
has answer: http://stackoverflow.com/a/48156905
accepted answer: http://stackoverflow.com/a/48156905
tagged with: view
has comment: http://stackoverflow.com/comment/83292450
tagged with: django
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48157213

http://stackoverflow.com/q/48057602
favorite count: 0
has comment: http://stackoverflow.com/comment/83087394
has comment: http://stackoverflow.com/comment/83087430
type: UnansweredQuestion
has body: Is there a way to give a GET route default params in python Flask API? for example: I have this route: GET user?fields=... and I can pass params with fields that I want to get from this model (username, email and etc) and if I don't pass this fields param it will get a default fields for the user that I will define in the route. EDIT:: and is there a way to do it in POST requests
tagged with: python
upvote count: 0
duplicate of: http://stackoverflow.com/q/11041405
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/10434599
has answer: http://stackoverflow.com/a/48057664
has title: default params for flask api routes
score: -1
tagged with: flask
linked to: http://stackoverflow.com/q/11041405
answer count: 1
has comment: http://stackoverflow.com/comment/83087360

http://stackoverflow.com/comment/87119450
type: Comment
type: QuestionComment
has text: Im still having this issue. Any luck on your end?
score: 0
comment on: http://stackoverflow.com/q/48081182

http://stackoverflow.com/comment/83747287
has text: @S.Tim thanks for the feedback. You should probably not have those "linear 2d arrays" to begin with. Are you using the `np.matrix` class? You should use `ndarray`s instead, they're much more convenient. And would it have been possible to compute each iteration in parallel? In that case you could do much better (in terms of performance) than looping, you could compute all the dot products at once.
type: AnswerComment
comment on: http://stackoverflow.com/a/48142633
type: Comment
score: 0

http://stackoverflow.com/a/48048951
answers question: http://stackoverflow.com/q/48047865
has body: Technically, parameters are variables in a function definition and arguments are the actual values given to the variables at the point of call. For example: def foo(arg): return arg foo('Python') The variable arg in the function definition is the parameter and the value Python in the function call is an argument to that parameter. Wikipedia has a nice description: Parameters and arguments
score: 0
type: Answer

http://stackoverflow.com/a/48162787
downvote count: 0
has comment: http://stackoverflow.com/comment/83357741
has body: Check that you have also COOKIES_ENABLED set to True in the settings. As for the second question. You should be able to extract cookies form the headers of Response object with cookies = response.headers.getlist('Set-Cookie') You can now manually insert them into the FormRequest passing them as arguments to from_response method. I think it should be possible to either use cookies parameter of Request object, or directly using headers parameter (headers={'Cookie': xxx}).
upvote count: 2
answers question: http://stackoverflow.com/q/48161575
type: Answer
score: 2

http://stackoverflow.com/comment/83293588
type: QuestionComment
comment on: http://stackoverflow.com/q/48157208
score: 0
has text: the call is non-blocking and it skips to end/next instruction.
type: Comment

http://stackoverflow.com/q/48085771
has comment: http://stackoverflow.com/comment/83147626
linked to: http://stackoverflow.com/q/18369936
tagged with: image
type: Question
answer count: 1
has body: I am just getting started with tkinter widgets and am trying to create Checkbuttons with both images and text labels. Unfortunately, this cannot be done with basic Checkbutton(master=, image=, text=) as setting the image suppresses the text. Here's a silly yet reproducible example of what I'm trying to do. from tkinter import Tk, Frame, Checkbutton, Label from PIL import ImageTk, Image import requests def getImgFromUrl(url): # using solution from : https://stackoverflow.com/a/18369957/2573061 try: r = requests.get(url, stream=True) pilImage = Image.open(r.raw) phoImage = ImageTk.PhotoImage(pilImage) return phoImage except Exception as e: print('Error ' + repr(e) ) return None class AnimalPicker(Frame): def __init__(self): super().__init__() self.initUI() def initUI(self): self.master.title("Animal Picker") def main(): root = Tk() root.geometry("250x450+300+300") app = AnimalPicker() imageUrls = ['http://icons.iconarchive.com/icons/martin-berube/flat-animal/64/dachshund-icon.png', 'http://icons.iconarchive.com/icons/iconka/meow/64/cat-walk-icon.png', 'http://icons.iconarchive.com/icons/sonya/swarm/64/Unicorn-icon.png'] labels = ['Dog','Cat','Unicorn'] images = [getImgFromUrl(x) for x in imageUrls] for i in range(len(images)): cb = Checkbutton(root, text=labels[i], image = images[i]) cb.pack(anchor = 'w', padx=5,pady=5) root.mainloop() if __name__ == '__main__': main() Gives me: But I would like to have the labels "Cat", "Dog", and "Unicorn" either underneath or to the side of the images. It's also important that the solution work for an arbitrary number of Checkbuttons, as in the for loop above. Should I be using Grid and stacking these Checkbuttons next to Labels? I've managed to avoid learning it so far. Or is it easy to do with Pack?
score: 4
favorite count: 0
has title: How to create Checkbuttons with images and text?
has comment: http://stackoverflow.com/comment/83146599
has answer: http://stackoverflow.com/a/48101478
accepted answer: http://stackoverflow.com/a/48101478
has comment: http://stackoverflow.com/comment/83146835
tagged with: python
has comment: http://stackoverflow.com/comment/83146501
tagged with: checkbox
upvote count: 4
tagged with: python-3.x
tagged with: tkinter
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/83327673
type: Comment
type: QuestionComment
score: 0
has text: Incidentally, to reply to someone personally on SO (me, for instance) type the 'at' character to receive a menu of possible recipients.
comment on: http://stackoverflow.com/q/48171974

http://stackoverflow.com/comment/83155036
comment on: http://stackoverflow.com/a/48090241
has text: Um... So if I understand you well, you asked a question you have solved and posted the solution you found as an answer. But what I really want to say, this whole thing is... just a piece of a piece of cake. Anyway, thanks for your contribution.
type: AnswerComment
score: 0
type: Comment

wifi
tag name: wifi
type: Tag
tags question: http://stackoverflow.com/q/48039870
tags question: http://stackoverflow.com/q/48080532

http://stackoverflow.com/q/48098537
has comment: http://stackoverflow.com/comment/83179103
upvote count: 1
answer count: 1
has title: KNeighborsClassifier .fit method returns "ValueError: The truth value of a Series is ambiguous."
favorite count: 0
tagged with: ambiguous
type: UnansweredQuestion
has body: I have read numerous Q&amp;A on the subject title; however, I am having a hard time understanding why the ambiguous truth value error is raised when I use the KNeighborsClassifier .fit method. The code and the data that I have is relatively straightforward: First, I drop all nan values along the row axis from the Opt_Data dataframe and assign the results to the variable titled Training_Data. Training_Data = Opt_Data.dropna(axis=0,how='any') Screenshot of the sample dataset Next, I create two numpy arrays from the Training_Data dataframe. The X_Train array consists of data from Columns 1 - 10 and the Y_Train array consists of data from the Target Column. In the code below, the variable name question is the column name of the Target Column. X_Train = np.array(Training_Data.loc[:,Training_Data.columns != question]) Y_Train = np.array(Training_Data[question]) After creating my arrays, I set up my KNeighborsClassifier function and pass the results to the variable titled knn. The variable opt_neighbors is an integer value (29). When I use the .fit method on knn, I get the aforementioned value error "The truth value of a Series is ambiguous." knn = KNeighborsClassifier(n_neighbors=opt_neighbors,weights='distance',metric='hamming') knn.fit(X_Train,Y_Train) The shape of the actual X_Train array is (1783,10) and the shape of the actual Y_Train array is (1783,). I read a blog that stated duplicate rows could be the cause for this error. However, when I used the drop_duplicates method on the Training_Data dataframe and executed the same code, I received the same error message. I also read that "The or and and python statements require truth-values. For pandas these are considered ambiguous so you should use "bitwise" | (or) or &amp; (and) operations." However, I am not sure how this statement applies as I am not using or or and statements explicitly. I greatly appreciate any help that anyone can offer me. Thank you!
tagged with: python
has answer: http://stackoverflow.com/a/48106482
tagged with: valueerror
has comment: http://stackoverflow.com/comment/83174098
tagged with: knn
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/83178893

http://stackoverflow.com/a/48087561
has comment: http://stackoverflow.com/comment/83175321
score: 0
answers question: http://stackoverflow.com/q/48087452
type: Answer
has body: I have personally never experienced this, however, if this has been happening AS SOON AS you upgraded to the 3.4.6 python shell, the existing scripts may be affecting the .py scripts used to run the python shell. I don't know if this helps but maybe go back to 3.4.3 or download the 3.6.4 version of python. https://www.python.org/downloads/

http://stackoverflow.com/comment/83140015
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48081320
type: QuestionComment
has text: This might be silly but have you tried running your code from a directory which is not a google drive dir?

http://stackoverflow.com/q/48038937
has comment: http://stackoverflow.com/comment/83050957
type: Question
has title: Python requests 'Connection aborted.' if it will started with a cronjob
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/48039206
answer count: 1
favorite count: 0
tagged with: linux
tagged with: python
has comment: http://stackoverflow.com/comment/83048381
upvote count: 2
type: UnansweredQuestion
tagged with: python-requests
has body: If i start my python file normally it works. but if i start it with cron the ('Connection aborted.', gaierror(-2, 'Name or service not known')) error appears on all requests. you can see my cron configuration on my question before. but it shouldn't matter.
downvote count: 1
score: 1

http://stackoverflow.com/q/48059079
has title: 'list' object has no attribute 'split'
has body: I've got this code to retrieve the name of an investment fund starting from the input ISIN code: isin = raw_input("isin of the fund? ") name = c.execute("select name from funds where isin like ?", ('%'+isin+'%',)) s = c.fetchall() Now I need to process the name splitting it and removing certain words: stop_words=['Cap','Ptf', '(EUR)', 'EUR', 'USD', '(D)', 'A', 'B', 'C', 'D', 'I', 'E' ] final_list=[] for i in s[0].split(): if i not in stop_words: final_list.append(i) print(" ".join(final_list)) and what I got as error is: AttributeError: 'list' object has no attribute 'split' I'm a newbie and understand the problem, I just don't understand how to convert my list in a string to split it. Thank you for your help. Edit: grammar
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48059245
has comment: http://stackoverflow.com/comment/83090489
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/48059245
has comment: http://stackoverflow.com/comment/83091035
score: 0
answer count: 1

http://stackoverflow.com/q/48045736
type: Question
has comment: http://stackoverflow.com/comment/83063142
has title: lost my QT5 .ui file, recovery from pyuic5 .py output
score: 0
linked to: http://stackoverflow.com/q/27125110
has body: Is there any way to generate the original .ui file from the qtuic5 .py output? I removed &amp; deleted a branch and later realized it removed the .ui file.
has comment: http://stackoverflow.com/comment/83062710
tagged with: pyqt
has comment: http://stackoverflow.com/comment/83065318
has comment: http://stackoverflow.com/comment/83062816
duplicate of: http://stackoverflow.com/q/27125110
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/3640764
tagged with: python
tagged with: qt
answer count: 0

http://stackoverflow.com/comment/83191007
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48107155
type: QuestionComment
has text: well i apreciate your help, but it did not change a thing. I probably made a stupid error somewhere. I will keep looking. Thanks Again! God bless!

http://stackoverflow.com/q/48026938
tagged with: flask
favorite count: 0
accepted answer: http://stackoverflow.com/a/48062653
has body: In a third-party framework sources response function is wrapped as following: from flask import Response def wrap_func(func): def add_context(*args, **kwargs): output_value = func(*args, **kwargs) return Response( output_value ) return add_context And developer can use this decorator to make a custom function something like an entry point: @wrap_function def hello(): return 'Hello' Framework creates a response and send it, this functionality is hidden "under the hood". And now I need to set some Response parameters such as cookies from my function hello. As it seems to be impossible without the wrapper changes, I decided to contribute to the framework. My very first though was to return an optional value from wrapped function (hello) with response parameters and then parse it inside add_context. Note, that backward compatibility matters, "old-styled" functions should work as well as "new", with response parameters. So, alongside with hello, wrapper would have to support functions like this: @wrap_function def ping(): return 'Hello', {'cookies': [('te', 'st')]} But as for me it's definitely a hack job. Maybe there are some best practices to implement such change or even better approach to modify return of the wrapped function without losing compatibility?
has title: Add a second return value to a wrapped function without losing backward compatibility
has answer: http://stackoverflow.com/a/48062653
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: refactoring
type: Question
downvote count: 0
answer count: 1

cassandra-driver
type: Tag
tag name: cassandra-driver
tags question: http://stackoverflow.com/q/48118092

http://stackoverflow.com/q/48058402
has answer: http://stackoverflow.com/a/48060112
type: Question
linked to: http://stackoverflow.com/q/1832893
tagged with: glyph
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/48060464
accepted answer: http://stackoverflow.com/a/48060464
has title: unicode table information about a character in python
tagged with: unicode
favorite count: 0
has answer: http://stackoverflow.com/a/48058671
has body: Is there a way in python to get the technical information for a given character like it's displayed in the Unicode table? (cf.https://unicode-table.com/en/) Example: for the letter "Ȅ" Name > Latin Capital Letter E with Double Grave Unicode number > U+0204 HTML-code > &#516; Bloc > Latin Extended-B Lowercase > ȅ What I actually need is to get for any Unicode number (like here U+0204) the corresponding name (Latin Capital Letter E with Double Grave) and the lowercase version (here "ȅ"). Roughly: input = a Unicode number output = corresponding information The closest thing I've been able to find is the fontTools library but I can't seem to find any tutorial/documentation on how to use it to do that. Thank you.
has comment: http://stackoverflow.com/comment/83089766
linked to: http://stackoverflow.com/q/243831
tagged with: python
possible better answer: http://stackoverflow.com/a/48060112
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/q/48150321
tagged with: python
possible better answer: http://stackoverflow.com/a/77814580
has body: Title explains it all really. Would like to know how to get the cookies of a QWebEngineProfile as a dictionary of their names and values or in a json format. I am using PyQt5.
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/77814580
tagged with: qtwebengine
tagged with: cookies
tagged with: pyqt5
type: Question
has title: Obtain cookies as dictionary from a QWebEngineProfile
answer count: 2
has answer: http://stackoverflow.com/a/48154459
accepted answer: http://stackoverflow.com/a/48154459
upvote count: 3
favorite count: 0
tagged with: python-3.x
downvote count: 0

http://stackoverflow.com/comment/83031290
type: QuestionComment
has text: Anyways, running your example seems to work fine on my box. What happens if you visit that page from your browser? Do you get the same error? This might be a problem with your network rather than the code
comment on: http://stackoverflow.com/q/48030528
score: 0
type: Comment

http://stackoverflow.com/a/48070306
has body: Below is my rework of your code to get it to just basically play the game -- it still needs work to become a finished program. from turtle import Turtle, Screen FONT = ("Arial", 32, "bold") def k1(): # Enemy Key Commands enemy.backward(10) def k2(): enemy.forward(10) def k3(): # Yertle Key Commands yertle.backward(10) def k4(): yertle.forward(10) def k5(): # enemy shoot bullet.color("red") bullet.goto(enemy.position()) bullet.showturtle() bullet.forward(430) if bullet.distance(runner) &lt; 10: magic_marker.write("Game Over", align="center", font=FONT) bullet.hideturtle() def k6(): # yertle shoot bullet.color("blue") bullet.goto(yertle.position()) bullet.showturtle() bullet.forward(430) if bullet.distance(runner) &lt; 10: magic_marker.write("Game Over", align="center", font=FONT) bullet.hideturtle() def move_runner(): if runner.distance(checkpoint_1) &lt; 5 or runner.distance(checkpoint_2) &lt; 5: runner.left(180) runner.forward(2) screen.ontimer(move_runner, 50) screen = Screen() screen.setup(500, 500) bullet = Turtle("circle", visible=False) # Description For Bullet bullet.speed('normal') bullet.penup() bullet.setheading(90) checkpoint_1 = Turtle("circle", visible=False) # Turtle Description for Checkpoint 1 checkpoint_1.color("red") checkpoint_1.penup() checkpoint_1.goto(-220, 230) checkpoint_2 = checkpoint_1.clone() # Turtle Description for Checkpoint 2 checkpoint_2.goto(220, 230) runner = Turtle("turtle", visible=False) runner.color("orange") runner.speed('fastest') runner.penup() runner.sety(230) yertle = Turtle(shape="turtle", visible=False) # Turtle Description for Player 1 yertle.tiltangle(90) # face one way but move another! yertle.speed('fastest') yertle.penup() yertle.color("blue") yertle.goto(20, -200) enemy = yertle.clone() # Turtle Description for Player 2 enemy.color("red") enemy.goto(-20, -200) checkpoint_1.showturtle() checkpoint_2.showturtle() runner.showturtle() yertle.showturtle() enemy.showturtle() magic_marker = Turtle(visible=False) # for writ…
answers question: http://stackoverflow.com/q/48066703
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/48134752
has body: The point of using IO constructs (StringIO, BytesIO) is to work with objects that mimic a stream (like files). So your first solution is wrapping your bytes in a file-like object and reading from that wrapper as if it was a file. Your second solution just reads from the bytes. I say if the semantics of your code do not require that the bytes be a stream, skip the IO solution go straight to the source.
upvote count: 1
has comment: http://stackoverflow.com/comment/83265360
has comment: http://stackoverflow.com/comment/83265418
answers question: http://stackoverflow.com/q/48134680
type: Answer
has comment: http://stackoverflow.com/comment/83260253
downvote count: 0
score: 1

http://stackoverflow.com/comment/83082569
type: Comment
score: 0
has text: How does `master_list` actually looks like? It could just be a problem of "flattening" a *list of lists*? (converting a list of lists into a list)?
type: QuestionComment
comment on: http://stackoverflow.com/q/48055106

http://stackoverflow.com/comment/83052250
score: 0
has text: See https://stackoverflow.com/a/18241030/407651
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48040118

http://stackoverflow.com/q/48021475
has comment: http://stackoverflow.com/comment/83012313
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48021550
has body: I am experiencing a strange behavior on counting elements in column of sets with pd.Series.str.len() method x = pd.DataFrame({'t': ['', 'A', 'A B', 'A B C']}) x['s'] = x.t.str.split(' ').map(set) x['s_len'] = x.s.str.len() x['s_reduced'] = x.s - {'A'} x['s_reduced_len'] = x.s_reduced.str.len() print(x) t s s_len s_reduced s_reduced_len 0 {} 1 {} 1 1 A {A} 1 {} 0 2 A B {B, A} 2 {B} 1 3 A B C {C, B, A} 3 {C, B} 2 Why in this case the value of x.loc[0, 's_len'] is 1 and the value of x.loc[1, 's_reduced_len'] is 0? Is it a bug and I should report it or is it an odd intended behavior? The version of pandas is 0.20.3.
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83012027
accepted answer: http://stackoverflow.com/a/48021550
has comment: http://stackoverflow.com/comment/83012108
tagged with: pandas
tagged with: python
has title: Strange behavior of str.len() for empty set
has comment: http://stackoverflow.com/comment/83012097

http://stackoverflow.com/a/65401872
type: Answer
answers question: http://stackoverflow.com/q/48139899
has body: To solve the issue " 'numpy.ndarray' object has no attribute 'name'" error at line "ax.annotate(x.name, xy=(0.05, 0.9), xycoords=ax.transAxes, fontweight='bold')" and to keep generality, build an iteration function inside the cor_matrix function and move the annnotate_col function into the cor_matrix function as follow. def corrfunc(x, y, **kws): r, p = stats.pearsonr(x, y) p_stars = '' if p <= 0.05: p_stars = '*' if p <= 0.01: p_stars = '**' if p <= 0.001: p_stars = '***' ax = plt.gca() ax.annotate('r = {:.2f} '.format(r) + p_stars, xy=(0.05, 0.9), ycoords=ax.transAxes) def cor_matrix(df, save=False): # ======= NEW ITERATION FUNCTION ==== label_iter = iter(df).__next__ # ==================================== def annotate_colname(x, **kws): ax = plt.gca() # ===== GHANGE below x.name by label_iter() ====== ax.annotate(label_iter(), xy=(0.05, 0.9), xycoords=ax.transAxes, fontweight='bold') g = sns.PairGrid(df, palette=['red']) # Use normal regplot as `lowess=True` doesn't provide CIs. g.map_upper(sns.regplot, scatter_kws={'s':10}, line_kws={"color": "red"}) g.map_diag(sns.histplot, kde=True) # fix deprecated message g.map_diag(annotate_colname) g.map_lower(sns.kdeplot, cmap='Blues_d') g.map_lower(corrfunc) # Remove axis labels, as they're in the diagonals. for ax in g.axes.flatten(): ax.set_ylabel('') ax.set_xlabel('') if save: plt.savefig('corr_mat.png') return g
score: 0

http://stackoverflow.com/a/50055943
upvote count: 1
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48024654
has body: I have just succeeded with pip install https://github.com/kivy/kivy/archive/master.zip But not with pip install kivy https://kivy.org/docs/installation/installation-osx.html Running OS X, PyCharm 2018.1, pipenv, Python 3.6

http://stackoverflow.com/a/48047309
accepted answer of: http://stackoverflow.com/q/48046864
upvote count: 7
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Notice the prototype of cv2.drawMatches(): cv2.drawMatches(img1, keypoints1, img2, keypoints2, matches1to2, outImg[, matchColor[, singlePointColor[, matchesMask[, flags]]]]) -&gt; outImg So your parameters' order is wrong. From: img3 = cv2.drawMatches(img1,kp1,img2,kp2,None,matches[:10], flags=2) To: img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:10], None,flags=2)
score: 7
answers question: http://stackoverflow.com/q/48046864

http://stackoverflow.com/a/48066851
upvote count: 2
has body: You have to use pyjnius module to call Java code from Python. In your case: from jnius import autoclass res = str(autoclass('android.os.Environment').DIRECTORY_DCIM) I didn't check code.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48065970
downvote count: 0

http://stackoverflow.com/q/48109936
has comment: http://stackoverflow.com/comment/93234078
score: 5
tagged with: pandas
has comment: http://stackoverflow.com/comment/91412826
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83195025
type: UnansweredQuestion
has title: Convert column of a pandas dataframe from string to list type
tagged with: python
has comment: http://stackoverflow.com/comment/93232510
linked to: http://stackoverflow.com/q/23119472
answer count: 0
has comment: http://stackoverflow.com/comment/83195153
type: Question
has body: I've a dataframe 'df' in which one column contains list which is of data type string.I need to convert it into list or bring the list out from string. The following is my dataframe. UId Genres 427256 ['Comedy', 'Drama', 'Science Fiction'] 427259 ['Crime', 'Action', 'Science Fiction'] 427260 ['Animation', 'Family'] 427265 ['Comedy'] 427266 ['Comedy'] 427270 ['Comedy'] 427277 ['Comedy'] type(df.iloc[0]['Genres']) is String.
upvote count: 5
duplicate of: http://stackoverflow.com/q/23119472

http://stackoverflow.com/q/48087788
has comment: http://stackoverflow.com/comment/83150825
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/83292843
has title: Python 3 Pyperclip
favorite count: 0
type: UnansweredQuestion
has body: I am very new to Python and I am going through the "Automate the Boring Stuff with Python" book (https://automatetheboringstuff.com/chapter6/). I am working on the Password Locker project and having difficulties with the pyperclip module. I am running Python 3.6.2 on Mac OS X Yosemite. When I try to run my program through terminal I receive this message: Traceback (most recent call last): File "./pw.py", line 8, in &lt;module&gt; import sys, pyperclip ModuleNotFoundError: No module named 'pyperclip' However, I have already installed pyperclip and receive this message when I try using "pip3 install pyperclip": pip3 install pyperclip Requirement already satisfied: pyperclip in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages and it works fine for me in Shell: &gt;&gt;&gt; import pyperclip &gt;&gt;&gt; pyperclip.copy('hello') &gt;&gt;&gt; pyperclip.paste() 'hello' I believe my program is identical to that in the book aside from the actual passwords: #! /usr/bin/env python3 # pw.py - An insecure password locker program. PASSWORDS = {'email': '12345', 'blog' : '54321', 'luggage': '123456789' } import sys, pyperclip if len(sys.argv) &lt; 2: print('Usage: python pw.py [account] - copy account password') sys.exit() account = sys.argv[1] # first command line arg is the account name if account in PASSWORDS: pyperclip.copy(PASSWORDS[account]) print('Password for ' + account + ' copied to clipboard.') else: print('There is no account named ' + account) I've been trying to find out why this happens, but cannot figure it out. Again, I am very new to Python and any helpful insight would be much appreciated! Thanks!
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/61847036
has comment: http://stackoverflow.com/comment/83150604
has comment: http://stackoverflow.com/comment/83150492
downvote count: 1
type: Question
tagged with: pyperclip
has answer: http://stackoverflow.com/a/48216707
has answer: http://stackoverflow.com/a/48088267

http://stackoverflow.com/q/48050884
has answer: http://stackoverflow.com/a/48050955
has answer: http://stackoverflow.com/a/48051035
favorite count: 0
has body: I have a list of numbers. somelist = [5.000007,5.00099,5.0000075,5.0000075,5.0000075,5.0000099,5.00099,5.0000080,5.0000081,5.00099,5.0000080,5.0000096,5.0000087,5.008,5.00099,5.00000009] I’m using the following to produce a unique list of the 3 lowest values: def lowest_three(somelist): lowest_unique = set(somelist) return nsmallest(3, lowest_unique) It produces the output: [5.00000009, 5.000007, 5.0000075] Now I want a separate function to tell me which of the three lowest values is the most commonly occuring in the original list. So I want it to tell me that 5.0000075 is the most common number from the lowest_three list in the original list (somelist). I’ve tried the following but it’s not working (it’s currently producing an output of 5.00099 which isn’t even in the lowest_three list). def most_common_lowest(somelist): for x in lowest_three(somelist): return max(set(somelist), key=somelist.count) How can achieve this?
has answer: http://stackoverflow.com/a/48051064
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48050941
has comment: http://stackoverflow.com/comment/83074219
has answer: http://stackoverflow.com/a/48050981
has title: Check most common occurrence of a value of one list in a separate list
upvote count: 1
type: Question
answer count: 8
has comment: http://stackoverflow.com/comment/83074060
has answer: http://stackoverflow.com/a/48052485
accepted answer: http://stackoverflow.com/a/48051064
score: 1
has comment: http://stackoverflow.com/comment/83074187
possible better answer: http://stackoverflow.com/a/48050963
has answer: http://stackoverflow.com/a/48050943
has answer: http://stackoverflow.com/a/48050963
downvote count: 0

http://stackoverflow.com/q/48103815
tagged with: coverity
score: 0
type: Question
has comment: http://stackoverflow.com/comment/83189873
has answer: http://stackoverflow.com/a/48105524
linked to: http://stackoverflow.com/q/1732348
tagged with: python-3.3
answer count: 1
tagged with: http://stackoverflow.com/tag/xml
type: UnansweredQuestion
has title: Python Coverity Complexity Print
tagged with: python
has body: I am using Coverity created by Synopsys, consisting primarily of static code analysis and dynamic code analysis tools. I am currently running this against my code and as a result it generates a .xml file. The .xml houses strings of numbers that each of their own meaning. I would like to make a Python33 script to print the seventh number which directly maps to the complexity of a function. I would be fine printing it to the console but as I am a C coder and not only partial in Python here is what I have: Line example of the *.xml: FILE1.C function1;1;12;10;21;8;9;5;1441.75;0.0557199;;;318 FILE2.C function2;0;0;1;11;8;3;1;184.638;0.0175846;;;352 So the 7th number for the first function would be 9 and the second would be 3 So far I have: import fileinput import glob import re import sys #Read in all files in the directory ending in .xml files = glob.glob('*.xml') #search for the line beginning in and ending in pattern = re.compile(r' \s+;([_A-Z]+) \s+$') #this line is wrong realstdout = sys.stdout #create .bak files of the .h files unchanged (backups) for line in fileinput.input(files, inplace=True, backup='.bak'): sys.stdout.write(line) m = pattern.match(line) #print the 7th #; as function + complextity through all .xml lines. if m: sys.stdout.write('\n \%s \n' % m.group(1)) #this line is wrong realstdout.write('%s: %s\n'%(fileinput.filename(),m.group(1))) #this line is wrong Essentially I am just trying to print the 6th number after the function_name; Something like: function1: 9 function2: 3 Any help is appreciated, my python is horrendous.

http://stackoverflow.com/a/48144366
has comment: http://stackoverflow.com/comment/83266866
downvote count: 0
has body: I'd thought it'll be cool to share this. Module called autocorrect. It works by using a Candidate Model, by performing "simple edit" to the word. For example, it processes "deletion->remove a letter", "transposition->swap two adjacent letters", "replacement->change one letter to another", "insertion->add a letter". Therefore, hhhaaappy might not work but hhapy or hhapppy could work. &gt;&gt;&gt; from autocorrect import spell &gt;&gt;&gt; spell('hhhaaappy') 'hhhaaappy' &gt;&gt;&gt; spell('hhapy') 'shapy' &gt;&gt;&gt; spell('happpy') 'happy' &gt;&gt;&gt; spell('hhapppy') 'happy'
accepted answer of: http://stackoverflow.com/q/48144253
answers question: http://stackoverflow.com/q/48144253
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83266884
has comment: http://stackoverflow.com/comment/83266967
type: Answer
has comment: http://stackoverflow.com/comment/83267062
has comment: http://stackoverflow.com/comment/83266938
score: 3
upvote count: 3

http://stackoverflow.com/q/48115671
favorite count: 0
tagged with: sklearn-pandas
has body: I just curious on how how to generate a sequence, batches and or epochs to feed into a tensor flow model, a multi_layer RNN graph from a numpy array. Originally numpy array was generated from pandas dataset and a Sklearn split below. From Numpy to Pandas #define features and labels using X, Y from a numpy array X = Input_Output_Matrix.iloc[:, 0:3].values y = np.around(Input_Output_Matrix.iloc[:, 3], decimals=1).values # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) Note: Very important y_train.shape Out[37]: (6721, 100) X_train.shape Out[38]: (6721, 3) Now the shape of Scaling the features to speed up the model from sklearn.preprocessing import StandardScaler sc = StandardScaler() X = sc.fit_transform(X) res = tf.one_hot(indices=y, depth=100) with tf.Session() as sess: y = sess.run(res) In order to generate the configuration parameters. # Configuration is wrapped in one object for easy tracking and passing. class RNNConfig(): input_size = X_train.shape[1] output_size = y_train.shape[1] num_steps = 100 lstm_size = y_train.shape[0]//100 num_layers = 4 keep_prob = 0.8 batch_size = 100 init_learning_rate = 0.001 learning_rate_decay = 0.99 init_epoch = 5 max_epoch = 5000 DEFAULT_CONFIG = RNNConfig() The input parameters used for the config are actually based on the shape of the numpy array, lets say input_size = 3 for 3 inputs and output_size = 100 derived from the out puts from the one hot encoding i.e depth equals 100. #one hot encoding to generate 10 columns for the labels res = tf.one_hot(indices=y, depth=100) with tf.Session() as sess: y = sess.run(res) with multi_lstm_graph.as_default(): x_data = tf.placeholder(tf.float32, [None, DEFAULT_CONFIG.num_steps, DEFAULT_CONFIG.input_size]) y_label = tf.placeholder(tf.float32, [None, DEFAULT_CONFIG.num_steps, DEFAULT_CONFIG.output_size]) learning_rate = tf.placeholder…
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48116463
tagged with: python
answer count: 1
tagged with: tensorflow
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48116463
has title: How to use numpy array inputs in tensorflow RNN
score: 2
downvote count: 0
type: AnsweredQuestion
tagged with: batch-processing

http://stackoverflow.com/a/48097003
has comment: http://stackoverflow.com/comment/83174966
has comment: http://stackoverflow.com/comment/131479205
score: 21
has comment: http://stackoverflow.com/comment/131501358
accepted answer of: http://stackoverflow.com/q/48096745
has comment: http://stackoverflow.com/comment/131499843
answers question: http://stackoverflow.com/q/48096745
has comment: http://stackoverflow.com/comment/103302998
type: AcceptedAnswer
downvote count: 0
has body: Following the documentation on how to link to an existing database: Using an existing, external database for tests This example shows how you can connect to an existing database and use it for your tests. This example is trivial, you just need to disable all of pytest-django and Django’s test database creation and point to the existing database. This is achieved by simply implementing a no-op django_db_setup fixture. Put this into conftest.py: import pytest @pytest.fixture(scope='session') def django_db_setup(): settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'db.example.com', 'NAME': 'external_db', }
has comment: http://stackoverflow.com/comment/83176225
has comment: http://stackoverflow.com/comment/131491412
has comment: http://stackoverflow.com/comment/131513932
type: Answer
upvote count: 21

http://stackoverflow.com/q/48121539
tagged with: python
has title: How do you use Radon programmatically
score: 2
type: AnsweredQuestion
type: Question
has body: I'm trying to use radon located here: https://radon.readthedocs.io/en/latest/api.html I've done the following from radon.raw import analyze And in the documentation he has written: radon.raw.analyze(source) Where 'source' is the code. I tried putting my file path into the code like so: b = analyze(path_of_file) But that return the result of that path_of_file contained 1 logical line of code which is wrong. I also tried b = radon.raw.analyze(path_of_file) But that results in a red underline on my IED editor. I also tried: import path_of_file And then b = analyze(path_of_file) But that resulted in an attribute error. He also has the following code which might help: from radon.raw import analyze &gt;&gt;&gt; analyze("""def _split_tokens(tokens, token, value): '''Split a list of tokens on the specified token pair (token, value), where *token* is the token type (i.e. its code) and *value* its actual value in the code. But I cannot figure out how to use this. I'm just trying to get the raw function to output some data. Once I get that figured out, I think I can get the rest.
accepted answer: http://stackoverflow.com/a/48121609
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/48121609

http://stackoverflow.com/comment/127193740
type: AnswerComment
has text: This doesn't answer the question. At all.
type: Comment
comment on: http://stackoverflow.com/a/71946454
score: 1

http://stackoverflow.com/a/48015086
has comment: http://stackoverflow.com/comment/82999862
answers question: http://stackoverflow.com/q/48014637
has comment: http://stackoverflow.com/comment/82999561
downvote count: 0
has comment: http://stackoverflow.com/comment/82999425
type: Answer
has body: You can try this .. df1=df.apply(pd.value_counts).stack().swaplevel(0,1).to_frame('n') df1['pct']=df1['n'].div(df1.n.sum(level=0),level=0) df1 Out[89]: n pct year 2012 2.0 0.4 2013 3.0 0.6 grade A 2.0 0.4 B 2.0 0.4 C 1.0 0.2
upvote count: 3
score: 3

http://stackoverflow.com/a/48048773
upvote count: 3
has comment: http://stackoverflow.com/comment/83069298
accepted answer of: http://stackoverflow.com/q/48047684
answers question: http://stackoverflow.com/q/48047684
has comment: http://stackoverflow.com/comment/83069614
has body: Assuming already sorted list groupby assumes that the list is already sorted. The example data satisfy this assumption. You can use enumerate to preserve the original index and modify you key function accordingly: for key, group in groupby(enumerate(totalist), lambda x: x[1][0][0]): print(key) for temp_thing in group: old_index, thing = temp_thing print(' ', old_index, thing) Output: A 0 [('A', 12), ('C', 1)] 1 [('A', 25), ('X', 3)] Z 2 [('Z', 3), ('T', 2)] 3 [('Z', 10), ('M', 8)] 4 [('Z', 8), ('M', 8)] C 5 [('C', 10), ('M', 8)] Assuming an unsorted list This is a modified solution, if you need to sort your list first. Best is to write one function that will be used for the sorting and the grouping: def key_function(x): return x[1][0][0] Now, use this function twice to get consistent sorting and grouping: for key, group in groupby(sorted(enumerate(totalist), key=key_function), key_function): print(key) for temp_thing in group: old_index, thing = temp_thing print(' old index:', old_index) print(' thing:', thing) Output: A old index: 0 thing: [('A', 12), ('C', 1)] old index: 1 thing: [('A', 25), ('X', 3)] C old index: 5 thing: [('C', 10), ('M', 8)] Z old index: 2 thing: [('Z', 3), ('T', 2)] old index: 3 thing: [('Z', 10), ('M', 8)] old index: 4 thing: [('Z', 8), ('M', 8)]
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83069249
has comment: http://stackoverflow.com/comment/83069365
has comment: http://stackoverflow.com/comment/83069348
type: Answer
score: 3

http://stackoverflow.com/a/48213442
has body: Well this is embarrassing actually. I managed to solve it on my own and boy was it a dumb solution. The reason nothing was transmitted to the database was that if some fields were left blank (that were not marked required in the form), they were interpreted as string-fields, which of course would give an error for Integer-fields. The problem was that as you can see in my template code, I did not include the code to show any errors when submitting the fields. I changed my template code to this: {% macro render_field(field) %} &lt;th scope="row"&gt;{{ field.label }} &lt;td&gt; {% if field.errors %} &lt;ul class=errors&gt; {% for error in field.errors %} &lt;li&gt;{{ error }}&lt;/li&gt; {% endfor %} {% endif %} {% endmacro %} &lt;form method="POST"&gt; &lt;table class="table"&gt; {{ form.csrf_token }} {% for name in form %} &lt;tr&gt; {{ render_field(name) }} &lt;/tr&gt; {% endfor %} &lt;/table&gt; &lt;/form&gt; I will now go bow my head in shame and hope that someday this might help someone.
score: 4
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48082951
upvote count: 4
answers question: http://stackoverflow.com/q/48082951
downvote count: 0

http://stackoverflow.com/a/48158846
upvote count: 2
answers question: http://stackoverflow.com/q/48131245
score: 2
downvote count: 0
type: Answer
has body: Have you tried the following? On B, run: bokeh serve filename.py --address 0.0.0.0 You can then access the application from another computer with the URL http://Bs_name_or_ip_address:5006/. If there is a firewall running on the B computer, you have to allow incoming traffic on the port. To override the default port number (5006), use the --port NNNN argument. See also: https://docs.bokeh.org/en/latest/docs/reference/command/subcommands/serve.html

http://stackoverflow.com/comment/83011585
type: Comment
comment on: http://stackoverflow.com/q/48020072
score: 0
type: QuestionComment
has text: Here is a working sample i made with your needs : https://pastebin.com/GPEa6Ai5 Just to unstuck you but this doesn't explain your issue.

http://stackoverflow.com/a/48054202
type: Answer
has comment: http://stackoverflow.com/comment/83080806
answers question: http://stackoverflow.com/q/48051158
score: 1
upvote count: 1
downvote count: 0
has body: I would use an Item Pipeline to deal with the duplicated items. # file: yourproject/pipelines.py from scrapy.exceptions import DropItem class DuplicatesPipeline(object): def __init__(self): self.url_seen = set() def process_item(self, item, spider): if item['url'] in self.url_seen: raise DropItem("Duplicate item found: %s" % item) else: self.url_seen.add(item['url']) return item And add this pipeline to your settings.py # file: yourproject/settings.py ITEM_PIPELINES = { 'your_project.pipelines.DuplicatesPipeline': 300, } Then you just need to run your spider scrapy crawl relpathfinder -o items.csv and the pipeline will Drop duplicate items for you. So will not see any duplicate in your csv output.
has comment: http://stackoverflow.com/comment/84221161

http://stackoverflow.com/comment/83243266
type: Comment
comment on: http://stackoverflow.com/q/48133010
has text: Also, what happens if `names[3]` gets executed?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83130053
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48077849
has text: It would be an excellent opportunity to learn... this is not a complex regex exercise. There could be a performance issue with brute force loops compared to regular expressions when your string gains length, as there is absolutely no optimisation in that.
type: Comment

http://stackoverflow.com/q/48074225
upvote count: 11
has comment: http://stackoverflow.com/comment/83122022
has answer: http://stackoverflow.com/a/68374454
has answer: http://stackoverflow.com/a/61666399
has body: I got an error,ModuleNotFoundError: No module named 'rest_framework' when I run command python manage.py runserver . Traceback says Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x108193ae8&gt; Traceback (most recent call last): File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/xxx/anaconda/envs/env/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Users/xxx/anaconda/envs/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 978, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 961, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' I already run command pip3 install djangorestframework,when I run this command again, Requirement already satisfied: djangorestframework in /u…
favorite count: 0
has answer: http://stackoverflow.com/a/48074409
has answer: http://stackoverflow.com/a/48075516
answer count: 9
tagged with: django
tagged with: python
score: 11
accepted answer: http://stackoverflow.com/a/48074308
linked to: http://stackoverflow.com/q/33308781
has answer: http://stackoverflow.com/a/70544881
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70744127
downvote count: 0
has answer: http://stackoverflow.com/a/48074308
has answer: http://stackoverflow.com/a/50667290
type: Question
possible better answer: http://stackoverflow.com/a/48075516
has answer: http://stackoverflow.com/a/57179466
has title: ModuleNotFoundError: No module named 'rest_framework' I already installed djangorestframework

http://stackoverflow.com/q/48044980
type: Question
tagged with: numpy
tagged with: arrays
downvote count: 0
answer count: 1
has title: Return array of counts for each feature of input
favorite count: 0
accepted answer: http://stackoverflow.com/a/48045026
tagged with: python
has body: I have an array of integer labels and I would like to determine how many of each label is present and store those values in an array of the same size as the input. This can be accomplished with the following loop: def counter(labels): sizes = numpy.zeros(labels.shape) for num in numpy.unique(labels): mask = labels == num sizes[mask] = numpy.count_nonzero(mask) return sizes with input: array = numpy.array([ [0, 1, 2, 3], [0, 1, 1, 3], [3, 1, 3, 1]]) counter() returns: array([[ 2., 5., 1., 4.], [ 2., 5., 5., 4.], [ 4., 5., 4., 5.]]) However, for large arrays, with many unique labels, 60,000 in my case, this takes a considerable amount time. This is the first step in a complex algorithm and I can't afford to spend more than about 30 seconds on this step. Is there a function that already exists that can accomplish this? If not, how can I speed up the existing loop?
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/48045026
has comment: http://stackoverflow.com/comment/83061019

http://stackoverflow.com/a/48171948
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83344602
accepted answer of: http://stackoverflow.com/q/48171626
answers question: http://stackoverflow.com/q/48171626
type: Answer
has comment: http://stackoverflow.com/comment/83347206
has comment: http://stackoverflow.com/comment/83323582
score: 5
has body: You can define a new plot (colored in yellow), which is empty at the beginning. Once you click a point, change the data of this plot to the data of the picked point and redraw the canvas. import matplotlib.pyplot as plt class MyPlot(object): def makePlot(self): self.fig = plt.figure('Test', figsize=(10, 8)) ax = plt.subplot(111) x = range(0, 100, 10) y = (5,)*10 ax.plot(x, y, '-', color='red') ax.plot(x, y, 'o', color='blue', picker=5) self.highlight, = ax.plot([], [], 'o', color='yellow') self.cid = plt.connect('pick_event', self.onPick) plt.show() def onPick(self, event=None): this_point = event.artist x_value = this_point.get_xdata() y_value = this_point.get_ydata() ind = event.ind self.highlight.set_data(x_value[ind][0],y_value[ind][0]) self.fig.canvas.draw_idle() if __name__ == '__main__': app = MyPlot() app.makePlot()
upvote count: 5

http://stackoverflow.com/q/48047731
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83067033
possible better answer: http://stackoverflow.com/a/52108025
has comment: http://stackoverflow.com/comment/83073578
has answer: http://stackoverflow.com/a/52108025
favorite count: 0
has comment: http://stackoverflow.com/comment/83067979
has body: By default in Django 2.0 we get AUTH_PASSWORD_VALIDATORS option with UserAttributeSimilarityValidator MinimumLengthValidator CommonPasswordValidator NumericPasswordValidator So is there any easy way to add extra VALIDATORS like minimum 1 uppercase, 1 symbol, 1 digit, etc. ? In python I can check Using regex import re userPass = 'HelloWorld*123' if re.search('[A-Z]', userPass)!=None and re.search('[0-9]', userPass)!=None and re.search('[^A-Za-z0-9]', userPass)!=None: print 'Strong Password'
accepted answer: http://stackoverflow.com/a/48056105
tagged with: regex
has comment: http://stackoverflow.com/comment/83067388
upvote count: 3
tagged with: django
tagged with: python
has title: Django 2.0 Password Validation
downvote count: 1
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48056105
has comment: http://stackoverflow.com/comment/83067621

http://stackoverflow.com/comment/83284833
comment on: http://stackoverflow.com/q/48146412
score: 0
type: Comment
type: QuestionComment
has text: Yes, I need to do convolution and pooling along the sample-series (4800000) for each track (10).

http://stackoverflow.com/q/48148374
upvote count: 1
has answer: http://stackoverflow.com/a/48148540
type: Question
duplicate of: http://stackoverflow.com/q/42184792
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: h5py
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/42184792
score: 1
has body: I am trying to install h5py and execute sudo pip3 install h5py I also tried to install h5py via wheel from https://pypi.python.org/pypi/h5py/2.7.0rc2 I have python 3.5 installed. And pip3 then crashes with this output: Traceback (most recent call last): File "/usr/local/bin/pip3", line 7, in &lt;module&gt; from pip import main File "/usr/local/lib/python3.5/dist-packages/pip/__init__.py", line 26, in &lt;module&gt; from pip.utils import get_installed_distributions, get_prog File "/usr/local/lib/python3.5/dist-packages/pip/utils/__init__.py", line 27, in &lt;module&gt; from pip._vendor import pkg_resources File "/usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/__init__.py", line 3018, in &lt;module&gt; @_call_aside File "/usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/__init__.py", line 3004, in _call_aside f(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/__init__.py", line 3046, in _initialize_master_working_set dist.activate(replace=False) File "/usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/__init__.py", line 2578, in activate declare_namespace(pkg) File "/usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/__init__.py", line 2152, in declare_namespace _handle_ns(packageName, path_item) File "/usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/__init__.py", line 2092, in _handle_ns _rebuild_mod_path(path, packageName, module) File "/usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/__init__.py", line 2121, in _rebuild_mod_path orig_path.sort(key=position_in_sys_path) AttributeError: '_NamespacePath' object has no attribute 'sort' I'm running on Ubuntu 16.04.3 LTS I don't think pip3 is broken because I installed a lot with pip3 before. What can I do? Thanks a lot.
has title: pip3 crashes when installing h5py
tagged with: pip

http://stackoverflow.com/comment/123072367
type: AnswerComment
has text: @VincentAlex Thanks. I've done some research and I found an API from https://www.peername.org/ extension. But it's not that good, it doesn't support .bazar and sometimes it returns HTTP 403. Are there any better alternatives?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48119442

http://stackoverflow.com/a/48131102
has body: A typical AJAX POST request in Flask looks like this: JavaScript: var xhr = new XMLHttpRequest(); var JSON_sent = {"your": "JSON"}; xhr.open('POST', '/ajax-route'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function (e) { if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) { var JSON_received = JSON.parse(xhr.responseText); //handle received JSON here } else { console.log(xhr.responseText); } }; xhr.send(JSON.stringify(JSON_sent)); Flask: from flask import jsonify, request @app.route('/ajax-route', methods=['POST']) def ajax_route(): try: JSON_sent = request.get_json() print(JSON_sent) # handle your JSON_sent here # Pass JSON_received to the frontend return jsonify(JSON_received) except Exception as e: print("AJAX excepted " + str(e)) return str(e) There are lots of examples using jQuery, but you seem to be using vanilla JS, so that's the answer I provided. https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xv-ajax http://flask.pocoo.org/docs/0.12/patterns/jquery/ EDIT using the code provided now that I understand the intention better: JavaScript: var xhr = new XMLHttpRequest(); xhr.open('POST', '/test'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function (e) { if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) { var jsonobj = JSON.parse(xhr.responseText); //handle received JSON here } else { console.log(xhr.responseText); } }; xhr.send(); Flask: @app.route('/test', methods=['POST']) def test(): try: users = User.query.all() users_schema = UserSchema(many=True) output = users_schema.dump(users).data jsonobj = jsonify(users=output) return jsonobj except Exception as e: print("AJAX excepted " + str(e)) return str(e) Also if you're not sending anything, a GET request instead of POST should be fine.
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83241438
has comment: http://stackoverflow.com/comment/83241684
has comment: http://stackoverflow.com/comment/83241089
has comment: http://stackoverflow.com/comment/83240940
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48126969

http://stackoverflow.com/comment/83310116
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48165133
score: 0
has text: Also there is one issue, whenever i set loggerLevel to INFO i have this log,

http://stackoverflow.com/q/48166814
downvote count: 0
answer count: 7
accepted answer: http://stackoverflow.com/a/48166877
has answer: http://stackoverflow.com/a/48166904
has answer: http://stackoverflow.com/a/48166939
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48166868
has answer: http://stackoverflow.com/a/48166915
type: AnsweredQuestion
has body: I want to find all indexes of "a" item of my string, but it prints only the first one. What is the problem of this program: def str_lookup_reverse(s, c): for index in range(len(s)-1): if s[index] == c: print(index) s = "parisa" str_lookup_reverse(s, "a")
upvote count: 2
has title: searching string to find indexes
has answer: http://stackoverflow.com/a/48166929
has answer: http://stackoverflow.com/a/48166877
type: Question
has answer: http://stackoverflow.com/a/48166963
score: 2
possible better answer: http://stackoverflow.com/a/48166904

http://stackoverflow.com/a/48058242
answers question: http://stackoverflow.com/q/48057922
has body: If you want to get the SQL the first thing you should do is get the QSqlQuery, the QSqlTableModel / QueryModel classes have the query() method that returns that value, then to get the sql used in some query the lastQuery() method is used. In your case: print(self.model.query().lastQuery())
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48057922
type: AcceptedAnswer
downvote count: 0

urllib
tags question: http://stackoverflow.com/q/48132036
tags question: http://stackoverflow.com/q/48068772
type: Tag
tags question: http://stackoverflow.com/q/48090641
tags question: http://stackoverflow.com/q/48081655
tag name: urllib
tags question: http://stackoverflow.com/q/48066225
tags question: http://stackoverflow.com/q/48119844
tags question: http://stackoverflow.com/q/48103647
tags question: http://stackoverflow.com/q/48123538
tags question: http://stackoverflow.com/q/48141097
tags question: http://stackoverflow.com/q/48054123
tags question: http://stackoverflow.com/q/48163472
tags question: http://stackoverflow.com/q/48087918
tags question: http://stackoverflow.com/q/48115455

http://stackoverflow.com/comment/83272951
comment on: http://stackoverflow.com/a/48137085
type: Comment
type: AnswerComment
has text: Ah, that's what I meant, `if main_start_time >= main_end_time: main_start_time -= relativedelta(days=7)`
score: 0

http://stackoverflow.com/comment/83310560
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48165636
score: 0
has text: @Matthias ok got it, no. of spaces (enter) matter in python

http://stackoverflow.com/q/48154729
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83300246
has comment: http://stackoverflow.com/comment/83290591
answer count: 0
type: Question
has title: How to update/remove ffmpeg on Windows 10
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83288609
has comment: http://stackoverflow.com/comment/83288709
tagged with: cmd
has body: I found a python script that had to use ffmpeg via cmd.exe thus I "installed" ffmpeg following these instructions. I downloaded the latest version ffmpeg 3.4.1 but would like to replace it with ver 2.4.x. (I think syntax from the .py file is for ver 2.4.x). I replaced the entire folder with files from the older version zip but when I input ffmpeg -version it still shows version 3.4. I also tried removing path from environment variables,rebooting, and deleting entire ffmpeg folder to no avail. CMD.exe still displays ffmpeg as version 3.4 even when the entire folder is deleted. I was not able to find anything on ffmepg documentation or on google. I know its not exactly programming related but I thought I would get an answer here rather than in video production. Snippet of the code system("./ffmpeg -i xxx.ts -c copy -bsf:a aac_adtstoasc xxx.mp4")
favorite count: 0
tagged with: ffmpeg
upvote count: 2

http://stackoverflow.com/comment/83215534
type: AnswerComment
has text: Ok, so the delta should only reflect the difference between expert/user interaction? For instance, the difference between the users first message and the expert's response?
comment on: http://stackoverflow.com/a/48099961
type: Comment
score: 0

http://stackoverflow.com/comment/83191452
comment on: http://stackoverflow.com/a/48107986
type: AnswerComment
has text: Nice with boundaries. Still need a bit more proper answer for last row. You can make it
score: 0
type: Comment

http://stackoverflow.com/comment/83192100
has text: @jezrael,to answer your question, words for replacement are not always last. they can be anywere
type: AnswerComment
comment on: http://stackoverflow.com/a/48107986
type: Comment
score: 0

http://stackoverflow.com/comment/83273536
score: 0
type: Comment
has text: @MikiBelavista, unfortunately, not all installed packages are compatible with Python3. I had an issue when I was able to install the package but not to run it.
comment on: http://stackoverflow.com/a/48147629
type: AnswerComment

http://stackoverflow.com/q/48135100
has answer: http://stackoverflow.com/a/48136506
score: -2
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83247647
upvote count: 0
tagged with: subplot
answer count: 1
has body: I can create a graph using Jupyter however when I write this code using Python 3.6.4 shell I received the following: `enter code here `File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Users\RJ\AppData\Local\Programs\Python\Python36-32\lib\idlelib\run.py", line 144, in main ret = method(*args, **kwargs) File "C:\Users\RJ\AppData\Local\Programs\Python\Python36-32\lib\idlelib\run.py", line 474, in runcode exec(code, self.locals) File "", line 1, in enter image description here
accepted answer: http://stackoverflow.com/a/48136506
favorite count: 0
has comment: http://stackoverflow.com/comment/83247739
has comment: http://stackoverflow.com/comment/83247653
has title: Trying to Create a Graph
tagged with: python
has comment: http://stackoverflow.com/comment/83247781
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83247537
has comment: http://stackoverflow.com/comment/83248026
has comment: http://stackoverflow.com/comment/83247750
downvote count: 2
has comment: http://stackoverflow.com/comment/83247742
type: Question
tagged with: graph

http://stackoverflow.com/q/48035862
has title: python: pretty print deeply nested braces in string (mastermind game)
has answer: http://stackoverflow.com/a/48036575
type: Question
tagged with: text-parsing
has comment: http://stackoverflow.com/comment/83041706
upvote count: 3
answer count: 1
downvote count: 1
tagged with: nested
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83041666
has body: Here is a long string that is deeply nested... {HHCAA:{00:GGEDB:{00:FFFFF,01:DFDFF:{... Please see this link for the full string >>> mastermind github string This string is in relation to this original question >>> Mastermind Strategy How to pretty print the string so that we can follow through to the end and make it a lookup table... e.g. I want to find the first 00, 01, 02, 03 and so on... Please see some extract below: {HHCAA: {00:GGEDB:{00:FFFFF,01:xxxx...}}}}, 01:DCDCB:{00:EEHFF:xxxx 02:xxxx 03:xxxx The first nested brace printed in column 1, indent it say 5 spaces for the next one, then indent again.. then come back to column 1 again.. and start indenting again, etc. or make it tabular.
score: 2

http://stackoverflow.com/a/48047274
answers question: http://stackoverflow.com/q/48047254
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83066115
has comment: http://stackoverflow.com/comment/83066419
type: Answer
accepted answer of: http://stackoverflow.com/q/48047254
has body: If square is not a square, but is instead a rectangle, then you have two lengths to deal with: (a) The number of rows, i.e. len(square), and (b) The number of columns, i.e. len(square[0]). In your first loop, j runs through the rows, i.e. from 0..3 in your example. But it is being used as a column index, even though the valid column indices only run from 0..2. So instead of checking for j == len(square), instead check if j == len(square[0]).

http://stackoverflow.com/a/48102936
upvote count: 4
answers question: http://stackoverflow.com/q/48101564
type: AcceptedAnswer
has body: Apparently the problem occurs when writing unnormalized 64 bit floating point data. I get an output file that sounds reasonable by either converting x to 16 bit or 32 bit integers, or by normalizing x to the range [-1, 1] and converting to 32 floating point. I'm not using sounddevice; instead, I'm saving the filtered data to a new WAV file and playing that. Here are the variations that worked for me: # Convert to 16 integers wavfile.write('off_plus_noise_filtered.wav', sr, x.astype(np.int16)) or... # Convert to 32 bit integers wavfile.write('off_plus_noise_filtered.wav', sr, x.astype(np.int32)) or... # Convert to normalized 32 bit floating point normalized_x = x / np.abs(x).max() wavfile.write('off_plus_noise_filtered.wav', sr, normalized_x.astype(np.float32)) When outputting integers, you could scale up the values to minimize the loss of precision that results from truncating the floating point values: x16 = (normalized_x * (2**15-1)).astype(np.int16) wavfile.write('off_plus_noise_filtered.wav', sr, x16)
has comment: http://stackoverflow.com/comment/83190464
type: Answer
accepted answer of: http://stackoverflow.com/q/48101564
has comment: http://stackoverflow.com/comment/83182001
has comment: http://stackoverflow.com/comment/83181650
downvote count: 0
score: 4

http://stackoverflow.com/q/48097039
has comment: http://stackoverflow.com/comment/83170878
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: java
has comment: http://stackoverflow.com/comment/83169069
has body: I've got java code to call a python script Java private void visualizeData() { try{ Runtime.getRuntime().exec(“python pyScripts/visualize.py”) } catch (IOException e){ e.printStackTrace(); } } And this is my code for the visualize.py: visualize.py from mpl_toolkits.mplot3d import Axes3D import matplotlib.pylot as plt f = open(“ecoli_data_transformed.txt”,”r”) fig = plt.figure() ax = fig.add_subplot(111, projection=‘3d’) for line in f: (a, b, c) = line.split(“\t”) a = float(a) b = float(b) c = float(c) ax.scatter(a,b,c) ax.setxlabel(‘PCA1’) ax.setylabel(‘PCA2’) ax.setzlabel(‘PCA3’) plt.show() But it doesn't plot the data. If I call the test.py script from the java code (test.py is in the same directory as visualize.py), it works: test.py from mpl_toolkits.mplot3d import Axes3D import matplotlib.pylot as plt import numpy as np np.random.seed(19680801) def randrange(n, min, vmcx): return (vmax - vein)*np.random.rand(n) + vmin fig = plt.figure() ax = fig.add_subplot(111, projection=‘3d’) n = 100 for c, m, slow, high in [(‘r’, ‘o’, -50, -25), (‘b’, ‘^’, -30, -5)]: xs = randrange(n, 23, 32) ys = randrange(n, 0, 100) zs = randrange(n, zlow, zhigh) ax.scatter(xs, ys, zs, c=c, marker=m) ax.set_xlabel(‘X Label’) ax.set_ylabel(‘Y Label’) ax.set_zlabel(‘Z Label’) plt.show() What could be the problem? *NOTE: Calling the visualize.py script from console by 'python visualize.py' works totally fine.
has comment: http://stackoverflow.com/comment/83169697
type: Question
has title: Unable to start python scripts from java code
has comment: http://stackoverflow.com/comment/83171761
upvote count: 2
has comment: http://stackoverflow.com/comment/83169025
answer count: 1
has answer: http://stackoverflow.com/a/48098453
accepted answer: http://stackoverflow.com/a/48098453
favorite count: 0

http://stackoverflow.com/q/48056624
has title: In what condition must define or initial variable in python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48056706
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have a problem in my program. Code as follows: def getHeight(self,root): #Write your code here if not root: return -1 if root.left: i = self.getHeight(root.left) + 1 if root.right: j = self.getHeight(root.right) + 1 return max(i, j) Raises the error: Traceback (most recent call last): File "solution.py", line 37, in height=myTree.getHeight(root) File "solution.py", line 23, in getHeight i = self.getHeight(root.left) + 1 File "solution.py", line 23, in getHeight i = self.getHeight(root.left) + 1 File "solution.py", line 27, in getHeight return max(i, j) UnboundLocalError: local variable 'i' referenced before assignment And if I add i, j = 0, 0, it will work well. And following code: if True: i = 1 + 1 The code work well without initialization. Could someone please explain the difference?
type: Question
has answer: http://stackoverflow.com/a/48056681
accepted answer: http://stackoverflow.com/a/48056706
has answer: http://stackoverflow.com/a/48057077
has comment: http://stackoverflow.com/comment/83085457
possible better answer: http://stackoverflow.com/a/48056681
answer count: 3

http://stackoverflow.com/a/52079369
upvote count: 5
has body: You should install https://github.com/rthalley/dnspython first pip install dnspython
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48055993
score: 5

http://stackoverflow.com/q/48123368
type: AnsweredQuestion
score: 7
has title: Pandas error when using if-else to create new column: The truth value of a Series is ambiguous
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/57709777
linked to: http://stackoverflow.com/q/45493948
has comment: http://stackoverflow.com/comment/136036674
has answer: http://stackoverflow.com/a/48123410
has body: I'm using Pandas and am trying to create a new column using a Python if-else statement (aka ternary condition operator) in order to avoid division by zero. For example below, I want to create a new column C by dividing A/B. I want to use the if-else statement to avoid dividing by 0. import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=list('AB')) df.head() # A B # 0 1 3 # 1 1 2 # 2 0 0 # 3 2 1 # 4 4 2 df['C'] = (df.A / df.B) if df.B &gt; 0.0 else 0.0 However, I am getting an error from the last line: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I searched on StackOverflow and found other posts about this error, but none of them involved this type of if-else statement. Some posts include: Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() The truth value of a Series is ambiguous in dataframe Error: The truth value of a Series is ambiguous - Python pandas Any help would be appreciated.
tagged with: pandas
linked to: http://stackoverflow.com/q/45811610
has answer: http://stackoverflow.com/a/58510181
has answer: http://stackoverflow.com/a/48123599
favorite count: 0
linked to: http://stackoverflow.com/q/36921951
accepted answer: http://stackoverflow.com/a/48123410
has answer: http://stackoverflow.com/a/48123413
upvote count: 8
answer count: 5
duplicate of: http://stackoverflow.com/q/36921951
tagged with: python
possible better answer: http://stackoverflow.com/a/48123413
duplicate of: http://stackoverflow.com/q/26886653

http://stackoverflow.com/q/48086608
score: 0
has comment: http://stackoverflow.com/comment/83148801
has comment: http://stackoverflow.com/comment/83148246
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83149045
has title: Can max be coerced to return only a float
has body: I have a class that has two attributes (index and value). I want to be able to call max and return only the value(which is a float). p = [Point(1, 23.33), Point(2, 12.3)] max(p) #&lt;Point object at 0x1052d4eb8&gt; # I would like to see 23.33 # float(max(p)) returns the float but I want to be able to use the max function by it self Is there a method in the data model that I can override to force max to return just the float? The entire class below. Python 3.6 class Point: """ a set of data indexed by time """ def __init__(self, index, value): self._index = index self._value = value def __float__(self): return float(self._value) def __add__(self, other): return float(self._value) + other def __radd__(self, other): return self.__add__(other) def __lt__(self, other): return self._value &lt; float(other) def ___le__(self, other): return self._value &lt;= float(other) def __eq__(self, other): return self._value == float(other) def __ne__(self, other): return self._value != float(other) def __gt__(self, other): return self._value &gt; float(other) def __ge__(self, other): return self._value &gt;= float(other)
has comment: http://stackoverflow.com/comment/83148257
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/48086899
has comment: http://stackoverflow.com/comment/83148215
has comment: http://stackoverflow.com/comment/83186517

http://stackoverflow.com/q/48161651
answer count: 3
tagged with: urllib3
tagged with: python
has comment: http://stackoverflow.com/comment/83417383
has comment: http://stackoverflow.com/comment/83463541
has comment: http://stackoverflow.com/comment/83408356
type: UnansweredQuestion
has body: I’m getting: 'HTTP/1.1 400 Bad Request\r\n' and I don’t get why. It looks like it authenticates and then there is a redirection and then it now doesn’t work. Why is this happening? I had thought it was the header and that it was missing content type, but even adding that produced the same outcome.. headers = { 'basic_auth': 'brofewfefwefewef:EKAXsWkdt5H6yJEmtexN', 'Content-Type': 'application/json' } client = Client(ClientConfig(), headers=headers, refresh=True) class FileDownloader(object): ...Line 152... def _get_http_pool(self, secure=True): if secure: _http = urllib3.PoolManager(cert_reqs=str('CERT_REQUIRED'), ca_certs=certifi.where()) else: _http = urllib3.PoolManager() if self.headers: content_type = self.headers.get('Content-Type') if 'Content-Type' in self.headers: del self.headers['Content-Type'] _headers = urllib3.util.make_headers(**self.headers) _http.headers.update(_headers) if content_type: _http.headers['content-type'] = content_type print(_http.headers) return _http https://github.com/JMSwag/PyUpdater/blob/master/pyupdater/client/downloader.py Line 366, is where the download itself starts. This is perplexing to say the least. Error: DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.bitbucket.org send: b'GET /2.0/repositories/Anexampleuser/repo/downloads/keys.gz HTTP/1.1\r\nHost: api.bitbucket.org\r\nAccept-Encoding: identity\r\nauthorization: Basic YnJvZmV3ZmVmd2VmZXdlZjpFS0FYc1drZHQ1SDZ5SkVtdGV4Tg==\r\n\r\n' reply: 'HTTP/1.1 302 Found\r\n' DEBUG:urllib3.connectionpool:https://api.bitbucket.org:443 "GET/2.0/repositories/Anexampleuser/repo/downloads/keys.gz HTTP/1.1" 302 0 DEBUG:urllib3.util.retry:Incremented Retry for (url='https://api.bitbucket.org/2.0/repositories/Anexampleuser/repo/downloads/keys.gz'): Retry(total=2, connect=None, read=None, redirect=None, status=None) INFO:urllib3.poolmanager:Redirecting https://api.bitbucket.org/2.0/repositories/Anexampleuser/repo/downloads/keys.gz -&gt; https://bbuseruploads.s3.amazonaws.com/a…
score: 1
has answer: http://stackoverflow.com/a/48167019
has answer: http://stackoverflow.com/a/48263718
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83414658
downvote count: 1
favorite count: 0
has title: Dealing with Bad request
has answer: http://stackoverflow.com/a/48263074

http://stackoverflow.com/a/48157732
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48155106
type: Answer
has body: You can try something like this: sorted_ar = [None,10, 10, 12, 12, 12, 15, 25] track={} for i,j in enumerate(sorted_ar): if j not in track: track[j]=[(i,1)] else: track[j].append((i,1)) final_={} for i,j in track.items(): if i not in final_: final_[i]=(sum(list(map(lambda x:x[0],j))),sum(list(map(lambda x:x[1],j)))) print(final_) output: {None: (0, 1), 10: (3, 2), 15: (6, 1), 12: (12, 3), 25: (7, 1)}
answers question: http://stackoverflow.com/q/48155106
score: 0

http://stackoverflow.com/comment/83316738
type: Comment
score: 0
type: AnswerComment
has text: Great.Thank you! and as Keyur Potdar mentionned my return True statement was misplaced.
comment on: http://stackoverflow.com/a/48168533

http://stackoverflow.com/comment/83057667
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48043359
score: 1
has text: You are using `()` on an object that can't be called. Please provide [a Minimal, Complete and Verifiable example](https://stackoverflow.com/help/mcve) for more help.

http://stackoverflow.com/comment/83187763
comment on: http://stackoverflow.com/q/48105967
type: Comment
has text: In python 2 you should be using `raw_input`, not `input`
score: 0
type: QuestionComment

http://stackoverflow.com/q/48017496
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: python
has title: getting null for PythonInterpreter.get() when using Jython
tagged with: java
has comment: http://stackoverflow.com/comment/83006810
type: Question
tagged with: jython
has body: I'm using Jython to try to call a certain method in my Python file. I'm getting error message like this [ERROR] - Ambiguous method overloading for methodorg.python.util.PythonInterpreter#exec. Cannot resolve which method to invoke for [null] due to overlapping prototypes between: [class java.lang.String] [class org.python.core.PyObject] Here's my Java code static def visitPage(){ PySystemState sys = Py.getSystemState(); sys.path.append(new PyString(*The path to certain package*)); PythonInterpreter interpreter = new PythonInterpreter(null, sys); interpreter.execfile(*Here's the path to the python file*); PyObject waitPage = interpreter.get("wait"); println waitPage.toString(); interpreter.exec(waitPage); } The print result gives me null. So I think my problem is not able to get the method. Here's my Python code. I'm getting access to a method that is inherited by LoginPage class, from Page Object class. class LoginPage(PageObject): So I'm wondering if there is another way I can use Jython's Python Interpreter?
has comment: http://stackoverflow.com/comment/83156972
tagged with: pythoninterpreter

http://stackoverflow.com/a/68461131
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48027558
has body: Below is a simple approach which worked for me when none of the other answers did. First make sure you are selecting the div with the "scrollbar" element. scrolling_element= find_element_by_xpath(scrolling_element_xpath) driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', scrolling_element)
upvote count: 1
type: Answer

http://stackoverflow.com/a/48065478
has comment: http://stackoverflow.com/comment/83104989
answers question: http://stackoverflow.com/q/48065403
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83105085
has comment: http://stackoverflow.com/comment/83104751
has comment: http://stackoverflow.com/comment/83104291
type: Answer
has comment: http://stackoverflow.com/comment/83104507
has comment: http://stackoverflow.com/comment/83104360
has comment: http://stackoverflow.com/comment/83104538
has body: Yes. We can first construct a numpy array that contains L0, L1 and L2: A = np.array([L0, L1, L2]) Next we construct a numpy array of S: B = np.array(S) now we have for C = A[B] (or C = np.take(A,B,axis=0) as suggested by @Divakar): &gt;&gt;&gt; C = np.take(A,B,axis=0) &gt;&gt;&gt; C array([[[[b, 0], [b, b]], [[b, b], [b, 1]], [[b, b], [2, b]]], [[[b, b], [2, b]], [[b, 0], [b, b]], [[b, b], [b, 1]]]]) This is of course not exactly what we intended: we want to obtain a 2D-array. We can do this by first transposing (or swapaxes, like @PaulPanzer suggests) and then reshaping, we obtain: &gt;&gt;&gt; C.transpose(0,2,1,3).reshape(4,6) array([[b, 0, b, b, b, b], [b, b, b, 1, 2, b], [b, b, b, 0, b, b], [2, b, b, b, b, 1]]) Since 4 and 6 of course depend on the size of the dimensions of L0, L1, L2 and S, we can also calculate them based on that size: A = np.array([L0, L1, L2]) B = np.array(S) m, n = B.shape _, u, v = A.shape np.take(A,B,axis=0).swapaxes(1,2).reshape(u*m, v*n) Like @DSM says, from Numpy-1.13, there is np.block function for this purpose, and we can write it as: &gt;&gt;&gt; np.block([[A[i] for i in row] for row in S]) array([[b, 0, b, b, b, b], [b, b, b, 1, 2, b], [b, b, b, 0, b, b], [2, b, b, b, b, 1]])
upvote count: 5
accepted answer of: http://stackoverflow.com/q/48065403
has comment: http://stackoverflow.com/comment/83105514

ignore-case
type: Tag
tags question: http://stackoverflow.com/q/48105991
tag name: ignore-case

http://stackoverflow.com/a/48159806
answers question: http://stackoverflow.com/q/48159774
type: Answer
score: 2
downvote count: 0
upvote count: 2
has body: Every element of your array is a valid JSON so you could do import json Y = [json.loads(l) for l in L]

http://stackoverflow.com/comment/84785371
has text: I disagree. It works (now) even in a function in an external module or in a lambda function. If it doesn't work then it depends on other details and it is the same directly in the cell. (or can you confirm the difference now?)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48286813
score: 0

http://stackoverflow.com/comment/83250209
score: 1
type: AnswerComment
has text: i think `to_pickle` is a better option here
comment on: http://stackoverflow.com/a/48135997
type: Comment

http://stackoverflow.com/q/48103693
downvote count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83183141
has body: I am reading a songs file in csv format and I do not know what I am doing wrong. import csv import os import random file = open("songs.csv", "rU") reader = csv.reader(file) for song in reader: print(song[0], song[1], song[2]) file.close() This is the error: Traceback (most recent call last): File "/Users/kuku/Desktop/hey/mine/test.py", line 10, in &lt;module&gt; for song in reader: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 414: ordinal not in range(128)
tagged with: python
has answer: http://stackoverflow.com/a/48104079
upvote count: 0
type: Question
has answer: http://stackoverflow.com/a/49867802
has comment: http://stackoverflow.com/comment/83182870
has answer: http://stackoverflow.com/a/48103865
score: -1
has title: return codecs.ascii_decode(input, self.errors)[0]
answer count: 3

http://stackoverflow.com/q/48085579
type: Question
tagged with: apply
score: 0
answer count: 2
has body: I have the pandas df below, with a few columns, one of which is ip_addresses df.head() my_id someother_id created_at ip_address state 308074 309115 2859690 2014-09-26 22:55:20 67.000.000.000 rejected 308757 309798 2859690 2014-09-30 04:16:56 173.000.000.000 approved 309576 310619 2859690 2014-10-02 20:13:12 173.000.000.000 approved 310347 311390 2859690 2014-10-05 04:16:01 173.000.000.000 approved 311784 312827 2859690 2014-10-10 06:38:39 69.000.000.000 approved For each ip_address I'm trying to return the description, city, country I wrote a function below and tried to apply it from ipwhois import IPWhois def returnIP(ip) : obj = IPWhois(str(ip)) result = obj.lookup_whois() description = result["nets"][len(result["nets"]) - 1 ]["description"] city = result["nets"][len(result["nets"]) - 1 ]["city"] country = result["nets"][len(result["nets"]) - 1 ]["country"] return [description, city, country] # --- suspect['ipwhois'] = suspect['ip_address'].apply(returnIP) My problem is that this returns a list, I want three separate columns. Any help is greatly appreciated. I'm new to Pandas/Python so if there's a better way to write the function and use Pandas would be very helpful.
tagged with: pandas
has title: pandas dataframe apply function over column creating multiple columns
has answer: http://stackoverflow.com/a/48097382
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48085619

http://stackoverflow.com/comment/83266854
comment on: http://stackoverflow.com/q/48143955
score: 0
type: QuestionComment
type: Comment
has text: Does the project use a virtual environment? It will need to be activated before the script runs (and the shebang should then simply be `#!/usr/bin/env python` to defer the selection of the precise interpreter instance to the virtual environment). A common arrangement is to find an activation script with `ls */bin/activate` (it could be hidden; maybe try `ls .[!.]*/bin/activate` too?) though different arrangements are possible. If you find one, `source` it and try again. (There will be a command `deactivate` to exit; this command might not exist outside the virtualenv.)

http://stackoverflow.com/q/48105997
tagged with: data-science
has body: This is my dataframe https://drive.google.com/file/d/1qAnyOkp_YayqzZ4i0CwqCTDiYTIOmv6I/view?usp=sharing I need to find the value of ra, last column of that dataset via the ANN I have used keras library to make that, here is my code https://gist.github.com/anonymous/9955247ad7341e5bc119556dead9fc71 But the y_pred variable has set of 0s in output. Am I doing anything wrong with activation function? I need to predict the ra values with training dataset P.S: I am a newbie to datascience and just I have started learning it via udemy
score: 0
answer count: 1
tagged with: keras
type: UnansweredQuestion
tagged with: python
has title: How to determine activation, loss, optimizer in keras while making artificial neural network
has answer: http://stackoverflow.com/a/48108148
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/48137510
favorite count: 0
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/83323728
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48140210
has title: passing args and kwargs to parent class with extra content in django CreateView
tagged with: forms
upvote count: 10
downvote count: 1
score: 9
type: Question
has answer: http://stackoverflow.com/a/48187136
answer count: 2
has body: I've made a django form in which I want to pass some context I need to display (mainly database entries in tags so the user can choose from them). I therefor made a get_context_data function where I add the context to the existing context like this: def get_context_data(self, **kwargs): context = super(UploadView, self).get_context_data(**kwargs) context['categories'] = Category.objects.all() context['form'] = VideoForm return context however, the form is not saving the information passed to the database. Why would that not work? Here is part of my code! forms.py: class VideoForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label=None) class Meta: model = Video fields = [ 'title', 'description', 'description_short', 'category', 'time', 'thumbnail', 'type', ] def clean_thumbnail(self): picture = self.cleaned_data.get("thumbnail") if not picture: raise forms.ValidationError("No Image") else: w, h = get_image_dimensions(picture) if w/h != (16/9): raise forms.ValidationError("Image in wrong aspect ratio (should be 16:9)") return picture upload.html (it's pretty long so it's better to upload it to Pastebin) views.py: class UploadView(LoginRequiredMixin, CreateView): form_class = VideoForm template_name= 'upload.html' def form_valid(self, form): instance = form.save(commit=False) instance.uploader=self.request.user return super(UploadView, self).form_valid(form) def get_context_data(self, **kwargs): context = super(UploadView, self).get_context_data(**kwargs) context['categories'] = Category.objects.all() context['form'] = VideoForm return context I'm using a custom form so I can set classes which I use for editing the CSS (instead of just using form.as_p and having a really ugly from there...) EDIT: After a bit more testing I found that if I put print(instance) inside the def form_valid(self, form): function it would not print out anything, suggesting the instance is empty. How can this be? Also, I tried removing: context['fo…
linked to: http://stackoverflow.com/q/23803255

http://stackoverflow.com/a/48110239
downvote count: 0
answers question: http://stackoverflow.com/q/48109259
type: Answer
has body: multiprocessing.Lock is not used for blocking, it's used to protect one or more resources from concurrent access. The simplest of the examples could be a file written by multiple processes. To guarantee that only one process at a time is writing on the given file, you protect it with a Lock. There are situations where your logic cannot block. For example, if your logic is orchestrated by an event loop like the asyncio module, blocking would stop the entire execution until the Lock is released. In such cases the common approach is trying to acquire the Lock. If you succeed, you proceed accessing the protected resource, otherwise you move to other routines and try later.
score: 3
upvote count: 3

http://stackoverflow.com/q/48060041
has comment: http://stackoverflow.com/comment/83903251
has body: I am going over tensorflow tutrial for RNN of drawings: https://www.tensorflow.org/versions/master/tutorials/recurrent_quickdraw But I stuck to executing the command: train_model.py \ --training_data=rnn_tutorial_data/training.tfrecord-00000-of-00010 \ --eval_data=rnn_tutorial_data/eval.tfrecord-00000-of-00010 \ --classes_file=rnn_tutorial_data/training.tfrecord.classes Tensorflow throws: model_dir should be non-empty and It still happens after I add: --model_dir=modeldir
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/55198628
score: 1
has comment: http://stackoverflow.com/comment/83216645
upvote count: 1
tagged with: recurrent-neural-network
has comment: http://stackoverflow.com/comment/83093491
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/48501625
has comment: http://stackoverflow.com/comment/83093002
tagged with: quickdraw
answer count: 2
has title: Tensorflow throw "model_dir should be non-empty"
downvote count: 0

http://stackoverflow.com/a/48114387
answers question: http://stackoverflow.com/q/48114098
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83280633
type: Answer
has body: Currently, your spider yields a single item: {'title': u' '} which does not have the date and time fields filled out. This is because of the way you initialize the ItemLoader class in your spider. You should be initializing your item loader with a specific selector in mind. Replace: for div in divs: l = KikaItemLoader(item=ShowItem(), response=response) with: for div in divs: l = KikaItemLoader(item=ShowItem(), selector=div)
has comment: http://stackoverflow.com/comment/83256007
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48114098
has comment: http://stackoverflow.com/comment/83252392
upvote count: 2

http://stackoverflow.com/q/48093693
tagged with: pandas
has comment: http://stackoverflow.com/comment/83162139
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83162774
has comment: http://stackoverflow.com/comment/83161914
tagged with: python
tagged with: timestamp
has comment: http://stackoverflow.com/comment/83162109
type: Question
has body: I have a variable of the type pandas._libs.tslib.Timestamp type(dd_end) pandas._libs.tslib.Timestamp the variable contains : pnl 2008-11-26 daily_returns_itub4 2008-10-24 dtype: datetime64[ns] How do i slice it to get the Timestamp that refers to daily_returns_itub4 ?
score: 0
has title: Python (pandas._libs.tslib.Timestamp) - Returning Values

http://stackoverflow.com/comment/83242217
score: 0
type: Comment
type: QuestionComment
has text: `find_peaks_cwt` is for 1-D array. If you want to find local peaks in your 2-D spectrogram, please read this: https://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array
comment on: http://stackoverflow.com/q/48128995

http://stackoverflow.com/comment/83062296
type: Comment
type: QuestionComment
score: 0
has text: Yup that's along the right lines... You can just re-use the existing listings such as listings.filter(beds=beds, bathrooms=bathrooms) if you wanted though.
comment on: http://stackoverflow.com/q/48045438

cross-validation
tags question: http://stackoverflow.com/q/48159755
tag name: cross-validation
type: Tag

http://stackoverflow.com/comment/99582724
type: AnswerComment
type: Comment
has text: what is so special on Point Grey FLIR cameras?
comment on: http://stackoverflow.com/a/56496750
score: 0

http://stackoverflow.com/q/48095713
tagged with: python
score: 18
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48106287
tagged with: flask-restful
has comment: http://stackoverflow.com/comment/83166151
type: Question
has title: Accepting multiple parameters in flask-restful add_resource()
accepted answer: http://stackoverflow.com/a/48106287
tagged with: flask
upvote count: 18
has comment: http://stackoverflow.com/comment/83166271
answer count: 1
downvote count: 0
favorite count: 0
has body: I want to handle a GET request in my Flask REST API. The request will include multiple parameters, and you can expect this to be a typical GET request: https://localhost:5000/item/analysis=true&amp;class=A&amp;class=B Thus, a GET request consists of: a Boolean variable called "analysis" a list called "class" I want to accept this inside an add_resource() as follows: add_resource(Item, '/item/&lt;whatever-comes-here&gt;') I am clueless about how I would accept multiple parameters (one of them being a list) inside the add_resource(). How do I accept them in the add_resource() function and how do I unpack them inside the get() function? I have spent time reverse engineering this, but I have not yet been successful. Am I doing something wrong? (I understand that there might be a better way to send lists with a REST API GET request, so I'd appreciate any pointers regarding that!) Sincere thanks in advance!

http://stackoverflow.com/comment/83061748
type: Comment
has text: @heemayl : correct, thanks! it is more efficient. Added it to the answer too
comment on: http://stackoverflow.com/a/48045278
type: AnswerComment
score: 0

http://stackoverflow.com/q/48051368
has title: Selenium WebDriver -- Can't get into an iframe with dynamic ID
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/83076176
type: Question
has answer: http://stackoverflow.com/a/48056289
has comment: http://stackoverflow.com/comment/83074831
has comment: http://stackoverflow.com/comment/83076878
has comment: http://stackoverflow.com/comment/83076780
linked to: http://stackoverflow.com/q/15785920
has body: Using Selenium, I try to reach an element inside an iframe. Here is the HTML code: Here is my Python code to get into the iframe: time.sleep(3) driver.switch_to_frame(driver.find_element_by_id("DWT54_content_ifr")) I also tried these codes: driver.switch_to_frame("DWT54_content_ifr") and driver.switch_to_frame(driver.find_element_by_xpath("//iframe[@id='DWT54_content_ifr']")) But each time I get the same error: "Unable to locate element". UPDATE: I managed to get into the iframe using this line of code: driver.switch_to_frame(3) But this is not very convenient as I have to count manually the number of iframe in the page... Any help, please? Thanks.
tagged with: http://stackoverflow.com/tag/html
answer count: 1
accepted answer: http://stackoverflow.com/a/48056289
favorite count: 0
upvote count: 2
tagged with: iframe
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/83075739

http://stackoverflow.com/comment/83047184
comment on: http://stackoverflow.com/a/48038390
type: Comment
has text: Thx i can see it now . I will try alone to emit stop signal
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83098905
score: 0
type: QuestionComment
type: Comment
has text: and for those of you who can code in tradesignals pine editor, that's the pine code for it: Up=hl2-(Factor*atr(ATR)) Dn=hl2+(Factor*atr(ATR)) TUp=close[1]>TUp[1]? max(Up,TUp[1]) : Up TDown=close[1]<TDown[1]? min(Dn,TDown[1]) : Dn Trend = close > TDown[1] ? 1: close< TUp[1]? -1: nz(Trend[1],1) Tsl = Trend==1? TUp: TDown
comment on: http://stackoverflow.com/q/48062788

http://stackoverflow.com/comment/83030427
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48030083
score: 1
has text: I need to know ur OS. Then I can help you find your $PATH

http://stackoverflow.com/q/48039870
score: 0
has comment: http://stackoverflow.com/comment/83050417
has comment: http://stackoverflow.com/comment/83050440
has comment: http://stackoverflow.com/comment/83050566
has comment: http://stackoverflow.com/comment/83050279
has comment: http://stackoverflow.com/comment/83050167
tagged with: python
has comment: http://stackoverflow.com/comment/83050482
has comment: http://stackoverflow.com/comment/83050453
has comment: http://stackoverflow.com/comment/83050403
answer count: 0
has comment: http://stackoverflow.com/comment/83050485
has comment: http://stackoverflow.com/comment/83050561
type: UnansweredQuestion
has body: I'm sure there is a super easy answer to this question, but i'm new to python, and am having trouble finding resources on the internet that are specific enough to my problem. I'm trying to run a program that searches for wifi networks, and then outputs what it finds. from wifi import Cell, Scheme Cell.all('wlan0') In the terminal I have already downloaded the packages wifi and cell. Thank you in advance for any help given. EDIT: The error message as follows, Traceback (most recent call last): File "Search Wifi", line 1, in from wifi import Cell, Scheme ImportError: No module named 'wifi'
has comment: http://stackoverflow.com/comment/83050505
type: Question
has comment: http://stackoverflow.com/comment/83050418
has comment: http://stackoverflow.com/comment/83050465
has comment: http://stackoverflow.com/comment/83050441
has comment: http://stackoverflow.com/comment/83050525
has comment: http://stackoverflow.com/comment/83050265
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/83050551
has title: Python Wifi Search Not Working
tagged with: wifi
has comment: http://stackoverflow.com/comment/83050454
has comment: http://stackoverflow.com/comment/83050288

http://stackoverflow.com/comment/83247345
type: AnswerComment
has text: It set NaNs by boolean mask.
score: 0
comment on: http://stackoverflow.com/a/48135008
type: Comment

word2vec
tags question: http://stackoverflow.com/q/48137617
tags question: http://stackoverflow.com/q/48089141
tags question: http://stackoverflow.com/q/48038568
tags question: http://stackoverflow.com/q/48082018
tags question: http://stackoverflow.com/q/48073718
tags question: http://stackoverflow.com/q/48044670
tags question: http://stackoverflow.com/q/48019843
tags question: http://stackoverflow.com/q/48062662
tags question: http://stackoverflow.com/q/48140848
type: Tag
tag name: word2vec

http://stackoverflow.com/q/48072007
downvote count: 0
has body: I know something similar to this question has been asked many times over already, but all answers given to similar questions only seem to work for arrays with 2 dimensions. My understanding of np.argsort() is that np.sort(array) == array[np.argsort(array)] should be True. I have found out that this is indeed correct if np.ndim(array) == 2, but it gives different results if np.ndim(array) &gt; 2. Example: &gt;&gt;&gt; array = np.array([[[ 0.81774634, 0.62078744], [ 0.43912609, 0.29718462]], [[ 0.1266578 , 0.82282054], [ 0.98180375, 0.79134389]]]) &gt;&gt;&gt; np.sort(array) array([[[ 0.62078744, 0.81774634], [ 0.29718462, 0.43912609]], [[ 0.1266578 , 0.82282054], [ 0.79134389, 0.98180375]]]) &gt;&gt;&gt; array.argsort() array([[[1, 0], [1, 0]], [[0, 1], [1, 0]]]) &gt;&gt;&gt; array[array.argsort()] array([[[[[ 0.1266578 , 0.82282054], [ 0.98180375, 0.79134389]], [[ 0.81774634, 0.62078744], [ 0.43912609, 0.29718462]]], [[[ 0.1266578 , 0.82282054], [ 0.98180375, 0.79134389]], [[ 0.81774634, 0.62078744], [ 0.43912609, 0.29718462]]]], [[[[ 0.81774634, 0.62078744], [ 0.43912609, 0.29718462]], [[ 0.1266578 , 0.82282054], [ 0.98180375, 0.79134389]]], [[[ 0.1266578 , 0.82282054], [ 0.98180375, 0.79134389]], [[ 0.81774634, 0.62078744], [ 0.43912609, 0.29718462]]]]]) So, can anybody explain to me how exactly np.argsort() can be used as the indices to obtain the sorted array? The only way I can come up with is: args = np.argsort(array) array_sort = np.zeros_like(array) for i in range(array.shape[0]): for j in range(array.shape[1]): array_sort[i, j] = array[i, j, args[i, j]] which is extremely tedious and cannot be generalized for any given number of dimensions.
type: Question
possible better answer: http://stackoverflow.com/a/48072631
linked to: http://stackoverflow.com/q/33140674
has answer: http://stackoverflow.com/a/48072631
tagged with: sorting
score: 15
tagged with: numpy
answer count: 3
has answer: http://stackoverflow.com/a/48072491
tagged with: arrays
accepted answer: http://stackoverflow.com/a/48072551
favorite count: 0
tagged with: python
has title: How to use numpy.argsort() as indices in more than 2 dimensions?
upvote count: 15
has answer: http://stackoverflow.com/a/48072551
type: AnsweredQuestion

http://stackoverflow.com/a/71271500
answers question: http://stackoverflow.com/q/48145966
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/135851110
upvote count: 3
has comment: http://stackoverflow.com/comment/125982711
has body: The library OData library used in the question doesn't exist anymore. Anyone wondering how to work with OData in Python can check this out: python-pyodata Using this library you can make a request like this: import requests import pyodata SERVICE_URL = 'http://services.odata.org/V2/Northwind/Northwind.svc/' # Create instance of OData client client = pyodata.Client(SERVICE_URL, requests.Session()) You can checkout the documentation to see how to use it: https://github.com/SAP/python-pyodata/blob/master/docs/usage/README.md
score: 3
has comment: http://stackoverflow.com/comment/135828973

http://stackoverflow.com/comment/83302870
type: Comment
type: QuestionComment
score: 0
has text: Yes each license plate consists of 8 characters. I used LSTM for the network to use the information of previous prediction for new prediction, for example if it splits a character wrong it can used previous character information to predict this one. Am I wrong?
comment on: http://stackoverflow.com/q/48145150

http://stackoverflow.com/q/48070296
tagged with: python-asyncio
has body: I am trying to create a simple monitoring system that periodically checks things and logs them. Here is a cutdown example of the logic I am attempting to use but I keep getting a RuntimeWarning: coroutine 'foo' was never awaited error. How should I reschedule an async method from itself? Code in test.py: import asyncio from datetime import datetime async def collect_data(): await asyncio.sleep(1) return {"some_data": 1,} async def foo(loop): results = await collect_data() # Log the results print("{}: {}".format(datetime.now(), results)) # schedule to run again in X seconds loop.call_later(5, foo, loop) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.create_task(foo(loop)) loop.run_forever() loop.close() Error: pi@raspberrypi [0] $ python test.py 2018-01-03 01:59:22.924871: {'some_data': 1} /usr/lib/python3.5/asyncio/events.py:126: RuntimeWarning: coroutine 'foo' was never awaited self._callback(*self._args)
has title: Python asyncio recursion with call_later
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/37512182
accepted answer: http://stackoverflow.com/a/48076507
type: Question
tagged with: recursion
score: 8
has comment: http://stackoverflow.com/comment/83114512
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/37278647
has answer: http://stackoverflow.com/a/48076507
upvote count: 8

http://stackoverflow.com/q/48067515
has title: Travis environment variable (Python)
type: Question
score: 0
has body: I have set up "ENVIRONMENT" as an environment variable in the Travis console, but when Travis runs, it still can't access the variable in Python. Any idea? File "/home/travis/build/.../config/env.py", line 12, in set builtins.environment = os.environ['ENVIRONMENT'] File "/home/travis/virtualenv/python3.6.3/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'ENVIRONMENT'
answer count: 1
tagged with: travis-ci
has answer: http://stackoverflow.com/a/48067559
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83108498

http://stackoverflow.com/a/48116662
has comment: http://stackoverflow.com/comment/83210132
upvote count: 1
has comment: http://stackoverflow.com/comment/83210463
accepted answer of: http://stackoverflow.com/q/48112466
answers question: http://stackoverflow.com/q/48112466
has comment: http://stackoverflow.com/comment/83211203
has body: The issue is with your adaption of: for row in cursor.fetchall(): print row This will print all the rows returned by fetchall(), one by one. You tried to adapt this into a function returning all rows: def get_statistics(): cursor = finDB.execute_sql('CALL Allstatistics;') for row in cursor.fetchall(): return row Now this will return the first row only, as the return statement terminates your loop on first iteration. What you really want is something like this: def get_statistics(): cursor = finDB.execute_sql('CALL Allstatistics;') return cursor.fetchall() This will correctly return all rows in the cursor, or None if there are no result rows. With checking if there is a non-empty result, and instead of None returning an empty list, you could do it this way: def get_statistics(): cursor = finDB.execute_sql('CALL Allstatistics;') rows = cursor.fetchall() if rows: return rows return [] Regarding cursor.fetchone(), this will return the next available row of the cursor, or None if no more rows are available. For example, you can iterate over all available rows in your cursor like this: rows = [] row = cursor.fetchone() # fetch first row, or None if empty result while row is not None: rows.append(row) row = cursor.fetchone() # fetch the next row, if None loop terminates return rows # return all collected results For your use-case, it might be interesting to construct a more convenient data structure for your result, e.g. a list of dicts: rows = [] row = cursor.fetchone() while row is not None: rows.append({'foo': row[0], 'bar': row[1], 'baz': row[2]}) row = cursor.fetchone() return rows Note that this can be similarly achieved like this: rows = [] for row in cursor.fetchall(): rows.append({'foo': row[0], 'bar': row[1], 'baz': row[2]}) return rows You can then write in your template, looping for row in rows: foo is {{row['foo']}} and bar is {{row['bar']}} Or you could construct a list of namedtuple, allowing you to write in template: foo is {{row.foo}} and bar is {{foo.bar}…
has comment: http://stackoverflow.com/comment/83211101
has comment: http://stackoverflow.com/comment/83211303
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83211118
has comment: http://stackoverflow.com/comment/83210408
type: Answer
has comment: http://stackoverflow.com/comment/83210278
score: 1

http://stackoverflow.com/q/48056297
tagged with: apache2.4
tagged with: flask
has body: Im tring to host flask on apache2.4(ubuntu 16) using wsgi and but im facing 500 error in browser: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at root@51.255.213.181 to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Apache/2.4.25 (Ubuntu) Server at 51.255.213.181 Port 80 when i run tail -f /var/log/apache2/error.log: [Tue Jan 02 05:27:28.444613 2018] [wsgi:error] [pid 3308:tid 139686857123584] [client 209.95.51.167:53868] Traceback (most recent call last): [Tue Jan 02 05:27:28.444688 2018] [wsgi:error] [pid 3308:tid 139686857123584] [client 209.95.51.167:53868] File "/var/www/TW96/tw96.wsgi", line 4, in [Tue Jan 02 05:27:28.444703 2018] [wsgi:error] [pid 3308:tid 139686857123584] [client 209.95.51.167:53868] from index import app as application [Tue Jan 02 05:27:28.444717 2018] [wsgi:error] [pid 3308:tid 139686857123584] [client 209.95.51.167:53868] File "/var/www/TW96/tw96/index.py", line 32, in [Tue Jan 02 05:27:28.444740 2018] [wsgi:error] [pid 3308:tid 139686857123584] [client 209.95.51.167:53868] app.run(port=80,debug=True) [Tue Jan 02 05:27:28.444755 2018] [wsgi:error] [pid 3308:tid 139686857123584] [client 209.95.51.167:53868] File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 841, in run [Tue Jan 02 05:27:28.444766 2018] [wsgi:error] [pid 3308:tid 139686857123584] [client 209.95.51.167:53868] run_simple(host, port, self, **options) [Tue Jan 02 05:27:28.444789 2018] [wsgi:error] [pid 3308:tid 139686857123584] [client 209.95.51.167:53868] File "/usr/local/lib/python3.5/dist-packages/werkzeug/serving.py", line 780, in run_simple [Tue Jan 02 05:27:28.444799 2018] [wsgi:error] [pid 3308:tid 139686857123584] [client 209.95.51.167:53868] s.bind((hostname, port)) [Tue Jan 02 05:27:28.444825 2018] [wsgi:error] …
has answer: http://stackoverflow.com/a/48056411
has answer: http://stackoverflow.com/a/73744226
tagged with: linux
has title: permission denied in apache configuration : [Errno 13] Permission denied
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/73744226
favorite count: 0
type: Question
upvote count: 2
answer count: 2
accepted answer: http://stackoverflow.com/a/48056411
tagged with: python
downvote count: 1
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/83086096

http://stackoverflow.com/q/48050064
linked to: http://stackoverflow.com/q/40586031
has answer: http://stackoverflow.com/a/49956105
type: Question
tagged with: tcsh
score: 3
tagged with: remote-debugging
tagged with: ssh
tagged with: python
has title: Received "/: Event not found." when using PyCharm remote dubugger
has answer: http://stackoverflow.com/a/48395571
tagged with: pycharm
upvote count: 3
answer count: 2
has body: When I use PyCharm with remote debug through ssh to a tcsh shell server, many times its stops working, and displays "/: Event not found" More specifically, I encounter the following in pycharm debug console. ssh://username@hostserver:22/path/to/bin/python -u /path/to/.pycharm_helpers/pydev/pydevd.py --cmd-line --multiproc --qt-support=auto --client '0.0.0.0' --port 40426 --file /path/to/python/file/main.py /: Event not found. Is the problem owing to history substitution in tcsh shell? Because I can get the same response when typing !/. I find some similar questions like Issue with pycharm remote debug (“/: Event not found.” ) and Event not found, but no useful answer. Sometimes this problem disappears automatically, which is weird.
type: UnansweredQuestion
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/83286056
has text: I wrote the code in sublime text3 and ran it on the server, but the errors always show on the screen. So I totally have no idea. Anyway, thank you all the same.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48143416
type: Comment

http://stackoverflow.com/comment/83068906
type: AnswerComment
has text: @StefanPochmann hashing of the keys makes a difference here. With string keys, the hashing is more expensive, so `defaultdict` wins.
type: Comment
comment on: http://stackoverflow.com/a/48046368
score: 0

http://stackoverflow.com/a/48044035
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83061820
type: Answer
has body: If you want to modify binding during the instantiation, I do not know if it's the best option, but you can use a custom property. This will also allow you to unbind when you want: import kivy from kivy.app import App from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout kivy.require('1.10.0') Builder.load_string (""" &lt;Slider&gt; size_hint: 1, None height: dp(40) &lt;DoubleSlider@BoxLayout&gt;: tied: False # &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; slider_1: slider_1 slider_2: slider_2 orientation: 'vertical' Slider id: slider_1 Slider id: slider_2 value: slider_1.value if root.tied else self.value &lt;UI&gt;: orientation: 'vertical' BoxLayout: Label: text: "Tied" CheckBox: on_active: ds.tied = not ds.tied DoubleSlider: id: ds """) class UI(BoxLayout): pass class MyApp(App): def build(self): return UI() if __name__ == '__main__': MyApp().run() Edit: Another option is to create a new property associated with the value property of the slider and use the on_ syntax: import kivy from kivy.app import App from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout kivy.require('1.10.0') Builder.load_string (""" &lt;Slider&gt; size_hint: 1, None height: dp(40) &lt;DoubleSlider@BoxLayout&gt;: slider_1: slider_1 slider_2: slider_2 value1: slider_1.value value2: slider_2.value orientation: 'vertical' Slider id: slider_1 Slider id: slider_2 &lt;UI&gt;: orientation: 'vertical' DoubleSlider: on_value1: self.slider_2.value = self.value1 """) class UI(BoxLayout): pass class MyApp(App): def build(self): return UI() if __name__ == '__main__': MyApp().run()
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48042935
has comment: http://stackoverflow.com/comment/83062562
answers question: http://stackoverflow.com/q/48042935

http://stackoverflow.com/a/48027391
has comment: http://stackoverflow.com/comment/83025067
has comment: http://stackoverflow.com/comment/83025086
upvote count: 4
has body: Option 1 Sounds like you can use np.where for this - i = df.var1 == 'A' j = df.var3 == 'A' df['var5'] = np.where(i, df.var2, np.where(j, df.var4, np.NaN)) df var1 var2 var3 var4 var5 0 A 23 B 7 23.0 1 B 13 C 4 NaN 2 C 12 A 11 11.0 3 A 5 C 15 5.0 Option 2 An alternative would be np.select - df['var5'] = np.select([i, j], [df.var2, df.var4], default=np.nan) df var1 var2 var3 var4 var5 0 A 23 B 7 23.0 1 B 13 C 4 NaN 2 C 12 A 11 11.0 3 A 5 C 15 5.0 Note, i and j are the same variables defined in the code listing for Option 1. Option 3 pd.Series.mask/where df.var2.mask(~i, df.var4.mask(~j, np.nan)) 0 23.0 1 NaN 2 11.0 3 5.0 Name: var2, dtype: float64
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/48027171
answers question: http://stackoverflow.com/q/48027171
type: Answer

http://stackoverflow.com/a/48105403
type: Answer
has body: I think this usecase/situation is described on their (django-allauth) documentation. You can check it here. Basically you need to create a custom adapter class (that inherits from allauth.account.adapter.DefaultAccountAdapter or allauth.socialaccount.adapter.DefaultSocialAccountAdapter, depending on the case) with that functionality and them point to it using the ACCOUNT_ADAPTER variable in the settings.
score: 0
has comment: http://stackoverflow.com/comment/83192142
answers question: http://stackoverflow.com/q/48103810

http://stackoverflow.com/comment/83056056
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48034096
has text: @furas thank you. Could this be a twitter feature issue? If so where do I raise the issue, if you have an idea?
score: 0

deep-learning
tags question: http://stackoverflow.com/q/48033044
tags question: http://stackoverflow.com/q/48139621
tags question: http://stackoverflow.com/q/48119212
tags question: http://stackoverflow.com/q/48055704
tags question: http://stackoverflow.com/q/48121763
tags question: http://stackoverflow.com/q/48098951
tags question: http://stackoverflow.com/q/48039925
tags question: http://stackoverflow.com/q/48034205
tags question: http://stackoverflow.com/q/48125575
tags question: http://stackoverflow.com/q/48054531
tags question: http://stackoverflow.com/q/48040054
tags question: http://stackoverflow.com/q/48057841
tags question: http://stackoverflow.com/q/48027263
tags question: http://stackoverflow.com/q/48074705
tags question: http://stackoverflow.com/q/48068306
tags question: http://stackoverflow.com/q/48126924
tags question: http://stackoverflow.com/q/48129804
tags question: http://stackoverflow.com/q/48158454
tags question: http://stackoverflow.com/q/48042951
tags question: http://stackoverflow.com/q/48070378
tags question: http://stackoverflow.com/q/48114820
tags question: http://stackoverflow.com/q/48169791
tags question: http://stackoverflow.com/q/48041468
tags question: http://stackoverflow.com/q/48145420
tags question: http://stackoverflow.com/q/48160602
tags question: http://stackoverflow.com/q/48020440
tags question: http://stackoverflow.com/q/48140989
tags question: http://stackoverflow.com/q/48033451
tags question: http://stackoverflow.com/q/48143905
tags question: http://stackoverflow.com/q/48067824
tags question: http://stackoverflow.com/q/48136804
tags question: http://stackoverflow.com/q/48044595
type: Tag
tags question: http://stackoverflow.com/q/48129527
tags question: http://stackoverflow.com/q/48141841
tags question: http://stackoverflow.com/q/48100954
tags question: http://stackoverflow.com/q/48119910
tags question: http://stackoverflow.com/q/48143587
tags question: http://stackoverflow.com/q/48114258
tags question: http://stackoverflow.com/q/48132807
tags question: http://stackoverflow.com/q/48137219
tags question: http://stackoverflow.com/q/48161549
tag name: deep-learning
tags question: http://stackoverflow.com/q/48101576
tags question: http://stackoverflow.com/q/48144747
tags question: http://stackoverflow.com/q/48019798
tags question: http://stackoverflow.com/q/48141267
tags question: http://stackoverflow.com/q/48073274
tags question: http://stackoverflow.com/q/48101886

http://stackoverflow.com/q/48088038
type: AnsweredQuestion
score: 1
has body: I changed some sources to be real time object detection in the object_detection_tutorial provided by the tensorflow object detection API. However, the following error occurred. What is the solution? The code that caused the problem is shown below. import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image import cv2 cap = cv2.VideoCapture(1) if tf.__version__ &lt; '1.4.0': raise ImportError('Please upgrade your tensorflow installation to v1.4.* or later!') # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # ## Object detection imports # Here are the imports from the object detection module. from utils import label_map_util from utils import visualization_utils as vis_util # # Model preparation # ## Variables # # Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file. # # By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies. # What model to download. MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17' MODEL_FILE = MODEL_NAME + '.tar.gz' DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/' # Path to frozen detection graph. This is the actual model that is used for the object detection. PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb' # List of the strings that is used to add correct label for each box. PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt') NUM_CLASSES = 90 # ## Download Model opener = urllib.request.URLopener() opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE) tar_file…
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84122268
has comment: http://stackoverflow.com/comment/89772271
accepted answer: http://stackoverflow.com/a/51507138
tagged with: python
has title: tensorflow object detection API Error at windows
downvote count: 0
has answer: http://stackoverflow.com/a/51507138
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/48067036
tagged with: python
has body: I am running the following &gt;&gt;&gt; datetime.datetime.strptime("Jan 1 2017", "%b %d %Y").replace(tzinfo=timezone("US/Central")).strftime("%Y-%m-%dT%H:%M:%S%z") '2017-01-01T00:00:00-0551' I would expect this to be at an offset of -0600, but it seems to be off by 9 minutes. Why is this timezone wrong and how do I get it to correct?
answer count: 0
duplicate of: http://stackoverflow.com/q/11473721
type: Question
has comment: http://stackoverflow.com/comment/83107660
score: 0
has comment: http://stackoverflow.com/comment/83107465
has comment: http://stackoverflow.com/comment/83107669
has comment: http://stackoverflow.com/comment/83107551
has title: PYZT Timezones Are Incorrect
tagged with: timezone
type: UnansweredQuestion
tagged with: datetime

http://stackoverflow.com/a/48086177
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/48086131
score: 6
has body: You're only validating lines that have ONLY one number, so a line with two numbers will be skipped because of if len(working_list) != 1: continue, that basically says "if there isn't EXACTLY one number on this line then skip", you may have meant something like if len(working_list) &lt; 1: continue
accepted answer of: http://stackoverflow.com/q/48086131
has comment: http://stackoverflow.com/comment/83147280

http://stackoverflow.com/comment/83239593
score: 0
type: Comment
has text: If I want to get vector of int16 then I need to use round(bsc) ?
type: AnswerComment
comment on: http://stackoverflow.com/a/48131234

http://stackoverflow.com/comment/83078555
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48049922
has text: Update: I figured out how to animate the nice image that I got with the `caption` command, avoiding all this impossibly complicated typograhical problems using `draw.text`. I used MoviePy which you can find here: https://zulko.github.io/moviepy/ Now I don't know how to put the question answered or even if I can with only this comment

reindex
tag name: reindex
tags question: http://stackoverflow.com/q/48148328
type: Tag

http://stackoverflow.com/comment/83003724
type: QuestionComment
has text: `np.where((...))` Are the double parentheses intentional?
score: 3
comment on: http://stackoverflow.com/q/48017236
type: Comment

http://stackoverflow.com/comment/83150664
has text: @asheets thanks for clarifying (and helping). The counter should only update on a Sunday to Monday transition
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48087700

http://stackoverflow.com/comment/83138079
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48079362
has text: No need to compute the distance matrix, what if i have some row having the min value, and I want only one row as an answer

swift-package-manager
tag name: swift-package-manager
type: Tag
tags question: http://stackoverflow.com/q/48167999

http://stackoverflow.com/q/48083401
has body: I have a python variable (I am using pyspark) of date datatype: The variable value is 2016-10-31 print type(load_dt) &gt;&gt; &lt;type 'datetime.date'&gt; I am having difficulty passing this to a sparksql query: hive_context.sql("select * from tbl t1 where cast (substring(t1.dt,1,10) as date) ={0}".format(load_dt)); Error: u"cannot resolve '(cast(substring(dt,1,10) as date) = ((2016 - 10) - 31))' due to data type mismatch: differing types in '(cast(substring(period_dt,1,10) as date) = ((2016 - 10) - 31))' (date and int)
tagged with: sql
has answer: http://stackoverflow.com/a/48083416
accepted answer: http://stackoverflow.com/a/48083416
answer count: 1
downvote count: 0
favorite count: 0
tagged with: apache-spark
has title: Cannot pass variables to a spark sql query in pyspark
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
score: 1
tagged with: pyspark

http://stackoverflow.com/comment/83240396
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48131371
type: QuestionComment
has text: Trying to better optimize a post from Divakar will be hard to do :).

http://stackoverflow.com/q/48152870
tagged with: dictionary
tagged with: operand
has comment: http://stackoverflow.com/comment/83285266
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83284411
has comment: http://stackoverflow.com/comment/83285134
has comment: http://stackoverflow.com/comment/83293974
has answer: http://stackoverflow.com/a/48168914
has body: The problem is that while running this code everything is fine: d={'9h':9, 'Qd':10} l=['9h', 'Qd', 'test', 'test2'] s=0 for i in range(len(l)): if l[i] in d: s += d.get(l[i]) print s But while doing it with classes I got the error "unsupported operand type(s) for +=: 'int' and 'NoneType'" Here is my class implementation: def __init__(self, plr_cur_value, plr_result_score): self.plr_cur_value = plr_cur_value self.plr_result_score = plr_result_score def deck_adjust(self): for i in range(len(self.plr_cur_value)): if self.plr_cur_value[i] in self.d: self.plr_result_score + = self.d.get(plr_cur_value[i]) return self.plr_result_score
type: Question
has comment: http://stackoverflow.com/comment/83284864
score: 0
tagged with: types
answer count: 1
has title: While dealing with Dictionary elements in Python faced unsupported operand type(s) for +=: 'int' and 'NoneType'
has comment: http://stackoverflow.com/comment/83285023
tagged with: python

filter
tags question: http://stackoverflow.com/q/48066677
tags question: http://stackoverflow.com/q/48101564
tag name: filter
tags question: http://stackoverflow.com/q/48152584
tags question: http://stackoverflow.com/q/48020296
tags question: http://stackoverflow.com/q/48166581
tags question: http://stackoverflow.com/q/48077120
type: Tag
tags question: http://stackoverflow.com/q/48084789

http://stackoverflow.com/q/48112695
answer count: 1
has comment: http://stackoverflow.com/comment/83201052
tagged with: args
tagged with: python
linked to: http://stackoverflow.com/q/10666163
favorite count: 0
has comment: http://stackoverflow.com/comment/83200958
has comment: http://stackoverflow.com/comment/83201170
has title: python logical operator with variable number of arguments
upvote count: 2
score: 0
downvote count: 2
has body: is there a way in python to check the logical operator AND with variable number of arguments. for example: def and_function(a,b,c,d,e....): if a and b and c and d and c and d and e and . and . is True: return True i see that this is possible using *args function and using a counter. But wish to know if there is a better way of doing it.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83200880
has answer: http://stackoverflow.com/a/48112835
linked to: http://stackoverflow.com/q/19389490
linked to: http://stackoverflow.com/q/15112125
type: Question
accepted answer: http://stackoverflow.com/a/48112835
duplicate of: http://stackoverflow.com/q/19389490

http://stackoverflow.com/comment/83282529
has text: Alternatively, you could use the [soundfile](https://github.com/bastibe/SoundFile) module, which does most of the conversions for you. You'd only have to scale the range from `+-1.414` down to `+-1.0` before saving it to a 16-bit file.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48144381
type: QuestionComment

http://stackoverflow.com/comment/83302923
score: 0
type: QuestionComment
type: Comment
has text: To be clear, there is, in no way, an optimization that actually goes and pre-fetches files and reads them or anything of that nature... Python is very much 'what you see is what you get' -- Very few optimizations are performed for you.
comment on: http://stackoverflow.com/q/48161562

http://stackoverflow.com/a/66916589
type: Answer
has body: Documentation for sys.maxsize: An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform. python3 The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have. python2 What is Py_ssize_t? It is an index type (number type for indexing things, like lists). It is the signed version of size_t (from the C language). We don't use a normal number/ int, because this is unbounded in Python. In Python, we don't use size_t because we want to support negative indexing, in Python we can do my_list[-4:]. So Py_ssize_t provides negative and positive numbers between a range. The _t stands for type, to inform developers that size_t is a type name, not a variable. Just a convention. So what is the effect of having a limit on Py_ssize_t? Why does this limit list, strings, dict size? There is no way to index a list with an element larger than this. The list cannot get bigger than this, because it won't accept a non Py_ssize_t. In the dictionary case, Py_ssize_t is used as the hash. Python doesn't use linked lists in its dictionary implementation, it uses Open Addressing/ probing, where if a collision is found, we a systematic way of getting another place to find the key and put the value. So you can't have more than Py_ssize_t in a dictionary in Python. In all practical cases (64 bit machines aka. probably you), you will run out of memory before you max out Py_ssize_t. Trying dict.fromkeys(range(sys.maxsize + 5)) never got there, it just slowed my computer down.
downvote count: 0
score: 10
answers question: http://stackoverflow.com/q/48138632
upvote count: 10

http://stackoverflow.com/comment/83066380
comment on: http://stackoverflow.com/q/48040545
has text: Can you post your models and the main query?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48153353
has body: What's unclear about the docs? func : callable f(x, *args) Function to be optimized. args can be passed as an optional item in the dict minimizer_kwargs ... See also minimize The local minimization function called once for each basinhopping step. minimizer_kwargs is passed to this routine. So it's somewhat like: minimizer_kwargs = {"args": (a, b)} ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs)
answers question: http://stackoverflow.com/q/48153251
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48153251

http://stackoverflow.com/comment/83310586
has text: A big plus !!! @jezrael , you just made my day forever as I can apply this now in some economic models. Fantastic!!
score: 0
comment on: http://stackoverflow.com/a/48165739
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48134525
type: UnansweredQuestion
has body: I'm quite new to image processing. I am using opencv with python. I am familiar with the normal way of finding contours, but in this case I want to neglect each square as a contour but want to contour over each said shape as shown. After thresholding currently I am getting contour of each square. Is there any easy function in the opencv library to detect these entire big shapes than the small squares.
has answer: http://stackoverflow.com/a/48134829
upvote count: 1
tagged with: python
tagged with: opencv
score: 1
tagged with: image-processing
has title: How to detect larger contours which consists of smaller contours?
has comment: http://stackoverflow.com/comment/83246476
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83246420
tagged with: contour
favorite count: 0

http://stackoverflow.com/a/48030234
score: 0
type: Answer
has body: Try this: def getDatafromDB(self): sql = """Select Query from table""" self.cursor.execute(sql) data=self.cursor.fetchall() while data: print(data) if self.cursor.nextset(): sql = "{call "+data+"(?)}" params = (3,) cursor = connection.cursor() rows = cursor.execute(sql, params).fetchall() print(rows) else: data= None
answers question: http://stackoverflow.com/q/48028823

http://stackoverflow.com/q/48118508
tagged with: list
accepted answer: http://stackoverflow.com/a/48118704
score: 0
has title: How to change certain elements in multidimensional list via function - Python 3-x
upvote count: 1
has comment: http://stackoverflow.com/comment/83213739
downvote count: 1
has comment: http://stackoverflow.com/comment/83213589
type: Question
tagged with: recursion
has comment: http://stackoverflow.com/comment/83213783
has comment: http://stackoverflow.com/comment/83213475
has comment: http://stackoverflow.com/comment/83214009
has body: i've been spending some time on this, but i'm still learning and haven't managed to do it. Well partialy i did, but i don't want the entering variable to be changed. def changeit(element, value1, value2): if type(element) == list: for index, element2 in enumerate(element): if element2 == value1: element[index] = value2 if type(element2) == list: changeit(element2, value1, value2) if value1 not in element: return element def changelist(inputlist, value1, value2): for index, element in enumerate(inputlist): if type(element) == list: changeit(element, value1, value2) if element == value1: inputlist[index] = value2 return inputlist So the function should replace all value1 for value2. The desired output would be: &gt;&gt;&gt; k = [[[7]], 8] &gt;&gt;&gt; print(changelist(k, 7, 'a')) ['a', 8] &gt;&gt;&gt; k [[[7]], 8] but so far i'm getting: &gt;&gt;&gt; k = [[[7]], 8] &gt;&gt;&gt; print(changelist((k,7,"x")) ['x', 8] &gt;&gt;&gt; k ['x', 8] And i just can't find a way how to not change the entering list. Thanks!
linked to: http://stackoverflow.com/q/17246693
tagged with: function
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83213662
has answer: http://stackoverflow.com/a/48118704
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/117406898
type: AnswerComment
score: 0
type: Comment
has text: Thanks man, I changed mine to python3.9 and now it works like a charm. You don't know the many times I changed the interpreter to py3.9 and banged my keyboard in frustration. FRIGGIN code runner. There are like 5 python installations on my pc lol.
comment on: http://stackoverflow.com/a/55620146

http://stackoverflow.com/q/48152069
type: Question
has comment: http://stackoverflow.com/comment/83282618
accepted answer: http://stackoverflow.com/a/48152246
has comment: http://stackoverflow.com/comment/83284585
has comment: http://stackoverflow.com/comment/83283533
has comment: http://stackoverflow.com/comment/83284505
tagged with: execution
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83282656
tagged with: cmd
has comment: http://stackoverflow.com/comment/83283877
score: -6
favorite count: 0
has answer: http://stackoverflow.com/a/48152246
has comment: http://stackoverflow.com/comment/83285108
has comment: http://stackoverflow.com/comment/83282637
has comment: http://stackoverflow.com/comment/83282619
tagged with: python
has comment: http://stackoverflow.com/comment/83283283
downvote count: 6
has comment: http://stackoverflow.com/comment/83283735
type: AnsweredQuestion
has body: I have an example of Python script script.py, which is supposed to take a binary file and convert it to another binary file. In the example, the call is as follows: dir1/file1 -D python dir2/file2 &gt; script.py I thought it will take file2 from dir2, convert and output is as file1 in dir but it is not the case. When I run this script (I ensured the dir2/file2 exists) nothing happens. Inside the script.py I have the code: def main(): if len(sys.argv) &lt;2: print &gt;&gt;sys.stderr sys.exit(1) try: convert(sys.argv[1]) except: return1 So I assume that the main work is done by some other function convert. What puzzles me is the cmd call for this script. How to interpret this call? Is this normal way of calling python functions? Edit after comments: Thanks for explanation, the file1 is a binary and it exists on the system. Originally I thought it was created by the script by someone who already did it. From what you say it looks that it is some kind of executable which calls python in the background. (By the way it is interesting how people downgrade the question if they don't know the answer)
has title: what is meaning of this python call

http://stackoverflow.com/a/48099772
has body: Here is an O(N^d (log N)^d) fft-based approach. The idea is to chop up both operands into strides-spaced grids at all offsets modulo strides, do the conventional fft convolution between grids of corresponding offsets and then pointwise sum the results. It is a bit index-heavy but I'm afraid that can't be helped: import numpy as np from numpy.fft import fftn, ifftn def strided_conv_2d(x, y, strides): s, t = strides # consensus dtype cdt = (x[0, 0, ...] + y[0, 0, ...]).dtype xi, xj = x.shape yi, yj = y.shape # round up modulo strides xk, xl, yk, yl = map(lambda a, b: -a//b * -b, (xi,xj,yi,yj), (s,t,s,t)) # zero pad to avoid circular convolution xp, yp = (np.zeros((xk+yk, xl+yl), dtype=cdt) for i in range(2)) xp[:xi, :xj] = x yp[:yi, :yj] = y # fold out strides xp = xp.reshape((xk+yk)//s, s, (xl+yl)//t, t) yp = yp.reshape((xk+yk)//s, s, (xl+yl)//t, t) # do conventional fft convolution xf = fftn(xp, axes=(0, 2)) yf = fftn(yp, axes=(0, 2)) result = ifftn(xf * yf.conj(), axes=(0, 2)).sum(axis=(1, 3)) # restore dtype if cdt in (int, np.int_, np.int64, np.int32): result = result.real.round() return result.astype(cdt) arr = np.array([[2,3,7,4,6,2,9], [6,6,9,8,7,4,3], [3,4,8,3,8,9,7], [7,8,3,6,6,3,4], [4,2,1,8,3,4,6], [3,2,4,1,9,8,3], [0,1,3,9,2,1,4]]) arr2 = np.array([[3,4,4], [1,0,2], [-1,0,3]]) print(strided_conv_2d(arr, arr2, (2, 2))) Result: [[ 91 100 88 23 0 29] [ 69 91 117 19 0 38] [ 44 72 74 17 0 22] [ 16 53 26 12 0 0] [ 0 0 0 0 0 0] [ 19 11 21 -9 0 6]]
type: Answer
has comment: http://stackoverflow.com/comment/83174714
has comment: http://stackoverflow.com/comment/83176739
answers question: http://stackoverflow.com/q/48097941
score: 4
has comment: http://stackoverflow.com/comment/83174932
upvote count: 4
has comment: http://stackoverflow.com/comment/83174630
downvote count: 0

http://stackoverflow.com/q/48032574
has body: I'm trying to learn webscraping and when running a script using the run command on Windows, it shows an error in cmd: Traceback (most recent call last): File "c:\users\user\MyPythonScripts\k.py", line 1, in &lt;module&gt; import bs4, requests ModuleNotFoundError: No module named 'bs4' It only happens using the run command, the script fine on the PyCharm IDE though.
answer count: 0
has comment: http://stackoverflow.com/comment/83035396
has title: ModuleNotFoundError: No module named 'bs4' when running a script using the run command
tagged with: web-scraping
upvote count: 1
downvote count: 1
type: Question
score: 0
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/83035328
has comment: http://stackoverflow.com/comment/83035338

http://stackoverflow.com/comment/83142117
comment on: http://stackoverflow.com/q/48083313
type: Comment
type: QuestionComment
has text: I know my question might be a duplication but foe some reasons procedure suggested in similar posts does not work for me
score: 0

http://stackoverflow.com/comment/83075243
has text: please ignore the parameters('row,col,num') in Case 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48051678
score: 0

http://stackoverflow.com/comment/83141119
score: 1
comment on: http://stackoverflow.com/q/48081688
type: QuestionComment
type: Comment
has text: You would have to say what the allowed character set is. The larger the character set, the fewer characters that will be needed. You can also consider truncating the hash to further reduce the size of the output.

http://stackoverflow.com/q/48026715
has comment: http://stackoverflow.com/comment/83024501
tagged with: network-programming
has comment: http://stackoverflow.com/comment/83024418
score: 1
has body: My port forward rule I've created a python TCP server and client which is working fine when I launch both server and client on my computer and when I launch the server and the client on different computers on the same network, however I wanted to make it work when computers are in different networks. I have forwarded my router port 8080 to convert to 8888 in my computer, in fact I have also a rule for the port 80 on my router converting to 8080 on my PC which is the Wamp server, and as the python server is not working I guessed it was from the code but I can't figure it out: Server: import socket sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.bind(("127.0.0.1", 8888)) sck.listen(1) conn, adr = sck.accept() print('Connected to ', adr) while 1: data = conn.recv(1024).decode() if data and ('over' not in data): conn.send(data.encode()) continue break conn.close() Client: import socket sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect(('&lt;my_external_ip&gt;', 8888)) while True: data = input('Say something: ') if 'Shut up' in data: sck.send('over'.encode()) sck.close break sck.send(data.encode()) I've made this test: Started Wamp server and tried to access it by my external ip with chrome (working) Opened my Python TCP Client and connected to the Wamp server (working) Turned Wamp off and started my python server with the same port as Wamp, then tried to acess with the python client (not working) If there's nothing wrong with the TCP Server code why does Wamp work and he don't? Please check the following - Whats the logic behind binding 127.0.0.1 I couldn't understand... Won't that make it only be accessible by my PC? If that part is ok than at least is something related to the Server code I guess...
has comment: http://stackoverflow.com/comment/83068970
has comment: http://stackoverflow.com/comment/83024808
has comment: http://stackoverflow.com/comment/83023184
type: Question
has comment: http://stackoverflow.com/comment/83024271
downvote count: 0
has title: Connect to python server in different network
favorite count: 0
tagged with: sockets
has comment: http://stackoverflow.com/comment/83024781
has comment: http://stackoverflow.com/comment/83023363
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83024651
upvote count: 1
has comment: http://stackoverflow.com/comment/83261369

http://stackoverflow.com/a/48144662
accepted answer of: http://stackoverflow.com/q/48100919
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/83303420
has comment: http://stackoverflow.com/comment/83294968
has comment: http://stackoverflow.com/comment/83353655
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83300598
has body: I don't know if this is what you need, but I think I can use the Matplotlib Library. from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.dates as mdates fig = plt.figure() ax = fig.gca(projection='3d') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('Time') ax.plot(df2['lon'].values, df2['lat'].values, mdates.date2num(df2['dtime'].tolist()),label=str(1)) ax.zaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S')) ax.legend() plt.show() Explain: The role of label is to identify which category the current data belongs to, and I used ID as an example. mdates.date2numis used in conjunction with set_major_formatter. If we use the following code： ax.plot(df2['lon'].values, df2['lat'].values, df2['dtime'].values,label=str(1)) As a result, the graph time axis is shown to be a large int： If we only use the set_major_formatter to modify the time display format to get the wrong： OverflowError: Python int too large to convert to C long mdates.date2num converts time into smaller numbers,so we need to use mdates.date2num and set_major_formatter
has comment: http://stackoverflow.com/comment/83350568
type: Answer
answers question: http://stackoverflow.com/q/48100919

http://stackoverflow.com/comment/83205988
type: Comment
type: QuestionComment
score: 0
has text: It needs to create new DHCP Pool range after deducting exclusion range of IPs/single IP. E.g.: There are DHCP Pool range 192.168.1.1 - 192.168.1.254, and exclusion range 192.168.1.150 - 192.168.1.160, 192.168.1.200, 192.168.1.250.
comment on: http://stackoverflow.com/q/48114542

http://stackoverflow.com/q/48069000
has answer: http://stackoverflow.com/a/48070256
answer count: 1
has title: Writing value to given filed in csv file using pandas or csv module
has comment: http://stackoverflow.com/comment/83111882
has body: Is there any way you can write value to specific place in given .csv file using pandas or csv module? I have tried using csv_reader to read the file and find a line which fits my requirements though I couldn't figure out a way to switch value which is in the file to mine. What I am trying to achieve here is that I have a spreadsheet of names and values. I am using JSON to update the values from the server and after that I want to update my spreadsheet also. The latest solution which I came up with was to create separate sheet from which I will get updated data, but this one is not working, though there is no sequence in which the dict is written to the file. def updateSheet(fileName, aValues): with open(fileName+".csv") as workingSheet: writer = csv.DictWriter(workingSheet,aValues.keys()) writer.writeheader() writer.writerow(aValues) I will appreciate any guidance and tips.
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/83111821
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/83111983
score: 0
tagged with: pandas

http://stackoverflow.com/comment/83201236
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48112770
type: AnswerComment
has text: Ok. There's no need to include the OP's original version in your answer. There are several more things you can do to improve this code. Since you got rid of the `global`, you probably should return the password. It would be good if you got rid of that ugly recursive call to `generate_password()`: don't use recursion when a simple `while` loop can do the job. Maybe add `try...except` logic in case the user doesn't input a number for `length`. And check that `length` isn't less than 8.

http://stackoverflow.com/q/48044269
has comment: http://stackoverflow.com/comment/83062665
possible better answer: http://stackoverflow.com/a/48044522
has body: The following program opens a two-column file and plots one column as a function of the other. The problem is that, as long as the graph window is open, the tkinter widgets are inactive. They become active again when the graph window is closed. I would like to keep the widgets active. So that, if I choose another file, I won't have to close the graph window. How can this be done? I tried to use, e.g., top.after(10, openfile) but, quite expectedly, the program prompts the user to choose a new file every 10 ms. import tkinter as Tk from tkinter.filedialog import askopenfilename import matplotlib.pyplot as plt top = Tk.Tk() file_name = Tk.StringVar() f = [] m = [] def openfile(): global opfi opfi = askopenfilename() def plot(): global opfi del f[:], m[:] with open(opfi, 'r') as file: for line in range(6000): g = file.readline().split('\t') field = str(g[0]) magn = str(g[1]) f.append(eval(field)) m.append(eval(magn)) plt.close() plt.plot(f, m, 'b') plt.show() b1 = Tk.Button(top, text='Sample', command=openfile, width=10) b1.place(relx=0.0, rely=0.0) b3 = Tk.Button(top, text='Plot', command=plot, width=6) b3.place(relx=0.4, rely=0.0) Tk.mainloop() And this is a file sample I work with: .983983186936 -0.702925299281 1.00236660232 -0.726670144435 1.02074058078 -0.75169698959 1.03909297815 -0.777209834745 1.05744133036 -0.801262179899 1.0757541608 -0.826426525054 1.09406204943 -0.852315870209 1.11235780038 -0.876239715363 1.13063106929 -0.900676560518 1.14890298837 -0.926342905673
tagged with: python
has comment: http://stackoverflow.com/comment/83064132
type: AnsweredQuestion
has title: Keeping tkinter panel active when plot is open
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83063122
has comment: http://stackoverflow.com/comment/83062940
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83059952
type: Question
has answer: http://stackoverflow.com/a/48044522
has answer: http://stackoverflow.com/a/48046473
accepted answer: http://stackoverflow.com/a/48046473
has comment: http://stackoverflow.com/comment/83063401
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/83107143
has text: To be correct you should be using `numpy.uintp` as the dtype for pointers. Internally that is how PyCUDA does it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48064939
score: 1

http://stackoverflow.com/a/48122093
has body: you are just calling the function again but not returning the value, it should be print "Let's try that again." return prompt() However, you shouldn't be doing this recursively at all... def prompt(): print "Hit 'Y' to begin." action = raw_input("&gt; ").lower() while action != "y": print "For this game to work, you're going to have to get" print "the hang of hitting the right key." print "Let's try that again." action = raw_input("&gt; ").lower() return "opening" ret = prompt() print ret
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48122025
score: 1
accepted answer of: http://stackoverflow.com/q/48122025
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83220990

http://stackoverflow.com/comment/83250910
comment on: http://stackoverflow.com/q/48132656
type: Comment
has text: @ Piinthesky Thanks for comment, I updated the Code above.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83120348
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48072551
type: AnswerComment
has text: After fiddling a little bit, I successfully implemented your solution into my code. +1 for fully answering my question and giving my a very helpful solution.

http://stackoverflow.com/a/48162458
answers question: http://stackoverflow.com/q/48162287
has comment: http://stackoverflow.com/comment/83304856
has body: Several points here: You do need to open the file in rb/wb mode (if on Python 2) or use the newline='' parameter on Python 3 when dealing with CSV files. At least if there is a possibility of newlines appearing in your data. You can't open the file for writing while it's still open for reading, especially since you haven't read any data from it at that point. You never write anything to the file. The only thing you do is open it in write mode (which erases it as the very first thing). Better use a different output file: #assuming Python 3 def delete_information_method(): #a tkinter entry global delete_entry #opening csv in read with open('employees.csv' , 'r', newline='') as emp_read: #creating our dictreader csv_dictreader = csv.DictReader(emp_read) fieldnames = csv_dictreader.fieldnames #opening new csv file in write mode with open ('employees_out.csv' , 'w', newline='') as emp_write: #creating our writer csv_writer1 = csv.DictWriter(emp_write, fieldnames=fieldnames) csv_writer1.writeheader() #our loop to check each line inside of our csv file is equal to what is inside the delete entry for line in csv_dictreader: if line['employee id'] != str(delete_entry.get()): csv_writer1.writerow(line) If you don't want to do that, read the entire file and then write it afterwards: def delete_information_method(): #a tkinter entry global delete_entry #opening csv in read with open('employees.csv' , 'r', newline='') as emp_read: #creating our dictreader csv_dictreader = csv.DictReader(emp_read) fieldnames = csv_dictreader.fieldnames contents = [line for line in csv_dictreader] #opening csv file in write mode with open ('employees.csv' , 'w', newline='') as emp_write: #creating our writer csv_writer1 = csv.DictWriter(emp_write, fieldnames=fieldnames) csv_writer1.writeheader() #our loop to check each line inside of our csv file is equal to what is inside the delete entry for line in contents: if line['employee id'] != str(delete_entry.get()): csv_writer1.writerow(line)
type: Answer
has comment: http://stackoverflow.com/comment/83307810
has comment: http://stackoverflow.com/comment/83305034
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/83304882
accepted answer of: http://stackoverflow.com/q/48162287
has comment: http://stackoverflow.com/comment/83305236

http://stackoverflow.com/q/48102986
has title: No validation on submit Flask
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: For some reason, form.validate_on_submit() does not return anything. from flask import Flask from flask_wtf import FlaskForm from wtforms import StringField, DecimalField, validators from flask import render_template app = Flask(__name__) app.config.update(dict( SECRET_KEY="super awesome key" )) class MyForm(FlaskForm): name = StringField('Product name', [validators.InputRequired(), validators.Length(min=0, max=30)]) @app.route('/', methods=['GET', 'POST']) def index(): form = MyForm() if form.validate_on_submit(): return "Mission accomplished!" return render_template('submit.html', form=form) {% macro render_field(field) %} {{ field.label }} {% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% endmacro %} Title Add new grocery product Provide appropriate product details {{ form.csrf_token }} {{ render_field(form.name.label) }} {{ form.name(size=20) }} The app itself is supposed to gather user input in specific form and insert this via SQLAlchemy into database. Output is supposed to: Return "Mission accomplished!" if validation succeeded Return validation of which field failed and display error msg "This field is required" on the submit.html template EDIT Duo some success with the code, I make another edit to the question. It seems that macro isn't displaying error message for appropriate field if the validation fails. I.E. if Field name is empty, macro should create and display error message ( This Field cannot be empty) by itself. FINAL EDIT I managed to find the solution. Submit.html template seems to cause the issue with macro if render_field looks like this: {{ render_field(form.name.label) }} instaed of this: {{ render_field(form.name) }}
downvote count: 1
has answer: http://stackoverflow.com/a/48104746
type: Question
tagged with: wtforms
answer count: 1
tagged with: flask
score: 0
favorite count: 0

http://stackoverflow.com/comment/83103907
type: Comment
comment on: http://stackoverflow.com/a/48065180
type: AnswerComment
has text: I recommend this site then: (https://pythonprogramming.net/pygame-buttons-part-1-button-rectangle/)
score: 0

http://stackoverflow.com/comment/83160455
type: AnswerComment
score: 0
type: Comment
has text: the i comes from the entry, it represents every element in it
comment on: http://stackoverflow.com/a/48088691

http://stackoverflow.com/q/48152944
answer count: 2
tagged with: connection
type: UnansweredQuestion
has title: Writing Python Dataframe to MSSQL Table
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/52967718
has body: I currently have a Python dataframe that is 23 columns and 20,000 rows. Using Python code, I want to write my data frame into a MSSQL server that I have the credentials for. As a test I am able to successfully write some values into the table using the code below: connection = pypyodbc.connect('Driver={SQL Server};' 'Server=XXX;' 'Database=XXX;' 'uid=XXX;' 'pwd=XXX') cursor = connection.cursor() for index, row in df_EVENT5_15.iterrows(): cursor.execute("INSERT INTO MODREPORT(rowid, OPCODE, LOCATION, TRACKNAME) cursor.execute("INSERT INTO MODREPORT(rowid, location) VALUES (?,?)", (5, 'test')) connection.commit() But how do I write all the rows in my data frame table to the MSSQL server? In order to do so, I need to code up the following steps in my Python environment: Delete all the rows in the MSSQL server table Write my dataframe to the server
has answer: http://stackoverflow.com/a/48153098
tagged with: sql-server
score: 0

http://stackoverflow.com/comment/83323277
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48171849
type: AnswerComment
has text: @jezrael no worry , I think op also help himself :-)

http://stackoverflow.com/a/48033578
accepted answer of: http://stackoverflow.com/q/48033519
type: Answer
answers question: http://stackoverflow.com/q/48033519
downvote count: 0
has body: this functions doesn't return any object to be used, check the documentation: https://www.pygame.org/docs/ref/music.html#pygame.mixer.music.load after loading the file you should use pg.mixer.music.play()
score: 3
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/48100445
score: 1
upvote count: 1
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48100240
answers question: http://stackoverflow.com/q/48100240
type: Answer
has body: The Pythonic way would be to just try it and catch the exception. try: int(value) passed_values.append(value) except ValueError: failed_values.append(value)

http://stackoverflow.com/q/48109956
possible better answer: http://stackoverflow.com/a/55156532
has answer: http://stackoverflow.com/a/48110633
accepted answer: http://stackoverflow.com/a/48110633
has answer: http://stackoverflow.com/a/70907877
has body: For some reason I have issues installing new packages with my pip. I have an OS Sierra environment and everything was working fine before. Now either I use a virtualenv or not, I get: Collecting requests Could not find a version that satisfies the requirement requests (from versions: ) No matching distribution found for requests This is not only for the "requests" library but also for all the others (e.g. django etc.). I have the latest pip: pip --version returns: pip 9.0.1 from /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg (python 2.7) And my python version is: 2.7.12 Moreover based on this article I checked if I can curl the PyPi website and I do get a response back. Any idea what is wrong? EDITED I executed the pip install as: pip install -vvv requests and I get a detailed output of the error: Collecting requests 2 location(s) to search for versions of requests: * http://pypi.python.org/simple/requests/ * http://pypi.wfp.org/simple/requests/ Getting page http://pypi.python.org/simple/requests/ Starting new HTTP connection (1): pypi.python.org "GET /simple/requests/ HTTP/1.1" 403 16 Could not fetch URL http://pypi.python.org/simple/requests/: 403 Client Error: SSL is required for url: http://pypi.python.org/simple/requests/ - skipping Getting page http://pypi.wfp.org/simple/requests/ Starting new HTTP connection (1): pypi.wfp.org "GET /simple/requests/ HTTP/1.1" 404 None Could not fetch URL http://pypi.wfp.org/simple/requests/: 404 Client Error: NOT FOUND for url: http://pypi.wfp.org/simple/requests/ - skipping Could not find a version that satisfies the requirement requests (from versions: ) Cleaning up... No matching distribution found for requests Exception information: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1- py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1- py2.7.egg/pip/commands/install.py", line 324, in run requirement_set.…
answer count: 3
has comment: http://stackoverflow.com/comment/83195645
has comment: http://stackoverflow.com/comment/83196176
has comment: http://stackoverflow.com/comment/83195891
favorite count: 0
has comment: http://stackoverflow.com/comment/83196009
tagged with: pip
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Unable to install any package through pip
has answer: http://stackoverflow.com/a/55156532
has comment: http://stackoverflow.com/comment/83195973
has comment: http://stackoverflow.com/comment/83196078
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83196286

http://stackoverflow.com/comment/83266376
type: Comment
comment on: http://stackoverflow.com/q/48141221
score: 0
has text: Possible duplicate of [selecting an iframe using python selenium](https://stackoverflow.com/questions/7534622/selecting-an-iframe-using-python-selenium)
type: QuestionComment

http://stackoverflow.com/a/48143350
score: 4
type: Answer
upvote count: 4
downvote count: 0
has body: I found the folder Keras is/ or would store this weight file and dropped it in there with the following line in Terminal. mv /home/mine/fastai/courses-master/deeplearning1/nbs/vgg16.h5 ~/.keras/models/vgg16.h5 The first path is the path with my fully downloaded weights .h5 file. The second path is where I put said weights and the path Keras looks at to find the weights.
accepted answer of: http://stackoverflow.com/q/48129804
answers question: http://stackoverflow.com/q/48129804
type: AcceptedAnswer

http://stackoverflow.com/comment/83280359
has text: whether or not they use an array is irrelevant. It's good programming practice, but what they want can be done without an array so your answer is a little bit misleading.
comment on: http://stackoverflow.com/a/48146991
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/q/48118537
has comment: http://stackoverflow.com/comment/83214575
has comment: http://stackoverflow.com/comment/83214303
tagged with: numpy
has answer: http://stackoverflow.com/a/48119537
tagged with: pandas-groupby
type: Question
tagged with: pandas
type: AnsweredQuestion
has body: I have a pandas dataframe in the following format: id,criteria_1,criteria_2,criteria_3,criteria_4,criteria_5,criteria_6 1,0,0,95,179,1,1 1,0,0,97,185,NaN,1 1,1,2,92,120,1,1 2,0,0,27,0,1,NaN 2,1,2,90,179,1,1 2,2,5,111,200,1,1 3,1,2,91,175,1,1 3,0,8,90,27,NaN,NaN 3,0,0,22,0,NaN,NaN I have the following working code: df_final = df[((df['criteria_1'] &gt;=1.0) | (df['criteria_2'] &gt;=2.0)) &amp; (df['criteria_3'] &gt;=90.0) &amp; (df['criteria_4'] &lt;=180.0) &amp; ((df['criteria_5'].notnull()) &amp; (df['criteria_6'].notnull()))].groupby('id').first() Which results is this: id,criteria_1,criteria_2,criteria_3,criteria_4,criteria_5,criteria_6 1,1,2,92,120,1,1 2,1,2,90,179,1,1 3,1,2,91,175,1,1 However, I would like to create a new Boolean indicator flag column to indicate which rows meet the criteria (result of above groupby) on the original dataframe using .transform(). Originally, I thought I could use a combination of .first().transform('any').astype(int), but I don't think that will work. If there is cleaner way to do this that would be great as well.
accepted answer: http://stackoverflow.com/a/48119537
tagged with: python
answer count: 1
has title: Python PANDAS: GroupBy First Transform Create Indicator
score: 0

http://stackoverflow.com/q/48154467
tagged with: fetching-strategy
type: UnansweredQuestion
tagged with: caching
tagged with: api
downvote count: 0
answer count: 0
tagged with: flask
favorite count: 0
has body: I'm trying to develop an API service that after collecting data continuously from different sources, elaborate that data, and keep that information ready from being requested from another service. I'm using Flask and it's working on top of a single thread. My problem is about the slowlines accessing the cached data. The gathering process it works pretty well, but sometimes when I ask for the data the server it's busy because in the meantime it's fetching the data from the sources. How should I set up the thread to avoid this? Here down I'm explain what I've done thru some simplified functions and classes. The Fetching Service class FetchingService(): def __init__(self,url=None,speed=None): self.url = url self.speed = speed # speed in seconds self.last_updated = None # last time the service was used def loadData(self): time = { 'timestamp': int(time.time()) } try: r = requests.get(self.url) # get the data from the url data = r.json() # if is a json data.update({ 'status': True }) data.update(time) return data except: data = { 'status': False } data.update(time) return data def isTimeToUpdate(self): if self.last_updated is not None: # check if is the time to run an update delta = int(time.time()) - self.last_updated if delta &gt;= self.speed: # if passed enougth time return True # is time to update else: return False # too early else: return False # last_updated not set def run(self): if self.last_updated is None: self.last_udated = int(time.time()) if self.isTimeToUpdate(): self.loadData() The Caching Service class Caching(): def __init__(self,instances): self.data = [] self.instances = instances def run(self): if self.instances: for i in instances: self.data.append(i.run()) def queryLast(self): if self.data: return self.data[-1] The Thread class myThread(): def __init__ (self,thread_time,instances): self.speed = thread_time self.data = None self.instances = instances self.dataLock = threading.Lock() self.myThread = threading.Thread() def primaryThread(self): self.my…
type: Question
tagged with: python
score: 1
upvote count: 1
has title: Python - Flask API service - Loop through API data sources, cache, and give rapid feedback on call

http://stackoverflow.com/comment/83292876
comment on: http://stackoverflow.com/q/48156752
score: 0
has text: Thanks all, I have edited the post. I defined the BeginDate column initially as you had suggested, so I am unsure what else could be wrong. Thanks
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83024734
type: AnswerComment
comment on: http://stackoverflow.com/a/48027381
type: Comment
has text: Yes. Besides being a glorified loop, apply has many other overheads to the point that a simple for loop might be faster (because it operates at C speed).
score: 0

http://stackoverflow.com/comment/83423220
comment on: http://stackoverflow.com/a/48163549
type: Comment
score: 0
has text: It doesent sort it highest to lowest though.
type: AnswerComment

http://stackoverflow.com/q/48027883
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48027937
tagged with: python
has title: Python 3 regular expression for $ but not $$ in a string
tagged with: regex
has comment: http://stackoverflow.com/comment/83025630
has comment: http://stackoverflow.com/comment/83025644
type: Question
score: 5
has answer: http://stackoverflow.com/a/48039562
upvote count: 5
downvote count: 0
has body: I need to match one of the following anywhere in a string: ${aa:bb[99]} ${aa:bb} ${aa} but not: $${aa:bb[99]} $${aa:bb} $${aa} my python 3 regex is: pattern = **r"[^\$|/^]**\$\{(?P&lt;section&gt;[a-zA-Z]+?\:)?(?P&lt;key&gt;[a-zA-Z]+?)(?P&lt;value&gt;\[[0-9]+\])?\}" What I'm looking for, is the proper way to say not $ or beginning of a string. The block r"[^\$|/^]" will properly detect all cases but will fail if my string starts at the first character. I trie, without success: r"[^\$|\b]... r"[^\$|\B]... r"[^\$]... r"[^\$|^] Any suggestion?
has comment: http://stackoverflow.com/comment/83025818
answer count: 3
has answer: http://stackoverflow.com/a/48027914
has comment: http://stackoverflow.com/comment/83025804

http://stackoverflow.com/q/48030017
type: AnsweredQuestion
has title: Consecutive API Calls and Bad Request Messages
tagged with: bad-request
tagged with: python-requests
has body: I wanted to make API calls for each element in 'title'. 'title' looks like this and is VERY large: ABMC-2017-0002 ACF-2015-0001 ACUS-2017-0004 ADF-2017-0005 AMS-DA-14-0095 VA-2017-VHA-0026 VETS-2017-0001 I wanted to go over them like so: try: for i in title: docketID=i url=APIUrl+'docket.json?api_key='+APIkey+'&amp;docketId='+docketID response = json.load(urlopen(url).read()) print('json loaded from URL \n') time.sleep(3) except: print json.loads(urlopen(url)).get('errors')[0] 'time.sleep(3)' was added later after I kept getting HTTP Error 400: Bad Request. The API calls per hour was limited. But afterwards I'm still getting HTTP Error 504: Gateway Time-out. Does anyone know how I can loop through a list and make consecutive API calls?
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83030295
has answer: http://stackoverflow.com/a/48030949
tagged with: api
answer count: 1
accepted answer: http://stackoverflow.com/a/48030949
tagged with: python

http://stackoverflow.com/comment/83200854
score: 0
comment on: http://stackoverflow.com/q/48108723
type: Comment
type: QuestionComment
has text: There are quite a few bug fixes in version 0.19 for `manifold.TSNE`. Try and upgrade your `sklearn` version.

http://stackoverflow.com/q/48080315
type: Question
tagged with: heroku
score: 1
accepted answer: http://stackoverflow.com/a/53249649
has comment: http://stackoverflow.com/comment/93379634
has title: Celery / Heroku - delay() does nothing when ran in the background using Heroku run python
has comment: http://stackoverflow.com/comment/83134789
answer count: 1
downvote count: 0
tagged with: delay
has comment: http://stackoverflow.com/comment/83135241
favorite count: 0
has comment: http://stackoverflow.com/comment/83135145
has comment: http://stackoverflow.com/comment/93383849
tagged with: python
has comment: http://stackoverflow.com/comment/83135639
has answer: http://stackoverflow.com/a/53249649
type: AnsweredQuestion
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/83135076
tagged with: celery
has body: I am attempting to add background workers using Celery to automatically run scripts each day to update the information my website provides. I've integrated Celery with Django and Heroku, and I can import the module and use the function, but it freezes when I use the add.delay()command until I press Ctrl+C to cancel the command. I am using celery 4.1 Here is how I run the commands: heroku ps:scale worker=1 heroku run python &gt;&gt;&gt;from Buylist.tasks import * &gt;&gt;&gt;add(2,3) &gt;&gt;&gt;5 &gt;&gt;&gt;add.delay(2,3) #-- Freezes until I press Control+C If you could help me figure out where my settings are misconfigured, that would be great. I'm testing atm. the tasks.py is the sample code to get a working example, and then I'll move on to figuring out CELERY_BEAT settings project/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Buylist/tasks # Buylist is the single app in my root directory # Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task from celery import Celery from celery.schedules import crontab @shared_task def test(arg): print(arg) @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y @shared_task def xsum(numbers…

http://stackoverflow.com/a/48169607
has comment: http://stackoverflow.com/comment/83325937
downvote count: 0
has body: You are indeed right, your code lacks flexibility. But in my opinion, you are looking at the problem from a valid perspective, yet not enough general. In other words, your solution has this idea implemented: "let me check first - given the quantities available for each price (which I sorted beautifully in an array) - what are the different sellers I have to buy from, then do all the computation." A more flexible idea can be: "Let me start buying the from cheaper available, as much as I can. I will stop when my order is fulfilled, and compute the math step by step". This means you build an iterative code, cumulating step by step the overall spent amount, and once completed computing the average price per piece and the max price (i.e. the last accessed in your ordered list). To turn into code to this thoughts: list_prices = [12,12.7,13.5,14.3] list_amounts = [85,100,30,54] BuyAmount = x remaining = BuyAmount spent_total = 0 current_seller = -1 # since we increment it right away while(remaining): # inherently means remaining &gt; 0 current_seller += 1 # in case we cannot fulfill the order if current_seller &gt;= len(list_prices): # since we need it later we have to restore the value current_seller -= 1 break # we want either as many as available or just enough to complete # BuyAmount buying = min([list_amounts[current_seller], remaining]) # update remaining remaining -= buying # update total spent_total += buying * list_prices[current_seller] # if we got here we have no more remaining or no more stock to buy # average price avgprice = spent_total / (BuyAmount - remaining) # max price - since the list is ordered - highprice = list_prices[current_seller] print(avgprice) print(highprice)
answers question: http://stackoverflow.com/q/48169038
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/comment/83030574
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48030198
has text: so in this case if we take the first item in the input: ` [7,0]` does it become [-7,0]?
type: QuestionComment

http://stackoverflow.com/a/48040519
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48040346
type: Answer
accepted answer of: http://stackoverflow.com/q/48040346
has body: Please replace reshape(1,-1) to reshape(-1, 1) for all usages. The former transforms an array into (1 person x n features) and the latter does (n persons x 1 feature). feature is hight, in this case. If you modified import section as below, there is no need to reshape the array since their shapes are already satisfy the form of (n persons x 1 feature). # Import dataset dataset = pd.read_csv('NBA.csv') X = dataset.iloc[:, 1].values y = dataset.iloc[:, 0].values X = X.reshape(-1, 1) y = y.reshape(-1, 1) In an early age of the sklearn, you can feed vector as inputs. But recently it has changed and now you need to explicitly indicate whether the vector is (1 sample x n features) or (n samples x 1 feature) by using reshape or some other methods.
upvote count: 1
score: 1

http://stackoverflow.com/q/48069875
has comment: http://stackoverflow.com/comment/83113933
answer count: 1
has body: I have an import error while coding a flask web application. Here are my imports: from flask import Flask from flask import session, request from flask import render_template, redirect from flask_sqlalchemy import sqlalchemy Although the last line of code gives me the error: from flask_sqlalchemy import sqlalchemy I have successfully installed Flask, SQLAlchemy, and Flask-SQLAlchemy using pip, and I have checked whether these are installed on the system using python -c "import Flask" etc. These checks resulted in a 0, meaning that it was correctly installed. NOTE: I have already read other posts, and tried flask.ext.sqlalchemy, flaskext_sqlalchemy, etc. as import variations. Here are the installed packages in the sitepackages directory for python 2.7. Flask_OAuth-0.12.dist-info httplib2 Flask_SQLAlchemy-2.3.2.dist-info httplib2-0.10.3.dist-info SQLAlchemy-1.2.0.dist-info oauth2 flask_oauth.py oauth2-1.9.0.post1.dist-info flask_oauth.pyc sqlalchemy flask_sqlalchemy tests I have also structured my files, so the imports are in the init.py file. My other files included views.py, config.py, run.py, and a templates folder containing html files. What am I doing wrong here, and how is my problem different from others?
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/83113748
has comment: http://stackoverflow.com/comment/83113905
type: UnansweredQuestion
tagged with: python
has title: Flask sqlalchemy import error, different error
type: Question
has comment: http://stackoverflow.com/comment/83113878
tagged with: flask
has comment: http://stackoverflow.com/comment/83113733
tagged with: python-2.7
has answer: http://stackoverflow.com/a/52862146
score: 0

http://stackoverflow.com/comment/83155964
type: Comment
comment on: http://stackoverflow.com/a/48090596
has text: Ref from official documation: Equality tests between OrderedDict objects are order-sensitive and are implemented as list(od1.items())==list(od2.items()) , https://docs.python.org/2/library/collections.html#ordereddict-objects, besides, using inheritance has other benefits, like I can print out the fieldsnames etc. Your answer is Ok for this case, but the generator cannot act as an Reader object.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83170451
has text: Note that unless you need butterfly-effect-proof reproducibility of the results, it should suffice to store the time and state (`ode_solver.t`, `ode_solver.y`) of the integrator (and your `rhs`). The only thing this does not store are internal parameters of the solver such as the integration time step, which will be automatically recalibrated when you start a new solver.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48096655

http://stackoverflow.com/comment/123131486
has text: @joel True, conceptually a type does not require a value. But in the context of `f(...) -> type:` annotations, we are referring to the _type of the returned **value**_. It has a very specific meaning, not a general annotation of _how_, _when_, or _if_ a function exits. Allowing so requires changing the _semantics_ of `->`, as described by PEP
type: AnswerComment
comment on: http://stackoverflow.com/a/48038206
type: Comment
score: 1

http://stackoverflow.com/q/48089770
has answer: http://stackoverflow.com/a/48109161
tagged with: python
has body: I have a sqlite3 DB with Consumer Key, Consumer Secret, Access Token, Access Token Secret. I'm SELECT'ing all the data and iterating through the cursor. While printing I get the data, but for some reason can't pass it to the twython object. This is the first code I tried: #!/usr/bin/env pythons from twython import Twython from time import sleep import sqlite3 db = sqlite3.connect('./mydb') cursor = db.cursor() cursor.execute ('''SELECT app_key, app_secret, oauth_token, oauth_token_secret FROM users''') for row in cursor: twitter = Twython(row[0], row[1], row[2], row[3]) search = twitter.search(q = '#peace', count = 10) tweets = search['statuses'] for tweet in tweets: b = tweet['id'] print(b) twitter.retweet(id = b) sleep(60) db.close() Then I tried this: #!/usr/bin/env pythons from twython import Twython from time import sleep import sqlite3 db = sqlite3.connect('./mydb') cursor = db.cursor() cursor.execute ('''SELECT app_key, app_secret, oauth_token, oauth_token_secret FROM users''') for row in cursor: twitter = Twython('{0}, {1}, {2}, {3}'.format(row[0], row[1], row[2], row[3])) search = twitter.search(q = '#peace', count = 10) tweets = search['statuses'] for tweet in tweets: b = tweet['id'] print(b) twitter.retweet(id = b) sleep(60) db.close() The error code: twython.exceptions.TwythonAuthError: Twitter API returned a 400 (Bad Request), Bad Authentication data. As an additional step, I tried manually passing the credentials (Consumer Key, Consumer Secret, Access Token, Access Token Secret) and it works like charm! Can someone tell me what I'm doing wrong here? According to me the first code should work just fine! Thanks in advance!
type: AnsweredQuestion
score: 1
has title: How to pass the values recieved from sqlite3 to Twython object in Python
upvote count: 1
tagged with: twython
type: Question
accepted answer: http://stackoverflow.com/a/48109161
tagged with: twitter
tagged with: sqlite
downvote count: 0
answer count: 1
favorite count: 0

kinect
type: Tag
tags question: http://stackoverflow.com/q/48150314
tag name: kinect

http://stackoverflow.com/comment/83006948
type: QuestionComment
comment on: http://stackoverflow.com/q/48018680
has text: If iteration over set is predictable, I would use it. It does seem predictable with some use cases while it's not for some use cases as I have mentioned above. I asked for implementation of it so that I understand the behavior and use it wisely if it helps.
score: 0
type: Comment

http://stackoverflow.com/q/48041639
has title: How can I count the swaps in a Merge Sort Algorithm in Python
downvote count: 0
score: 1
favorite count: 0
has body: I've done the MergeSort algorithm, but I don't know how to count the swaps. My code is: def mergesortInv(list): if len(list) &lt; 2: return list else: middle = len(list) // 2 left = mergesortInv(list[:middle]) #definim les dues meitats right = mergesortInv(list[middle:]) swaps=??? return mergeInv(left, right,swaps) def mergeInv(left, right,swaps): if len(left) &lt; 1: return right if len(right) &lt; 1: return left if left[0] &lt;= right[0]: return [left[0]] + mergeInv(left[1:],right,swaps) else: return [right[0]] + mergeInv(left,right[1:],swaps) The output of this algorithm would be the sorted list(the algorithm works in this part) and the number of swaps: mergesortInv(list) == ([1, 2, 3, 4, 5, 7, 8], 6) 6 is the number of swaps.
has comment: http://stackoverflow.com/comment/83054049
accepted answer: http://stackoverflow.com/a/48041759
linked to: http://stackoverflow.com/q/337664
upvote count: 1
tagged with: python
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/337664
has comment: http://stackoverflow.com/comment/83054586
has comment: http://stackoverflow.com/comment/83053993
has comment: http://stackoverflow.com/comment/83054780
type: Question
has comment: http://stackoverflow.com/comment/83054067
has answer: http://stackoverflow.com/a/48041800
tagged with: mergesort
has answer: http://stackoverflow.com/a/48041759
possible better answer: http://stackoverflow.com/a/48041800
answer count: 2

http://stackoverflow.com/q/48114708
linked to: http://stackoverflow.com/q/973473
has comment: http://stackoverflow.com/comment/83205700
has body: I have to loop through multiple folders and finally check if there are three folders in the final folders. If the three folders are present in the folder then do nothing,else print the folderpath or name.Im finding it difficult to make it work, Any suggestions are welcome,Thanks in advance This is what i have at the moment, check_empty =['One','Two','Three'] path = '/mnt/sdc1/Username/' folders = next(os.walk('/mnt/sdc1/Mahajan/'))[1] for folder in folders: files_in_folders = os.listdir(path +folder) for files_in in files_in_folders: for files in os.listdir(path+folder+'/'+files_in): for items in check_empty: if files in check_empty: print(folder +'Good') else: print(folder+'NotGood')
type: Question
has comment: http://stackoverflow.com/comment/83205834
has comment: http://stackoverflow.com/comment/83205328
has comment: http://stackoverflow.com/comment/83205737
score: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48115203
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83205497
has title: Looping through many folders

http://stackoverflow.com/comment/93340236
type: AnswerComment
comment on: http://stackoverflow.com/a/48129288
type: Comment
has text: Of cause. Performance wise this might still be a super bad idea though, especially with single resources. Assuming your app does the classic REST with cascades of resource requests your GraphQL endpoint gets a lot of load that it is not optimised for. GraphQL is a tradeoff that works better than REST because it gets rid of the limitations of REST.
score: 0

http://stackoverflow.com/q/48043754
answer count: 1
has body: I'm having some trouble with AND and OR within if else statements. This is my code: if subject == 'history' or subject == 'History' and unit == 'WWII' or unit == 'ww2': Any ideas how to fix this?
tagged with: if-statement
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/36298231
tagged with: logical-operators
score: 2
downvote count: 0
duplicate of: http://stackoverflow.com/q/36298231
has comment: http://stackoverflow.com/comment/83058460
has comment: http://stackoverflow.com/comment/83058503
favorite count: 0
type: Question
tagged with: python
has title: If Else Statements , AND OR logic operations, and text files (using Python)
has comment: http://stackoverflow.com/comment/83058581
tagged with: text-files
upvote count: 2
has answer: http://stackoverflow.com/a/48043805
has comment: http://stackoverflow.com/comment/83058480
has comment: http://stackoverflow.com/comment/83058467

http://stackoverflow.com/comment/83325462
has text: it's in another answer on the same page. If you want to get the class to which relationship is linked... `.relationships` gives you a list of relationships... each of those will have the following attribute that shows the related class: `.mapper.class_`
comment on: http://stackoverflow.com/q/48160084
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48043726
upvote count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python
has body: need some help in using beautifulsoup library for webscraping. I need to extract the text from the webpage http://thehill.com/…/365407-sean-diddy-combs-wants-to-buy-c… my goal is to extract the text exactly as in the webpage for which I am extracting all the "p" tags and its text, but inside "p" tags there are "a" tags which has also some text. so my questions: how to convert the unicoded ("") into normal strings as the text in the webpage? because when I only extract "p" tags, the beautifulsoup library converts the text into unicoded and even the special characters are unicoded, so I want to convert the extracted unicoded text into normal text. How can I do that? How to extract the text inside "p" tags which has "a" tags in it. I mean I would like to exract the complete text inside the "p" tags including the text inside nested tags. I have tried with the following code: html = requests.get("http://thehill.com/…/365407-sean-diddy-combs-wants-to-buy-c…").content news_soup = BeautifulSoup(html, "html.parser") a_text = news_soup.find_all('p') y = a_text[1].find_all('a').string
type: AnsweredQuestion
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/48043867
type: Question
answer count: 1
has title: complete webscraping using beautifulsoup
score: -1
has answer: http://stackoverflow.com/a/48043867
downvote count: 2

http://stackoverflow.com/q/48100774
has answer: http://stackoverflow.com/a/48101067
score: 0
has comment: http://stackoverflow.com/comment/83177040
type: Question
has title: Is it possible to pass values from a query to models.py in django?
has comment: http://stackoverflow.com/comment/83177232
has comment: http://stackoverflow.com/comment/83176910
tagged with: cx-oracle
answer count: 1
has comment: http://stackoverflow.com/comment/83177461
has comment: http://stackoverflow.com/comment/83177335
has body: I'm trying to make an app in which a person inserts an id and a birthday date of someone and outputs something. My doubt here is: having a query (from oracle) with the several id and birthday dates using: connection = cx_Oracle.connect(...) cursor = connection.cursor() cursor.execute("query") My question is: Is it possible to pass some values from the query to my models.py file? For example, in my "models.py" file I have a field called "id" and I would like to pass all the records from the query in the field "doente" to the "models.py" file as "id". My form is something like this: Form and my models.py file is: class PatientTutor(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(max_length = 8) patientID = models.CharField(max_length = 8) created = models.DateTimeField(auto_now_add = True) birthday = models.DateField(blank=True, default=None) birthdayPatient = models.DateField(blank=True, default=None) where the values from the fields: "GTS do autorizante" and "Data de nascimento do autorizante" are in my models.py and the values from the fields: "GTS do autorizado" and "Data de nascimento do autorizado" come from the query. I would like to copy all the values from the query to my models.py file but I don't know if that is possible. EDIT: my views.py file looks like this so for: def mostraFormTutorPaciente (request): return render(request, 'CartaoCliente/mostraFormTutorPaciente.html') def TutorPaciente (request): if request.method == 'POST': AutorizanteGTS = PatientTutor.objects.get(id = request.POST['AutorizanteGts']) NascAutorizante = PatientTutor.objects.get(birthday = request.POST['DtNascAutorizante']) connection = cx_Oracle.connect("....") cursor = connection.cursor() cursor.execute("select t_doente, doente, nome, dt_nasc, telef1, telef2" + \ "from gh.sd_doente where doente&lt;&gt;'" + patientID + \ "'and nvl(flag_anulado, 'N')&lt;&gt;'S' and dt_nasc &gt;= sysdate-18*365 and (trim(telef1) in (" + inClause + ") or trim(telef2) in…
type: UnansweredQuestion
tagged with: django
tagged with: python

calculation
tags question: http://stackoverflow.com/q/48016160
type: Tag
tag name: calculation
tags question: http://stackoverflow.com/q/48137976

http://stackoverflow.com/q/48072477
has answer: http://stackoverflow.com/a/48091419
tagged with: python
has comment: http://stackoverflow.com/comment/83132641
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83132629
tagged with: python-sounddevice
has title: Python - multiprocessing - queue: The reference of my queue changed even if it is the same object?
tagged with: multiprocessing
type: Question
accepted answer: http://stackoverflow.com/a/48091419
tagged with: mutability
has comment: http://stackoverflow.com/comment/83175576
tagged with: queue
score: 0
has body: I started using the multiprocessing not a long time ago and it is working on basic examples. Afterwards I tried to implement some kind of multi-sound input program and tried to canalize the input-flux via a queue to some processing module and that is currently badly failing. I will describe my problem in 3 points: folder-structure, process structure, what I tried. Folder structure Root folder Application start_applicaton.py input_cfg.ini Core core.py gui.py audio_recorder.py (Using sounddevice.InputStream) x_recorder.py Process structure When I start running my application, the gui is called and after I press the start-button the processes are created. Main Process audio_recorder_1 Process audio_recorder_ Process application Process What I tried core.py from multiprocessing import Queue, Process central_queue = Queue() ... d = {} d['output'] = central_queue o = AudioRecorder('name', **d) start_application.py import core def handle_queue_data(): while True: print(str(core.central_queue.get())) if __name__ == "__main__": Process(target=handle_queue_data, name="syncOutput").start() audio_recorder.py class AudioRecorder(object): def __init__(self, name, **d): ... self.output_queue = d['output'] def run(self): queue = Queue() def callback(indata, frames, time, status): if status: print(status, flush=True) # Push the got data into the queue queue.put([indata.copy()]) with sd.InputStream(samplerate=self.sample_rate, device=self.device_id, channels=self.channel_id, callback=callback): while True: self.output_queue.put(queue.get()) It was not working. After debugging, it seems like after the start from the core.py of the recorder, the reference of the queue had changed... FYI the debug information: # in the audio_recorder.py object centralized_queue = {Queue} &lt;multiprocessing.queues.Queue object at 0x00000000086B3320&gt; _buffer = {deque} deque([[array([[-0.01989746, -0.02053833],\n [-0.01828003, -0.0196228 ],\n [-0.00634766, -0.00686646],\n ..., \n [-0.01119995, -0.01144…
answer count: 1

http://stackoverflow.com/a/48136513
accepted answer of: http://stackoverflow.com/q/48135942
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48135942
type: Answer
has body: Try to use time.perf_counter() instead of time.time(). At least in my environment, time.perf_counter() never went to 0 as below. import time def time_perf_counter(): start_time = time.perf_counter() return time.perf_counter() - start_time def time_time(): start_time = time.time() return time.time() - start_time def test_timer(timer, n): count = 0 for i in range(n): if timer() == 0: count += 1 return count n_test = 100000 print('{:&gt;6s} / {:&gt;6s}'.format( '# fail', '# test')) print('{:6d} / {:6d}'.format( test_timer(time_perf_counter, n_test), n_test)) print('{:6d} / {:6d}'.format( test_timer(time_time, n_test), n_test)) The results are, for example: # fail / # test 0 / 100000 89109 / 100000 My environments: MBP High Sierra, Python 3.6.3
score: 0

http://stackoverflow.com/a/48023161
score: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/83015933
upvote count: 8
has comment: http://stackoverflow.com/comment/83015855
has comment: http://stackoverflow.com/comment/83015741
answers question: http://stackoverflow.com/q/48023127
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48023127
type: Answer
has body: The threshed is already np.uint8, no change is needed. th, threshed = cv2.threshold(fark, 30, 255, cv2.THRESH_BINARY) print(threshed.dtype, threshed.shape) But when use cv2.imread, default convert to BGR channels. To keep original shape and channels(for grayscale or png with alpha channel): img = cv2.imread("test.png", cv2.IMREAD_UNCHANGED) Or just for gray: img = cv2.imread("test.png", cv2.IMREAD_GRAYSCALE)

http://stackoverflow.com/q/48026478
has body: I have the following code: from xgboost import XGBClassifier print(df_train.shape) print(df_train_labels.shape) clf = clf.fit(df_train, df_train_labels, verbose=True) print("after fit") Here df_train and df_train_labels are pandas which I read from a CSV. The above code prints: (1460, 7) (1460,) However, nothing else is printed for 10 minutes which means the code is stuck at clf.fit so I'm assuming the algorithm shouldn't spend a long time on this. As you can see, there are only 1460 examples, so I'm assuming the algorithm shouldn't spend a long time on this. Furthermore, since I passed verbose=True, I would have expected the model to print some output, but that is not happening. Any idea why there is no output printed and why XGBClassifier takes such a long time?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/138820746
has answer: http://stackoverflow.com/a/63424598
type: Question
upvote count: 12
has answer: http://stackoverflow.com/a/51273499
has title: XGBClassifier is slow and does not print any output despite passing verbose parameter
has answer: http://stackoverflow.com/a/78736591
tagged with: dataframe
score: 12
answer count: 3
downvote count: 0
tagged with: xgboost
favorite count: 0

http://stackoverflow.com/comment/83255827
has text: I think the real issue is the floating point one so no need for an additional answer, edit into yours maybe?
comment on: http://stackoverflow.com/a/48139154
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/comment/83227951
type: AnswerComment
has text: Unfortunately, no. Since I am running my program on a website, the server has everything installed. I am forced to work with 0.19.2.
comment on: http://stackoverflow.com/a/48125588
type: Comment
score: 0

http://stackoverflow.com/q/48058825
downvote count: 1
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/48061741
score: -1
linked to: http://stackoverflow.com/q/3542881
type: Question
tagged with: amazon-sqs
answer count: 2
has body: I have configured event on my bucket, as soon as there is a new object in bucket, it triggers message to as SQS. Key in my bucket looks like '/model/invalid/SourceSystem/20160101/Monthly/SourceSystem/year=2018/month=01/day=02/test.csv' While reading the message from sqs I get the response as '/model/invalid/SourceSystem/20160101/Monthly/SourceSystem/year%3D2018/month%3D01/day%3D02/test.csv As of now I am using python code for replacing %3D with =, however it doesn't seem to be a correct solution fileLocation = fileLocation.replace('%3D', '=')
upvote count: 0
favorite count: 0
has title: Message in sqs contains hex value of "=" instaead of ASCII
tagged with: python
has answer: http://stackoverflow.com/a/48059170
type: UnansweredQuestion

http://stackoverflow.com/a/48158743
upvote count: 2
has comment: http://stackoverflow.com/comment/83321841
has body: If I use a TCP socket in python, I get a timeout error on the connect() call--just like with your iOS code. Here's a python TCP client you can play with: import socket import time s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #SOCK_STREAM =&gt; TCP, SOCK_DGRAM =&gt; UDP s.settimeout(10) s.connect(('192.168.2.131', 8530)) s.send(bytearray.fromhex('01 40')) # to switch 'on' time.sleep(20) Results: ~/python_programs$ p34 1.py Traceback (most recent call last): File "1.py", line 6, in &lt;module&gt; s.connect(('192.168.2.131', 8530)) socket.timeout: timed out Try using the python TCP code with your setup. I'm guessing it won't work because the iOS TCP code wouldn't work. Next, because you said that the python UDP code worked for you, I would try creating a UDP socket with SwiftSocket.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48156294
score: 2
has comment: http://stackoverflow.com/comment/83319735
answers question: http://stackoverflow.com/q/48156294

http://stackoverflow.com/comment/120282442
has text: hi -@cs95 i read your answer which is quite accurate, but i have another question in same scenario, what if i have more than one Text columns in the dataframe, how can we tokenize and pad_sequences those columns and reassign them to the Dataframe again. Here is my question posted, https://stackoverflow.com/questions/67769093/after-tokenize-a-column-of-text-how-to-reassigned-that-tokenized-output-which
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48049425

http://stackoverflow.com/a/48018166
has body: You can use Sympy to solve these equations. Install it if you don't already have it using pip install sympy import sympy in_dict = {"x":2,"y":"x+2","z":"y+2"} x, y, z = sympy.symbols('x y z') sympy.sympify("(x+2)*y/z").evalf(subs={x:in_dict['x'], y:in_dict['y'], z:in_dict['z']}) This will give you output as: 2.66666666666667
answers question: http://stackoverflow.com/q/48017962
downvote count: 0
score: 2
type: Answer
upvote count: 2

http://stackoverflow.com/comment/83032979
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48031337
has text: @kshikama Yes, I created two gmail accounts and I can send with my version 1 code and receive it on my other gmail account. I replace my credentials to "test" in order to protect my password and email address.
score: 0

http://stackoverflow.com/a/48120958
has comment: http://stackoverflow.com/comment/83234098
has comment: http://stackoverflow.com/comment/83227459
has body: Asper the HTML you have provided to click() on the button with text as Connect you can use the following line of code : WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='search-result__actions--primary button-secondary-medium m5' and contains(.,'Connect')]"))).click()
has comment: http://stackoverflow.com/comment/83218968
has comment: http://stackoverflow.com/comment/83234223
has comment: http://stackoverflow.com/comment/83238581
has comment: http://stackoverflow.com/comment/83219581
score: 0
has comment: http://stackoverflow.com/comment/83233986
answers question: http://stackoverflow.com/q/48120556
has comment: http://stackoverflow.com/comment/83234289
type: Answer

http://stackoverflow.com/q/48121126
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/83250619
downvote count: 0
has comment: http://stackoverflow.com/comment/83228544
score: 4
has answer: http://stackoverflow.com/a/48125997
has body: I want to use the Python Console in QGIS to change all attributes in a Shapefile with a certain value. I have a field named "ANB" and I want to change the value "2" in for example "3". I know how to access the layer and select the values I want: layer=QgsVectorLayer("C:.../Briefkasten.shp","briefkasten","ogr") selection=layer.getFeatures(QgsFeatureRequest().setFilterExpression(u' "ANB"=2')) But I don't know how to proceed. Can someone help me? Thank you very much! Greetings Robert
answer count: 1
has comment: http://stackoverflow.com/comment/83220467
favorite count: 0
tagged with: shapefile
has title: How to change an attribute in Shapefile with a certain value with QGIS / Python
has comment: http://stackoverflow.com/comment/83219390
type: UnansweredQuestion
tagged with: qgis
tagged with: python
tagged with: gis

http://stackoverflow.com/q/48113905
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
tagged with: series
tagged with: python
has title: Slice a Pandas Dataframe based on the results of a function on a column
accepted answer: http://stackoverflow.com/a/48113923
downvote count: 0
has answer: http://stackoverflow.com/a/48113923
type: AnsweredQuestion
score: 1
tagged with: dataframe
tagged with: slice
type: Question
has body: I want to slice a dataframe using a condition based on a DateTime column's month, element by element: Met_Monthly_DF = Metsite_DF.iloc[Metsite_DF['DateTime'].month == Month] I get the error: builtins.AttributeError: 'Series' object has no attribute 'month' It works on an element by element basis if I do say: Months = [DT.month for DT in Metsite_DF['DateTime'].tolist()] How do I apply this condition?

http://stackoverflow.com/comment/83021564
comment on: http://stackoverflow.com/a/48017644
type: AnswerComment
score: 0
type: Comment
has text: @Blckknght what do you think in general about your approach in terms of debugging, readability, easy to follow and understand? I saw before this technique many times, but my opinion - it's usually a big pain in really big projects.

http://stackoverflow.com/q/48143566
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83270553
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83270851
downvote count: 1
has comment: http://stackoverflow.com/comment/83288775
has comment: http://stackoverflow.com/comment/83579629
type: Question
upvote count: 10
has comment: http://stackoverflow.com/comment/83270686
score: 9
has comment: http://stackoverflow.com/comment/83564630
has title: bdist_mac cx_freeze with Tkinter and Selenium interaction
favorite count: 0
has comment: http://stackoverflow.com/comment/83547946
has comment: http://stackoverflow.com/comment/83270739
has comment: http://stackoverflow.com/comment/83577495
has comment: http://stackoverflow.com/comment/83270628
has comment: http://stackoverflow.com/comment/83579519
has comment: http://stackoverflow.com/comment/83577910
has comment: http://stackoverflow.com/comment/83285620
has comment: http://stackoverflow.com/comment/83579472
has comment: http://stackoverflow.com/comment/83270526
has comment: http://stackoverflow.com/comment/83577452
has comment: http://stackoverflow.com/comment/83272314
tagged with: python
tagged with: macos
has body: I created a Python 3 application that has a Tkinter GUI and a Selenium action upon clicking a button. I'm compiling it via cx_freeze. Here is the setup.py file: from cx_Freeze import setup, Executable import sys import os from pathlib import Path buildOptions = {"include_files":['execute.py'], "packages": ['encodings'], "includes": ['numpy.core._methods', 'numpy.lib.format'], "excludes": []} if sys.platform=='win32': base = "Win32GUI" else: base=None executables = [ Executable('bot_gui.py', base=base) ] home_path = str(Path.home()) user_txt_path = [] if sys.platform=='win32': print("windows detected") user_txt_path.append('\\user.txt') else: print("macos detected") user_txt_path.append('/user.txt') #for initialization f = open(home_path + user_txt_path[0], "w+") for i in range(12): f.write("---\n") setup(name='tachysloth', version = '1.0', description = 'test', options = dict(build_exe = buildOptions), executables = executables) When I run python setup.py build everything works fine; but when I run python setup.py bdist_mac, the GUI works when you click on the application (called tachysloth-1.0 below). Whe I click on a button to in the GUI to open google.com in Chrome, the button does not do anything. If you need more information to assess this problem, please let me know and I will provide that information as soon as possible.
tagged with: selenium-webdriver
tagged with: python-3.x

http://stackoverflow.com/q/48040346
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83051394
type: Question
has comment: http://stackoverflow.com/comment/83051302
has comment: http://stackoverflow.com/comment/83051381
has comment: http://stackoverflow.com/comment/83051256
tagged with: python
has comment: http://stackoverflow.com/comment/83051326
has comment: http://stackoverflow.com/comment/83051122
has comment: http://stackoverflow.com/comment/83051354
has answer: http://stackoverflow.com/a/48040519
has body: So I'm a newbie to Machine Learning and a little baffled by this error: Shapes (1,4) and (14,14) not aligned: 4 (dim 1) != 14 (dim 0) Here is the full error: File "/Users/jim/anaconda3/lib/python3.6/site-packages/sklearn/utils/extmath.py", line 140, in safe_sparse_dot return np.dot(a, b) ValueError: shapes (1,4) and (14,14) not aligned: 4 (dim 1) != 14 (dim 0) My test set has 4 rows of data and training set 14 rows of data, as indicated by (1,4) and (14,14). At least I think that's what that means. I'm trying to fit a simple linear regression to a Training set as indicated by my code below: # Fit Simple Linear Regression to Training Set from sklearn.linear_model import LinearRegression regressor = LinearRegression() X_train = X_train.reshape(1,-1) y_train = y_train.reshape(1,-1) regressor.fit(X_train, y_train) Then predict the Test Set Results: # Predicting the Test Set Results X_test = X_test.reshape(1,-1) y_pred = regressor.predict(X_test) My code is failing on the last line with the above error: y_pred = regressor.predict(X_test) Any hints in the right direction would be great. Here is my whole code sample: # Simple Linear Regression # Import Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Import dataset dataset = pd.read_csv('NBA.csv') X = dataset.iloc[:, 1].values y = dataset.iloc[:, :-1].values # Splitting the dataset into Train and Test from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Feature Scaling # None # Fit Simple Linear Regression to Training Set from sklearn.linear_model import LinearRegression regressor = LinearRegression() X_train = X_train.reshape(1,-1) y_train = y_train.reshape(1,-1) regressor.fit(X_train, y_train) # Predicting the Test Set Results X_test = X_test.reshape(1,-1) y_pred = regressor.predict(X_test) ** EDIT ** I checked the shape of X and y. Here is my output below: dataset = pd.read_csv('NBA.csv') X =…
tagged with: machine-learning
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83051373
has comment: http://stackoverflow.com/comment/83051142
has title: Error: Shapes (1,4) and (14,14) not aligned
accepted answer: http://stackoverflow.com/a/48040519
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83051191
downvote count: 0
score: 1
tagged with: scikit-learn

http://stackoverflow.com/comment/83241552
has text: Not sure I am following you, because actually I set the index on day and fruits when i create the df with : `set_index(['index', 'Fruit'])`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48131541
type: AnswerComment

http://stackoverflow.com/comment/83239074
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48131072
has text: `l.append("%s=%s" % (attr, value))` chnage to this.
type: Comment

http://stackoverflow.com/comment/83189571
type: AnswerComment
has text: Thank You! I did as you said and I fixed that problem.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48097737

http://stackoverflow.com/comment/83064656
has text: `list.map` does not do what you seem to think it does. It returns a new list by applying your function `get_accomodation_wifi_rating` to every element of `hotels_url_list`. Could you show us `get_accomodation_wifi_rating`? It seems to be returning `None` most of the time.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48046624
score: 0

http://stackoverflow.com/comment/83502005
comment on: http://stackoverflow.com/a/48179931
type: AnswerComment
score: 0
type: Comment
has text: I just tried one word "love" which is not correct. So I think there must be more mistakes. You can test this word of POS verb.

http://stackoverflow.com/comment/83184570
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48104449
has text: Also, `in` is a conditional operator, not a logical operator, so "short circuiting" does not apply here.

http://stackoverflow.com/comment/116850235
type: Comment
comment on: http://stackoverflow.com/a/48122648
type: AnswerComment
score: 0
has text: @JanmejayaNanda, all depends on your environment. Please ask new question with specifications.

http://stackoverflow.com/comment/83099285
type: QuestionComment
comment on: http://stackoverflow.com/q/48062788
type: Comment
has text: @Also, test this on your real data and perform a timing comparison with the other answer...
score: 0

http://stackoverflow.com/a/48172307
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48170703
score: 2
has comment: http://stackoverflow.com/comment/83331624
has comment: http://stackoverflow.com/comment/83362089
downvote count: 0
has body: In working with sparse matrices, changing the sparsity pattern is generally a very expensive operation, and so scipy does not do this silently. If you want to remove explicitly stored zeros from a sparse matrix, you should use the eliminate_zeros() method; for example: &gt;&gt;&gt; M = csr(np.random.random((1000,1000))&gt;0.9, dtype=float) &gt;&gt;&gt; M &lt;1000x1000 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 99740 stored elements in Compressed Sparse Row format&gt; &gt;&gt;&gt; M[:, 0] *= 0 &gt;&gt;&gt; M &lt;1000x1000 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 99740 stored elements in Compressed Sparse Row format&gt; &gt;&gt;&gt; M.eliminate_zeros() &gt;&gt;&gt; M &lt;1000x1000 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 99657 stored elements in Compressed Sparse Row format&gt; Scipy could call the eliminate_zeros routine automatically after doing this kind of operation, but the developers chose to give the user more flexibility and control when doing something as expensive as changing the sparsity structure.
has comment: http://stackoverflow.com/comment/83325365

http://stackoverflow.com/a/48041759
has body: Here is a slightly modified version of your code that appears to work: def mergesortInv(list, mergeInv): if len(list) &lt; 2: return list, 0 else: middle = len(list) // 2 left, lc = mergesortInv(list[:middle], mergeInv) #definim les dues meitats right, rc = mergesortInv(list[middle:], mergeInv) merge, mc = mergeInv(left, right) return merge, lc + rc + mc def mergeInvRec(left, right): if len(left) &lt; 1: return right, 0 if len(right) &lt; 1: return left, 0 if left[0] &lt;= right[0]: res, cnt = mergeInvRec(left[1:], right) return [left[0]] + res, cnt else: res, cnt = mergeInvRec(left, right[1:]) return [right[0]] + res, len(left) + cnt def mergeInvFlat(left, right): res, cnt = [], 0 il, ir = 0, 0 nl, nr = len(left), len(right) while il &lt; nl and ir &lt; nr: if left[il] &lt;= right[ir]: res.append(left[il]) il += 1 else: res.append(right[ir]) ir += 1 cnt += nl - il res.extend(left[il:]) res.extend(right[ir:]) return res, cnt It's mostly a matter of book keeping. Count the number of swaps at each step and add them. In the very last branch the first element of right bubbles all the way past every element of left which is why we tally len(left) swaps there. Edit: As @PM2Ring points out the recursion in mergeInv is a bit reckless and will exceed Python's maximum recursion depth for moderately sized lists. I've added a non-recursive version. You can switch between the recursive and nonrecursive versions by passing their name as the second arg to the main function.
has comment: http://stackoverflow.com/comment/83054725
score: 3
has comment: http://stackoverflow.com/comment/83055125
answers question: http://stackoverflow.com/q/48041639
has comment: http://stackoverflow.com/comment/83054268
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83054446
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48041639
has comment: http://stackoverflow.com/comment/83054117
upvote count: 3
has comment: http://stackoverflow.com/comment/83054890

http://stackoverflow.com/a/48052730
downvote count: 0
has body: You should take a look at String Literal document, which says: The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter r' orR'; such strings are called raw strings and use different rules for backslash escape sequences. In your example string, \t are not two characters but a single character which represents ASCII Horizontal Tab (TAB). In order to tell your Python interpreter that these two are separate character, you should be using raw string (using r before string "")as: &gt;&gt;&gt; list(r" Hello \t World.") [' ', ' ', ' ', ' ', 'H', 'e', 'l', 'l', 'o', ' ', '\\', 't', ' ', 'W', 'o', 'r', 'l', 'd', '.'] But here also you'll see two \\ in the resultant list, which is just a Python's way of representing \. For Python interpreter '\' is an invalid string because \' in a string represent Single quote ('). Hence, when you do '\', it raises below error because for Python there is no end quote present in the string: &gt;&gt;&gt; '\' File "&lt;stdin&gt;", line 1 '\' ^ SyntaxError: EOL while scanning string literal If you can't declare your string as raw string (as it's already defined or imported from some other source), you may convert it to byte string by setting encoding as "unicode-escape": &gt;&gt;&gt; my_str = " Hello \t World." &gt;&gt;&gt; unicode_escaped_string = my_str.encode('unicode-escape') &gt;&gt;&gt; unicode_escaped_string b' Hello \\t World.' Since it is a byte-string, you need to call chr to get the corresponding character value of each byte. For example: &gt;&gt;&gt; list(map(chr, unicode_escaped_string)) [' ', ' ', ' ', ' ', 'H', 'e', 'l', 'l', 'o', ' ', '\\', 't', ' ', 'W', 'o', 'r', 'l', 'd', '.']
type: Answer
upvote count: 5
answers question: http://stackoverflow.com/q/48052657
score: 5

http://stackoverflow.com/q/48068817
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83111399
has answer: http://stackoverflow.com/a/48070083
has comment: http://stackoverflow.com/comment/83111419
type: UnansweredQuestion
type: Question
has title: AttributeError: type object 'Level' has no attribute 'platform_list'
has body: I'm developing a platformer game for this I have tried to develop a level class however I keep on getting the error 'AttributeError: type object 'Level' has no attribute 'platform_list' I cannot identify the problem, I have taken some of the code which I feel is the area as to where the error triggers from is it possible to help? 'line 214, in current_level.update(LVL)', 'line70,in update self.platform_list.update()' class Level(object): def __init__(self, Sprite): """ Constructor. Pass in a handle to player. Needed for when moving platforms collide with the player. """ self.platform_list = pygame.sprite.Group() self.enemy_list = pygame.sprite.Group() self.sprite = Sprite self.background = None def update(self): """ Update everything in this level.""" self.platform_list.update() self.enemy_list.update() def draw(self, DS): """ Draw everything on this level. """ # Draw all the sprite lists that we have self.platform_list.draw(DS) self.enemy_list.draw(DS) LVL = Level sprite = Sprite([400, 550]) level_list = [] level_list.append(Level_01) # Set the current level current_level_no = 0 current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() sprite.level = current_level sprite.rect.x = 340 sprite.rect.y = H - sprite.rect.height active_sprite_list.add(sprite) # Loop until the user clicks the close button. done = False while not done: events() for event in pygame.event.get(): if event.type == pygame.QUIT: done = True key = pygame.key.get_pressed() if key == [pygame.K_RIGHT]: sprite.go_right() if key == [pygame.K_LEFT]: sprite.go_left() if key == [pygame.K_UP]: sprite.jump() # If the player gets near the right side, shift the world left (-x) if sprite.rect.right &gt; W: sprite.rect.right = W # If the player gets near the left side, shift the world right (+x) if sprite.rect.left &lt; 0: sprite.rect.left = 0 current_level.draw(DS) active_sprite_list.draw(DS) # Call the `update` method of the sprite to move it. sprite.update() # Update the player.…
answer count: 1

http://stackoverflow.com/comment/83030372
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48030079
type: Comment
has text: Add break statements after every time you set the price variable.. if you need to type 'quit' as your age to make the loop break, this will always break the line `age = int(age)` so this code will never work properly

http://stackoverflow.com/q/48111404
downvote count: 0
tagged with: pandas-groupby
tagged with: pandas
has title: Pandas groupby column1 apply max on column2 and corresponding value of column3 in result
has body: I have the following dataframe: d = {'item_code': ['Item1', 'Item2', 'Item3', 'Item1', 'Item2', 'Item2', 'Item2', 'Item1', 'Item3'], 'dollar_amount': ['200.25', '350.00', '120.00', '400.50', '1231.25', '700.00', '350.00', '200.25', '2340.00'], 'year': ['2010','2010','2010','2011','2011','2012','2012','2012','2012']} df = pd.DataFrame(data=d) df dollar_amount item_code year 0 200.25 Item1 2010 1 350.00 Item2 2010 2 120.00 Item3 2010 3 400.50 Item1 2011 4 1231.25 Item1 2011 5 700.00 Item2 2012 6 350.00 Item2 2012 7 200.25 Item1 2012 8 2340.00 Item3 2012 This is what I currently have: df['dollar_amount'] = df['dollar_amount'].astype(float) df.groupby('year', as_index=False).agg({'dollar_amount':'max'}) It gives me the following result: year dollar_amount 0 2010 350.0000 1 2011 1,231.2500 2 2012 2,340.0000 I want to groupby year and find the maximum dollar_amount in that year and also get the corresponding item_code for that maximum dollar_amount. So the expected outcome is something like this: year dollar_amount item_code 0 2010 350.0000 item2 1 2011 1,231.2500 item2 2 2012 2,340.0000 item3
favorite count: 0
linked to: http://stackoverflow.com/q/32459325
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: dataframe
has comment: http://stackoverflow.com/comment/83199140
type: Question
duplicate of: http://stackoverflow.com/q/32459325

http://stackoverflow.com/q/48170761
has answer: http://stackoverflow.com/a/58839235
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/58839235
tagged with: grpc
score: 7
accepted answer: http://stackoverflow.com/a/48171005
upvote count: 7
type: Question
linked to: http://stackoverflow.com/q/42629047
has title: How do I specify server options?
downvote count: 0
has answer: http://stackoverflow.com/a/51836224
has body: I'm trying to run gRPC server in Python. I found a way to do it like this: import grpc from concurrent import futures server = grpc.server(futures.ThreadPoolExecutor(max_workers=100)) ... # add my grpc servicer to server server.add_insecure_port('[::]:50051') server.start() I need to add some options to the server like max_send_message_length, max_receive_message_length, etc. There is an options argument in grpc.server(...), but I can't figure out how to use it. server = grpc.server(futures.ThreadPoolExecutor(max_workers=100), options=[???]) From gRPC documentation: options – An optional list of key-value pairs (channel args in gRPC runtime) to configure the channel. How do I create these options? Are they string-string pairs? I'm new to Python and gRPC, though.
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/48171005

http://stackoverflow.com/comment/83043550
type: QuestionComment
comment on: http://stackoverflow.com/q/48036690
has text: If you look a the networkx code you should be able to see how it stores its edges... whether it implies any ordering to an adjacency list or uses something else will provide more details...
score: 0
type: Comment

http://stackoverflow.com/comment/83047113
has text: Yes, you're right! I guess when I was doing the refactoring when I had the app named as auth PyCharm just replaced it with oauth when I changed the app name again
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48038337

http://stackoverflow.com/comment/83117654
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48071858
has text: Thanks @Alexander, but I am very new to Python and doing the MITx course currently on Python. So, I am not very well acquainted with enumerate function. Can you shed some more light on it?
score: 0

http://stackoverflow.com/a/48085626
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48085512
has body: As John Gordon stated in comments, the simplest way to do it would probably be like so: l = list("he'llo") l[1] += l[2] del l[2]
downvote count: 0
type: Answer

http://stackoverflow.com/comment/86231959
score: 0
has text: I'm having the same problem and found by debbuging the fromHTML code that svg Elements were returning an ``SVGAnimatedString`` as their ``className``!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48136491

http://stackoverflow.com/comment/83000025
comment on: http://stackoverflow.com/q/48015368
type: Comment
has text: `Product.objects.filter(car__isnull=False)` will give you all Car Products.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48062610
upvote count: 2
has body: I do not completely understand why this happens but I found what causes the problem and a solution: If we look at the column labels we can see something weird &gt;&gt;&gt; df = pd.read_csv(StringIO(txt),header=[0,1],na_values=['-1','']) &gt;&gt;&gt; df.columns MultiIndex(levels=[['Age', 'Height', 'Name'], ['Metres', 'Unnamed: 0_level_1', 'Unnamed: 2_level_1']], labels=[[2, 1, 0], [1, 0, 2]]) The indices of the second level don't match the indices of the first layer. And when you replace the strings you do that on the array that is in the correct order: &gt;&gt;&gt; df.columns.get_level_values(level=1) Index(['Unnamed: 0_level_1', 'Metres', 'Unnamed: 2_level_1'], dtype='object') But you can get the array that's in the incorrect order just by indexing: &gt;&gt;&gt; df.columns.levels[1] Index(['Metres', 'Unnamed: 0_level_1', 'Unnamed: 2_level_1'], dtype='object') So to remove the Unnamed indices: &gt;&gt;&gt; df.columns = df.columns.set_levels(df.columns.levels[1].str.replace('Un.*', ''), level=1) &gt;&gt;&gt; df Name Height Age Metres 0 A NaN 25.0 1 B 95.0 NaN However I would love for someone to point out why using the get_ and set_levels has this behavior.
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83098324
accepted answer of: http://stackoverflow.com/q/48061197
type: Answer
answers question: http://stackoverflow.com/q/48061197
has comment: http://stackoverflow.com/comment/83097982

http://stackoverflow.com/comment/83209650
comment on: http://stackoverflow.com/a/48116431
type: Comment
has text: I guess this is not the issue. Is not a slow delete. I guess django is still copying file. May be all space allocated ( it seems file is there ) but not content.
score: 0
type: AnswerComment

http://stackoverflow.com/a/48142770
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48136092
type: Answer
answers question: http://stackoverflow.com/q/48136092
upvote count: 1
score: 1
has body: This answer on the github issues page fixed the problem. https://github.com/chezou/tabula-py/issues/54 sudo mv /usr/bin/java /usr/bin/java-1.6 sudo ln -s /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java

http://stackoverflow.com/comment/83029301
type: QuestionComment
comment on: http://stackoverflow.com/q/48029517
type: Comment
score: 2
has text: Your sample data is not consistent with your description.

http://stackoverflow.com/a/48090953
type: Answer
answers question: http://stackoverflow.com/q/48090755
score: 0
has body: There is a loooot of weird stuff you can do with Python. One that comes to mind is using getattr (to fetch an attribute from a string representing its name) and setattr (to write an attribute using its name) Check this out: class Person(object): def __init__(self): self.a1 = 0 self.a2 = 1 self.a3 = 2 def method(self, attr_name): new_value = getattr(self, attr_name) * 2 setattr(self, attr_name, new_value) print(getattr(self, attr_name)) if __name__ == "__main__": pers = Person() pers.method('a1') pers.method('a2') pers.method('a3') Outputs: 0 2 4 However: You should also consider readability: Sometimes writing a bit more can make other people who read your code understand it much better. Abusing things like this can make the code very confusing very fast.

http://stackoverflow.com/comment/83103208
type: Comment
type: QuestionComment
has text: Deleting from the list you're iterating over is usually a recipe for disaster.
comment on: http://stackoverflow.com/q/48065019
score: 0

http://stackoverflow.com/comment/83093251
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48060345
has text: Yes. Why does that surprise you?
score: 1

http://stackoverflow.com/q/48153267
type: Question
score: 3
linked to: http://stackoverflow.com/q/40963347
has title: Mean of every 3 columns pandas
duplicate of: http://stackoverflow.com/q/40963347
has body: I have a DataFrame that looks like this: 2016-01 2016-02 2016-03 2016-04 2016-05 2016-06 .... name John 1000 1500 1800 2000 1600 1000 Except it has 10730 entries. What i would want is to have a new DataFrame with the mean of every quarter of the year (3 months). for example: 2016q1 2016q2 ..... John 143.333 1533.333 My solution to this is horrible and taking too much time, so anything is better. Thanks!
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48153520
favorite count: 0
tagged with: pandas
tagged with: python
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/48153520

http://stackoverflow.com/q/48054114
has title: Graph and Dijkstra in python
has comment: http://stackoverflow.com/comment/83089079
tagged with: dijkstra
type: Question
has comment: http://stackoverflow.com/comment/83080783
score: 0
has body: As another homework I have to do a Dijsktra's algorithm, but I'm not sure how to create a graph and if my implementation is right. I have to use a given pattern that look like this: class Vertex: def __init__(self, id, name): self.id = id self.name = name self.minDistance = None self.previousVertex = None self.edges = [] class Edge: def __init__(self, source, target, weight): self.source = source self.target = target self.weight = weight class Dijkstra: def __init__(self): self.vertexes = Vertex def createGraph(self, vertexes, edgesToVertexes): pass def getVertexes(self): pass def computePath(self, sourceId): pass def getShortestPathTo(self, targetId): pass def resetDijkstra(self): pass While calling a createGraph function it gives me two arrays: vertexes &amp; edgesToVertexes containing Vertexes and Edges. So how do I exactly extract data from these arrays and Initialize them as objects into both classes?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83080745
answer count: 0

http://stackoverflow.com/comment/83088046
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48057869
has text: An item is different from a widget, when in the documentation it refers to an item it is understood as QTableWidgetItem. :P
score: 0

http://stackoverflow.com/comment/83183434
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48103485
has text: @JonClements i've edited to clarify
score: 0

http://stackoverflow.com/a/50798412
type: Answer
downvote count: 0
score: 5
answers question: http://stackoverflow.com/q/48015074
has body: I've looked for the answer to this question on many pages and none of them worked until I found the one that releases the AJAX call so that the rerender is allowed to take place: $('form').on('submit', function(event) { $.ajax({ type: 'POST', url: "{{ url_for( 'myServerFunction' ) }}", data: JSON.stringify({'myId':bunchOfIds}), contentType: "application/json", success:function(response){ document.write(response); } }) The most important line is the success line that releases the document so that it can be rerendered.
upvote count: 5

http://stackoverflow.com/q/48062663
has comment: http://stackoverflow.com/comment/83098274
has title: Python Packaging and Resources
score: 0
answer count: 1
tagged with: user-interface
has body: Okay so I have been having trouble creating python.exe and running them on other computers. Does anyone have good resources on what executable converter to use and any other good tips. So far I have been using pyinstaller and I can run standalone scripts but not GUI applications.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48062709
type: Question
has comment: http://stackoverflow.com/comment/83098282

http://stackoverflow.com/comment/83321038
score: 0
type: Comment
type: QuestionComment
has text: If any topic (other than `None`) is to be accepted, what is the purpose of checking its value? Just use it after verifying that it isn't `None`. The only thing I can imagine is that you have a specific set of valid topics that you want `topic` to belong to: `if topic in valid_topics or topic == message.topic` (where `message.topic` is assumed to *not* necessarily be a member of `valid_topics`).
comment on: http://stackoverflow.com/q/48170638

http://stackoverflow.com/a/48042289
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48042187
has body: Since you can have only 256 different strings (because you only have 256 distinct integers), one approach would be to store the strings in a list. When you want to construct the JSON file, look the string up in the list and use its index in the JSON file. When you read an incoming JSON file, use the index in it to retrieve the correct string from the list.

http://stackoverflow.com/comment/83177708
has text: Fabulous! Thank you very much for your help. I had realized that I needed to give the widget a layout earlier, but I was missing the critical step of adding the canvas to that layout.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48099734

http://stackoverflow.com/a/48124628
has body: What you're looking for is the composition of all of your conditions with a bit-wise logical or. You can achieve this with a numpy.logical_or.reduce: import numpy as np conditions = [ df['Associated_word'].isnull(), df['Text'].isnumeric(), df['Text'].str.len() == 1 ] df = df[np.logical_or.reduce(conditions)]
answers question: http://stackoverflow.com/q/48124149
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48124149

http://stackoverflow.com/comment/83013147
score: 0
type: Comment
type: QuestionComment
has text: Related: https://stackoverflow.com/questions/18655648/what-exactly-is-the-point-of-memoryview-in-python
comment on: http://stackoverflow.com/q/48021949

http://stackoverflow.com/a/51788901
upvote count: 1
score: 1
downvote count: 0
has body: Need some refactoring, but works. Just add values to dictionary, for example x.name: x.make_dict() for every element. import logging import copy import connect logger = logging.getLogger('importer') class DriveObj(): def __init__(self, drive_obj): self.id = drive_obj.get('id') self.name = drive_obj.get('name') def make_dict(self): props = copy.deepcopy(vars(self)) del props['name'] return props @property def parents(self): try: return service.files().get(fileId=self.id, fields='parents').execute()['parents'] except KeyError: return [] class Directory(DriveObj): def __init__(self, drive_obj): super().__init__(drive_obj) self.mimeType = 'application/vnd.google-apps.folder' assert drive_obj.get('mimeType') == self.mimeType, 'Not dir :(' self.children = [] def add_content(self, drive_obj): self.children.append(drive_obj) class Document(DriveObj): def __init__(self, drive_obj): super().__init__(drive_obj) assert 'vnd.google-apps.folder' not in drive_obj.get('mimeType') self.mimeType = drive_obj.get('mimeType') def get_filelist(service): return service.files().list().execute() def get_content(service): content = list() for drive_obj in get_filelist(service)['files']: try: content.append(Directory(drive_obj)) except AssertionError: content.append(Document(drive_obj)) return content def find_id(content, id): for drive_obj in content: logger.debug('Got {}'.format(drive_obj.id)) if drive_obj.id == id: logger.debug('Find id in {}'.format(drive_obj.id)) return drive_obj elif type(drive_obj) == Directory and drive_obj.children: logger.debug('{} has children'.format(drive_obj.id)) result = find_id(drive_obj.children, id) if result: return result def create_corr_structure(content): for obj in content: if obj.parents: for parent in obj.parents: parent_obj = find_id(content, parent) if parent_obj: parent_obj.add_content(obj) else: logger.debug( 'There is no parent directory for {}'.format(obj.name)) content[:] = [value for value in content if not value.parents] if __name__ == "__mai…
type: Answer
answers question: http://stackoverflow.com/q/48112412

http://stackoverflow.com/comment/83159765
type: QuestionComment
comment on: http://stackoverflow.com/q/48092433
has text: output varaible/ dependent variable that you want to predict.
score: 0
type: Comment

http://stackoverflow.com/a/48480841
has body: It seem's that in your __init__ function, your sigma_ind parameter has default value of None which would be a problem in case that you don't pass sigma_ind during initialization because scipy.linalg.cholesky expect value.
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84135439
type: Answer
answers question: http://stackoverflow.com/q/48032834
score: 2

http://stackoverflow.com/comment/82998454
type: QuestionComment
has text: Use a separate file containing the links?
comment on: http://stackoverflow.com/q/48014693
score: 0
type: Comment

http://stackoverflow.com/a/79207631
score: 0
type: Answer
has body: # create a line geometry using shapely line = shapely.geometry.LineString([p1, p2]) # combine shapes into a geometrycollection gc = shapely.geometry.collection.GeometryCollection([line, p1, p2]) from fastkml import KML from fastkml import Placemark pm = Placemark(geometry=gc) k = KML(features=[pm]) more in the documentation
answers question: http://stackoverflow.com/q/48096059

http://stackoverflow.com/q/48145027
accepted answer: http://stackoverflow.com/a/48145353
has answer: http://stackoverflow.com/a/48145069
has answer: http://stackoverflow.com/a/48145078
answer count: 4
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48146359
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83268140
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/48145353
tagged with: python
has title: Pandas Set Data Type While Combining Files
has body: I used below codes to combine a bunch of csv files. There is a column [UPC] start with 000000. Pandas detect the UPC as numeric value so all leading zeroes are ignored. import pandas as pd file_ptn = os.path.join('nielsen_sku_fact*.csv') files = glob.glob(file_ptn) sch_inx = [ '[All Markets]', '[All Periods]', '[UPC]' ] df = reduce(lambda left,right: pd.DataFrame.combine_first(left,right), [pd.read_csv(f,index_col=sch_inx) for f in files]) The challenge is that [UPC] needs to be set as index in order to combine all files into the same schema. I prefer to use combine_first method for code elegance purposes; so no need to suggest a different merge/combine method other than combine_first.
upvote count: 2
possible better answer: http://stackoverflow.com/a/48145069

http://stackoverflow.com/q/48038148
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83046704
accepted answer: http://stackoverflow.com/a/48038331
type: AnsweredQuestion
score: 1
has body: Below is the data set I have col1 | col2 | col3 E | 1.2| 1.1 E | 2.5 | 1.5 E | 3.4 | 7.2 T | 1.0 |5.4 T | 2.1 | 1.2 What I want is a fourth col based on the above cols, so if col1 == 'E' then col4 will take col2 value and if col1 =='T', then col4 will take col3 value. I have tried loops and np.where but nothing is working and I am constantly getting only value for col2. which is wrong where col1 is T. This is one of the last pieces of code I tried, but failed: col4= [] for i in range(0,len(data_set['col1'])): try: subdf = data_set['col1'].loc[(data_set['col1']=='E')] curve = data_set['col2'] print(curve) except: subdf = data_set.loc[(data_set['col1']=='T')] curve =data_set['col3'] print(curve)
has answer: http://stackoverflow.com/a/48038331
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83046645
has comment: http://stackoverflow.com/comment/83046716
has comment: http://stackoverflow.com/comment/83046682
has comment: http://stackoverflow.com/comment/83046744
tagged with: python-3.x
has title: Create a fourth col based on three other cols in Python

http://stackoverflow.com/q/48081412
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48082117
has title: Weighting Data Using Numpy
has body: My data looks like: list=[44359, 16610, 8364, ..., 1, 1, 1] For each element in list I want to take i*([i+1]+[i-1])/2, where i is an element in the list, and i+1 and i-1 are the adjacent elements. For some reason I cannot seem to do this cleanly in NumPy. Here's what I've tried: weights=[] weights.append(1) for i in range(len(hoff[3])-1): weights.append((hoff[3][i-1]+hoff[3][i+1])/2) Where I append 1 to the weights list so that lengths will match at the end. I arbitrarily picked 1, I'm not sure how to deal with the leftmost and rightmost points either.
accepted answer: http://stackoverflow.com/a/48082117
linked to: http://stackoverflow.com/q/5715220
has comment: http://stackoverflow.com/comment/83137068
type: Question
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/48081648
score: 0
has answer: http://stackoverflow.com/a/48081648
has comment: http://stackoverflow.com/comment/83137092
tagged with: average
tagged with: numpy
has comment: http://stackoverflow.com/comment/83137196

http://stackoverflow.com/a/48161529
has body: Your problem is here: style = document.styles['Normal'] font = style.font A style applies to all paragraphs that have that style. It's a document global thing. So any change you make the style.font affect all paragraphs with that style (which is all your paragraphs in this case). Make sure you read this page in the documentation and the one that follows it: http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html Character formatting (e.g. bold, size, typeface) happens at the run level (below paragraph, a paragraph is composed of runs). So if you want to apply character formatting directly, as opposed to by using a style, you need to do it to each run. Adding content to a paragraph by calling document.add_paragraph(content) places all that content in a single run. So a quick fix might be: font = paragraph.runs[0].font Might be worth a try. But probably also a good idea to spend a little time with the concepts parts of the documentation to understand the Word object model a bit better. It's pretty complex for what seems on the surface to be a simple thing. This page is a good place to start: http://python-docx.readthedocs.io/en/latest/user/text.html
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48150222
downvote count: 0
score: 1

http://stackoverflow.com/comment/83095106
has text: This may solve the immediate error but it's not the correct solution to the problem. SQL should never be built from strings. Parameters should be used in all cases. When parameters are used, no manipulation of values is necessary.
type: AnswerComment
comment on: http://stackoverflow.com/a/48061199
type: Comment
score: 1

http://stackoverflow.com/a/48157199
has comment: http://stackoverflow.com/comment/83327721
upvote count: 4
has comment: http://stackoverflow.com/comment/83537715
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83328203
score: 4
has comment: http://stackoverflow.com/comment/83330404
type: Answer
answers question: http://stackoverflow.com/q/48156847
has comment: http://stackoverflow.com/comment/83328921
has body: The task of selecting the number of components to model a distribution with a Gaussian mixture model is an instance of Model Selection. This is not so straightforward and there exist many approaches. A good summary can be found here https://en.m.wikipedia.org/wiki/Model_selection . One of the simplest and most widely used is to perform cross validation. Normally outliers can be determined as those belonging to the component or components with the largest variance. You would call this strategy an unsupervised approach, however it can still be difficult to decide what the cutoff variance should be. A better approach (if applicable) is a supervised approach where you would train the GMM with outlier-free data (by manually removing outliers). You then use this to classify outliers as those which have particularly low likelihood scores. The second way to do it with a supervised approach would be to train two GMMs (one for outliers and one for inliers using model selection) then perform two-class classification for new data. Regarding your question about training univariate versus multivariate GMMs - it's difficult to say but for the purposes of outlier detection univariate GMMs ( or equivalently multivariate GMMs with diagonal covariance matrices) may be sufficient and require training fewer parameters compared to general multivariate GMMs, so I would start with that.
accepted answer of: http://stackoverflow.com/q/48156847

http://stackoverflow.com/q/48039787
tagged with: model
tagged with: field
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83050969
tagged with: python
has title: Update model with newly added field/column
linked to: http://stackoverflow.com/q/44732427
type: Question
has comment: http://stackoverflow.com/comment/83051053
answer count: 2
has body: Python app, using peewee to work with SQLite databases. I have this model containing one field: class RepUser(Model): user = BigIntegerField() And I update the database schema using a migrator like this: new_field = IntegerField(null=True) migrate(migrator.add_column('repuser', 'abc', new_field)) I expected that the model would update its fields to accomodate for the extra field being inserted, but it does not. For example, this gives a KeyError: model_instance.abc = 42 The goal is to be able to dynamically add and remove fields, and have the model update so they can be used. I found a related question here: Update existing table/model column/fields? The top answer says the model has to be updated as well after adding fields to the database schema, but I am not sure how to do this, and I can't find related information in the documentation. Thanks in advance for any help.
tagged with: peewee
score: 0
has answer: http://stackoverflow.com/a/48211407
has answer: http://stackoverflow.com/a/48040854
tagged with: migrate

ctypes
tags question: http://stackoverflow.com/q/48046378
tags question: http://stackoverflow.com/q/48070278
tags question: http://stackoverflow.com/q/48122238
tags question: http://stackoverflow.com/q/48067160
tags question: http://stackoverflow.com/q/48067886
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/48029901
tags question: http://stackoverflow.com/q/48133900
tags question: http://stackoverflow.com/q/48122588

http://stackoverflow.com/q/48091123
answer count: 6
has answer: http://stackoverflow.com/a/48091222
has answer: http://stackoverflow.com/a/48092255
has answer: http://stackoverflow.com/a/48091658
accepted answer: http://stackoverflow.com/a/48091181
tagged with: python
has body: I have the following dictionary, &gt;&gt;&gt; names {1: ('c1', 1), 2: ('c2', 2), 3: ('c1', 3), 4: ('c2', 4)} What is the best way to eliminate keys with duplicate entries based on the first entry in the value i.e 1 and 3 are duplicates because of 'c1' and 2 and 4 are duplicates because of 'c2'? I would like the final output to be something like this &gt;&gt;&gt; uniqueNames {1: ('c1', 1), 2: ('c2', 2) }
favorite count: 0
has answer: http://stackoverflow.com/a/48091311
has answer: http://stackoverflow.com/a/48091181
upvote count: 1
has comment: http://stackoverflow.com/comment/83156540
possible better answer: http://stackoverflow.com/a/48091222
has answer: http://stackoverflow.com/a/48091195
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83158032
score: 1
has title: Eliminating duplicate valued key from a dict
has comment: http://stackoverflow.com/comment/83156521
type: Question
downvote count: 0

http://stackoverflow.com/comment/83190850
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48069740
has text: If you don't mind my asking, what should the `"python.linting.flake8Path"` be set to? I found one example that lists `c:\something\something\flake8.exe`, but pip installs a directory of Python files, not an .exe. Setting it to `c:\Users\Mike\AppData\Roaming\Python\Python36\site-packages\flake8` didn't seem to work, either.

http://stackoverflow.com/comment/83240894
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48131491
has text: Unfortunately I have learned that also but when too late into my project. But for next time, what interface Python library would you recommend?
type: AnswerComment

http://stackoverflow.com/q/48155356
tagged with: network-programming
has comment: http://stackoverflow.com/comment/83289712
has body: I have written a linux server receiving packets on a specific Ethernet-type (using a raw socket), and sending them on a different ethernet device. The thing is, the rate I need to receive the packets, is greater then the rate I can send them to the other interface. So I'm using the socket buffer, untill it gets full, and then I expect packets drop. I have set the buffer size using setsockopt(socket, SOL_SOCKET, RECVBUF, 20 * 1024 * 1024) And validating using getsockopt, I do see the socket was configured correctly. The thing is I start do drop packets much faster then I expected (nearly 10 times) What I want to do, is get the amount of packets in the socket buffer, that I will be able to print the time left untill it is full. (The server is written in Python, yet I would be able to "translate" from other languages)
score: 0
has comment: http://stackoverflow.com/comment/83290360
tagged with: linux
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has comment: http://stackoverflow.com/comment/83289855
has comment: http://stackoverflow.com/comment/83289898
answer count: 0
has title: How to check the amount of packets in a receive buffer of a raw socket
has comment: http://stackoverflow.com/comment/83290248
type: Question

http://stackoverflow.com/q/48115159
answer count: 0
tagged with: matplotlib
has title: Contour plot on 2 parameter data in python
linked to: http://stackoverflow.com/q/41897544
type: Question
has body: Hi I have a numpy object with shape (1000,3) that I wish do a contour plot of. The first two columns represent x and y values and the 3rd is the associated density value at the the point denoted by the x and y values. These are NOT evenly spaced as the x and y values were generated by MCMC sampling methods. I wish to plot the x and y values and demarcate points which have density at a certain level. I have tried calling the contour function but it does not appear to work. presuming I have a data object such that np.shape(data) gives (1000,3) plt.figure() contour(data[:,0],data[:,1],data[:,2]) plt.show() this does not seem to work and gives the following error TypeError: Input z must be a 2D array I understand z, the 3rd column needs to be some sort of meshgrid, but the all the examples I have seen seen to rely on constructing one from evenly spaced x and y which I do not have. Help appreciated on how I can resolve this. EDIT: I have figured it out. Need to use the method for unevenly spaced points as described here. https://matplotlib.org/devdocs/gallery/images_contours_and_fields/griddata_demo.html#sphx-glr-gallery-images-contours-and-fields-griddata-demo-py
has comment: http://stackoverflow.com/comment/83206869
has comment: http://stackoverflow.com/comment/83207630
score: 0
has comment: http://stackoverflow.com/comment/83208356
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83206826
tagged with: python

http://stackoverflow.com/a/48188287
answers question: http://stackoverflow.com/q/48133645
upvote count: 2
type: Answer
score: 2
has body: You absolutely don't need to (and shouldn't try to) decompress or modify the sparse matrix. Your problem is most probably that you are using fit_transform() instead of transform(). Try this: vectorizer = TfidfVectorizer(max_features = 5000) vectorizer.fit(X_train) Xtrain = vectorizer.transform(X_train) Xtest = vectorizer.transform(X_test) Generally speaking, you should always fit() once, and then transform() as much as you need.
downvote count: 0

http://stackoverflow.com/comment/83261648
has text: I prefer `unittest` as you can do more elaborate tests and as well handling those, furthermore every test can have a `setup` phase, which in you phase could be creating a fresh maya scene.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48141755
score: 0

http://stackoverflow.com/comment/83241818
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48131867
has text: Are you using a virtual environment?
score: 0

http://stackoverflow.com/q/48028698
tagged with: self
has body: my program should after click roll dice - it use six images of dice, with one, two, three, four, five and six dots. First is showed image with one dot and than after click on the image should randomly change 8 times. In the end, last random image should stay on screen, but it doesn't work and I am not able to solve it. Any idea how to fix it please? (I know that 3 classes are not necessary for this, but i will continue in it when I'll have soluted this problem) Thanks import tkinter, random class Main: def __init__(self, area, dice): dice.throw(area) class Area: def __init__(self): self.canvas = tkinter.Canvas(width=1000, height=600) self.canvas.pack() self.dice1 = tkinter.PhotoImage(file='numberOne.png') self.canvas.create_image(680,540,image=self.dice1) self.canvas.bind('&lt;Button-1&gt;', Dice.throw) class Dice: def throw(event): if event.x &lt; 730 and event.x &gt; 630 and event.y &lt; 590 and event.y &gt; 490: dice1 = tkinter.PhotoImage(file='numberOne.png') dice2 = tkinter.PhotoImage(file='numberTwo.png') dice3 = tkinter.PhotoImage(file='numberThree.png') dice4 = tkinter.PhotoImage(file='numberFour.png') dice5 = tkinter.PhotoImage(file='numberFive.png') dice6 = tkinter.PhotoImage(file='numberSix.png') for i in range(8): number = random.randrange(6) + 1 if number == 1: area.canvas.create_image(680,540,image=dice1) elif number == 2: area.canvas.create_image(680,540,image=dice2) elif number == 3: area.canvas.create_image(680,540,image=dice3) elif number == 4: area.canvas.create_image(680,540,image=dice4) elif number == 5: area.canvas.create_image(680,540,image=dice5) elif number == 6: area.canvas.create_image(680,540,image=dice6) area.canvas.after(100) area.canvas.update() pl = Area() dice = Dice() main = Main(pl, dice)
tagged with: python
has answer: http://stackoverflow.com/a/48030289
type: AnsweredQuestion
tagged with: tkinter
possible better answer: http://stackoverflow.com/a/64514753
has title: Python - Object oriented function in tkinter with event of click
has comment: http://stackoverflow.com/comment/83027586
type: Question
has comment: http://stackoverflow.com/comment/83030499
has answer: http://stackoverflow.com/a/64514753
score: 0
answer count: 2
tagged with: events
accepted answer: http://stackoverflow.com/a/48030289
has comment: http://stackoverflow.com/comment/83027956

http://stackoverflow.com/q/48132036
has comment: http://stackoverflow.com/comment/91803846
type: Question
has answer: http://stackoverflow.com/a/74849425
has body: My Editor is PyCharm 2017.3 and my Python version is 3.4. I trying to translate the word clicked on my application from english to hindi. This application scraps words from a site and lists it.Everything is working fine with this application except the translation feature. I have just installed googletrans library but it is giving me error that goes like max no of retries exceeded. def translate(self): translate=Translator() translate.translate(self._word, dest="hi",src="en") Here is my translate function and here is the documentation I am referring to. This is my Error showing in console. Traceback (most recent call last): File "C:\Python34\lib\site-packages\urllib3\connectionpool.py", line 601, in urlopen chunked=chunked) File "C:\Python34\lib\site-packages\urllib3\connectionpool.py", line 346, in _make_request self._validate_conn(conn) File "C:\Python34\lib\site-packages\urllib3\connectionpool.py", line 850, in _validate_conn conn.connect() File "C:\Python34\lib\site-packages\urllib3\connection.py", line 326, in connect ssl_context=context) File "C:\Python34\lib\site-packages\urllib3\util\ssl_.py", line 329, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "C:\Python34\Lib\ssl.py", line 344, in wrap_socket _context=self) File "C:\Python34\Lib\ssl.py", line 540, in __init__ self.do_handshake() File "C:\Python34\Lib\ssl.py", line 767, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python34\lib\site-packages\requests\adapters.py", line 440, in send timeout=timeout File "C:\Python34\lib\site-packages\urllib3\connectionpool.py", line 639, in urlopen _stacktrace=sys.exc_info()[2]) File "C:\Python34\lib\site-packages\urllib3\util\retry.py", line 388, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.excep…
tagged with: google-translate
tagged with: urllib
upvote count: 4
has comment: http://stackoverflow.com/comment/91804280
has title: Python module googletrans throwing "Max retries exceeded with url: /" error
has comment: http://stackoverflow.com/comment/99933565
answer count: 1
downvote count: 0
score: 4
favorite count: 0
tagged with: urllib3
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/48083392
has body: Found the correct font name to make each character 8 by 8 big: import ctypes LF_FACESIZE = 32 STD_OUTPUT_HANDLE = -11 class COORD(ctypes.Structure): _fields_ = [("X", ctypes.c_short), ("Y", ctypes.c_short)] class CONSOLE_FONT_INFOEX(ctypes.Structure): _fields_ = [("cbSize", ctypes.c_ulong), ("nFont", ctypes.c_ulong), ("dwFontSize", COORD), ("FontFamily", ctypes.c_uint), ("FontWeight", ctypes.c_uint), ("FaceName", ctypes.c_wchar * LF_FACESIZE)] font = CONSOLE_FONT_INFOEX() font.cbSize = ctypes.sizeof(CONSOLE_FONT_INFOEX) font.nFont = 8 font.dwFontSize.X = 8 font.dwFontSize.Y = 8 font.FontFamily = 8 font.FontWeight = 8 font.FaceName = "Terminal" handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) ctypes.windll.kernel32.SetCurrentConsoleFontEx( handle, ctypes.c_long(False), ctypes.pointer(font))
accepted answer of: http://stackoverflow.com/q/48067200
answers question: http://stackoverflow.com/q/48067200
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/48075155
type: Answer
has body: I've figured it out. Open up all the inbound and outbound ports like 8080,80, etc.. for pip to install.
has comment: http://stackoverflow.com/comment/85690070
accepted answer of: http://stackoverflow.com/q/48074091
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/132583489
score: -2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85690030
answers question: http://stackoverflow.com/q/48074091

http://stackoverflow.com/a/58494665
upvote count: 23
answers question: http://stackoverflow.com/q/48082138
type: Answer
has body: To disable zoom and panning you need to set: layout.xaxis.fixedrange = true and layout.yaxis.fixedrange = true. To hide the controls you need to set displayModeBar = false. In Python this would for example look like this: dcc.Graph( id='my-id', config={'displayModeBar': False}, 'layout': go.Layout( xaxis={'title': 'x-axis','fixedrange':True}, yaxis={'title': 'y-axis','fixedrange':True}) )
has comment: http://stackoverflow.com/comment/126355028
score: 23
has comment: http://stackoverflow.com/comment/119020645
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48082138

http://stackoverflow.com/comment/83098030
type: QuestionComment
has text: Thank you @ctwheels kindly add it in answers so i can accept.
type: Comment
comment on: http://stackoverflow.com/q/48062271
score: 0

http://stackoverflow.com/q/48139239
tagged with: matrix
tagged with: arrays
has body: I'm searching for an efficient way to create a matrix of occurrences from two arrays that contains indexes, one represents the row indexes in this matrix, the other, the column ones. eg. I have: #matrix will be size 4x3 in this example #array of rows idxs, with values from 0 to 3 [0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3] #array of columns idxs, with values from 0 to 2 [0, 1, 1, 1, 2, 2, 0, 1, 2, 0, 2, 2, 2, 2] And need to create a matrix of occurrences like: [[1 0 0] [0 2 0] [0 1 2] [2 1 5]] I can create an array of one hot vectors in a simple form, but cant get it work when there is more than one occurrence: n_rows = 4 n_columns = 3 #data rows = np.array([0, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3]) columns = np.array([0, 1, 1, 1, 2, 2, 0, 1, 2, 0, 2, 2, 2, 2]) #empty matrix new_matrix = np.zeros([n_rows, n_columns]) #adding 1 for each [row, column] occurrence: new_matrix[rows, columns] += 1 print(new_matrix) Which returns: [[ 1. 0. 0.] [ 0. 1. 0.] [ 0. 1. 1.] [ 1. 1. 1.]] It seems like indexing and adding a value like this doesn't work when there is more than one occurrence/index, besides printing it seems to work just fine: print(new_matrix[rows, :]) : [[ 1. 0. 0.] [ 0. 1. 0.] [ 0. 1. 0.] [ 0. 1. 1.] [ 0. 1. 1.] [ 0. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.]] So maybe I'm missing something there? Or this cant be done and I need to search for another way to do it?
favorite count: 0
has answer: http://stackoverflow.com/a/48139278
accepted answer: http://stackoverflow.com/a/48139278
possible better answer: http://stackoverflow.com/a/48139382
tagged with: python
has title: Fill matrix of occurences from column/row arrays of indexes
upvote count: 4
type: AnsweredQuestion
downvote count: 0
type: Question
tagged with: indexing
has answer: http://stackoverflow.com/a/48139382
score: 4
tagged with: numpy
answer count: 2

http://stackoverflow.com/comment/83320497
type: QuestionComment
has text: I think : `np.mean(a,axis=0)[0]`, where `a` is the input , i.e. A or B or anything else of that format.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48170398

http://stackoverflow.com/comment/83284960
score: 0
type: AnswerComment
type: Comment
has text: Maybe I misunderstood, but I thought that you wanted all of the data in a dictionary (so no memory constraint). The memory storage can be avoided with a little bit of extra work.
comment on: http://stackoverflow.com/a/48153004

http://stackoverflow.com/a/48027258
has comment: http://stackoverflow.com/comment/83025487
score: 0
type: Answer
has body: Just change file_handle=open("/home/naseer/Python/newfile","r+") To : file_handle=open("/home/naseer/Python/newfile","a") file_handle.write("hai\n") "r" stands for writing erassng the previous data and "a" for append. As you want to add a new line append should work for you.
answers question: http://stackoverflow.com/q/48026581

http://stackoverflow.com/comment/83290125
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48154968
has text: I don't have access to a *RH* machine, but you should install the *python-devel* package for the *Python* version that you try to build against (in this case 2.7.\*). No longer familiar with rpm names (try *python-devel-2.7*? but I guess 2.6 is the default for your *OS* version). Here's a list of *RPM*s, you could download and install manually: https://rpmfind.net/linux/rpm2html/search.php?query=python-devel. Also you might need to set some env vars before `pip install`.

http://stackoverflow.com/q/48091964
has comment: http://stackoverflow.com/comment/83159729
type: Question
has comment: http://stackoverflow.com/comment/83158469
has comment: http://stackoverflow.com/comment/83158458
tagged with: fastcgi
has comment: http://stackoverflow.com/comment/83158381
tagged with: flask
duplicate of: http://stackoverflow.com/q/43568025
has title: Why does my Flask calculate different numbers on every refresh?
score: 0
linked to: http://stackoverflow.com/q/43568025
upvote count: 1
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/83158407
has comment: http://stackoverflow.com/comment/83159973
has comment: http://stackoverflow.com/comment/83158619
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83158490
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/83160651
has body: I created a fairly simple Webapp using Flask. It calculates the current distance of all planets by using Skyfield. The Server and the Python code work fine when i run them locally in my terminal. Unfortunately, when i deploy them to my Server with FastCGI, the site spits out totally different numbers whenever i hit refresh. I really can't find out what the problem is - can anyone help me? Current Site: Click The main Flask code: #!/usr/bin/env python3.4 from flask import Flask, render_template import calculations app = Flask(__name__) @app.route("/") def index(): return render_template("main.html", DistList=calculations.DistanceList(), DistRelList=calculations.DistanceRelationList()) @app.route("/sources") def sources(): return render_template("sources.html") if __name__=="__main__": app.run() The python to calculate the distances: import numpy import time from skyfield.api import load ts = load.timescale() planets = load('de421.bsp') # create dictionary with all data needed. (body, min distance, max distance) # Planetary Information taken from Nasa Fact Sheets # (https://nssdc.gsfc.nasa.gov/planetary/factsheet/) celestialsDict = { "Mercury": [planets["mercury"], 77342099, 221853642], "Venus": [planets["venus"], 38297055, 260898687], "Mars": [planets["mars"], 55650408, 401371087], "Jupiter": [planets["JUPITER_BARYCENTER"], 588518023, 968047821], "Saturn": [planets["SATURN_BARYCENTER"], 1195436585, 1658441995], "Uranus": [planets["URANUS_BARYCENTER"], 2581909650, 3157263061], "Neptune": [planets["NEPTUNE_BARYCENTER"], 4305875512, 4687350083], "Pluto": [planets["PLUTO_BARYCENTER"], 4293758085, 7533299975], "Moon": [planets["Moon"], 362102, 404694] } def DistanceToEarth(body): #return current distance to earth t = ts.now() astrometric = planets["earth"].at(t).observe(body) ra, dec, distance = astrometric.radec() return float("{:.2f}".format(distance.km)) def DistanceList(): #returns a list of distances of the celestials DistList = [] for body in celestialsDict: DistLis…
answer count: 0
has comment: http://stackoverflow.com/comment/83159822
has comment: http://stackoverflow.com/comment/83159660

http://stackoverflow.com/comment/83149098
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48086852
type: Comment
has text: I totally agree - see the comment I added on the question for why I might not want a catch-all, but instead would prefer to specifically catch individual exceptions in code that isn't top-level.

http://stackoverflow.com/a/48049214
type: AcceptedAnswer
downvote count: 0
has body: re.sub replaces the content in the string. You need to use re.search to extract the substring. You can use below regex to extract your desired number from url: '(?&lt;=thread-)\d+' This regex will return the string of first continuous series of number just after the "thread-". For example: &gt;&gt;&gt; urlss = 'http://www.deyi.com/thread-24488-1-1.html' &gt;&gt;&gt; import re &gt;&gt;&gt; re.search('(?&lt;=thread-)\d+', urlss).group() '24488'
accepted answer of: http://stackoverflow.com/q/48049189
answers question: http://stackoverflow.com/q/48049189
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83069943

http://stackoverflow.com/q/48087980
has answer: http://stackoverflow.com/a/48203617
possible better answer: http://stackoverflow.com/a/48211994
type: AnsweredQuestion
has body: I have a QuerySet of some objects. For each one, I wish to annotate with the minimum value of a related model (joined on a few conditions, ordered by date). I can express my desired results neatly in SQL, but am curious how to translate to Django's ORM. Background Let's say that I have two related models: Book, and BlogPost, each with a foreign key to an Author: class Book(models.Model): title = models.CharField(max_length=255) genre = models.CharField(max_length=63) author = models.ForeignKey(Author) date_published = models.DateField() class BlogPost(models.Model): author = models.ForeignKey(Author) date_published = models.DateField() I'm trying to find the first mystery book that a given author published after each blog post that they write. In SQL, this can be achieved nicely with windowing. Working solution in PostgreSQL 9.6 WITH ordered AS ( SELECT blog_post.id, book.title, ROW_NUMBER() OVER ( PARTITION BY blog_post.id ORDER BY book.date_published ) AS rn FROM blog_post LEFT JOIN book ON book.author_id = blog_post.author_id AND book.genre = 'mystery' AND book.date_published &gt;= blog_post.date_published ) SELECT id, title FROM ordered WHERE rn = 1; Translating to Django's ORM While the above SQL suits my needs well (and I could use raw SQL if needed), I'm curious as to how one would do this in QuerySet. I have an existing QuerySet where I'd like to annotate it even further books = models.Book.objects.filter(...).select_related(...).prefetch_related(...) annotated_books = books.annotate( most_recent_title=... ) I'm aware that Django 2.0 supports window functions, but I'm on Django 1.10 for now. Attempted solution I'd first built a Q object to filter down to mystery books published after the blog post. published_after = Q( author__book__date_published__gte=F('date_published'), author__book__genre='mystery' ) From here, I attempted to piece together django.db.models.Min and additional F objects to acheive my desired results, but with no success. Note: Django 2.0 …
type: Question
has comment: http://stackoverflow.com/comment/102021664
upvote count: 15
answer count: 2
tagged with: django-queryset
downvote count: 0
has title: Annotate QuerySet with first value of ordered related model
accepted answer: http://stackoverflow.com/a/48203617
score: 15
favorite count: 0
linked to: http://stackoverflow.com/q/3800551
tagged with: postgresql
linked to: http://stackoverflow.com/q/28550679
tagged with: django-1.10
has answer: http://stackoverflow.com/a/48211994
has comment: http://stackoverflow.com/comment/83238093
tagged with: django
tagged with: python

http://stackoverflow.com/q/48113622
tagged with: lxml
has comment: http://stackoverflow.com/comment/83204248
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/83267959
type: UnansweredQuestion
tagged with: python
has title: Notification to user when particular word appear on webpage using python
has body: I want notification when particular word is appear on website. for example, on news website if any news updated which contain word "GST", then it should notify me and provide me the detail of that news to be stored in any file. And I want to monitor it continuously for change. Is it possible with python using selenium, beautifulSoup, or lxml? Using below provided code I'm able to get notify if any change is there. But I want notification for particular word appear and all the details regarding this. import urllib import urllib2 import cookielib import time def fetch_html(): # fetch logic cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) resp = opener.open('www.example.com') data = resp.read() return data def write_html(html): # write logic file = open("htmlString.txt", "w") file.write(html) file.close() # monitor(html) def read_html(): with open('htmlString.txt','r') as f: return f.read() def monitor(): write_html(fetch_html()) while True: time.sleep(5) new_html = fetch_html() if new_html == read_html(): print('Nothing has changed') else: print new_html print('Something has changed') write_html(new_html) monitor() Thank You. EDIT For example, if source code contains The notification stipulates that manufacturers who have opted for composition scheme will now have to pay 1 percent Goods and Services Tax (GST) as against 2 percent earlier. GST council said that the e-way Bill system will have to be made ready by January 16 for trial runs. Which tag contain word "GST" is not fixed. what I want is to search for element which has that word and the value contained within tags. for example, The notification stipulates that manufacturers who have opted for composition scheme will now have to pay 1 percent Goods and Services Tax (GST) as against 2 percent earlier GST council said that the e-way Bill system will have to be made ready by January 16 for trial runs. Thank you
score: 0
tagged with: selenium
tagged with: web-scraping
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/83203147
has answer: http://stackoverflow.com/a/48115954

http://stackoverflow.com/a/48167019
upvote count: 1
type: Answer
downvote count: 0
has body: You need to give them access to the repository by creating a team inside bitbucket. Then you can use git --export to download files git archive --remote=ssh://git@bitbucket.org/&lt;your-username&gt;/&lt;reponame&gt;.git &lt;branchname&gt; &lt;filename&gt; --output output.tar Of course, you need to have git authed eg. using an ssh key or similar I don't think there is a way to make direct download links with auth in bitbucket, then you need to set that up outside bitbucket.
has comment: http://stackoverflow.com/comment/83405732
score: 1
answers question: http://stackoverflow.com/q/48161651

http://stackoverflow.com/comment/82998423
comment on: http://stackoverflow.com/q/48014713
type: Comment
type: QuestionComment
score: 3
has text: What is a "supercomputer"? Is that some local marketing name for a Dell or something?

http://stackoverflow.com/comment/83026902
has text: Please show the code you tried, even if it fails.
type: QuestionComment
comment on: http://stackoverflow.com/q/48028391
type: Comment
score: 2

http://stackoverflow.com/comment/83277715
type: Comment
comment on: http://stackoverflow.com/a/48149098
score: 0
type: AnswerComment
has text: Writing a deamon is not that easy. This is why i linked a question which explains it instead of trying to explain it here. For example the deamon typically runs in the background and uses a PID file.

http://stackoverflow.com/comment/83035757
comment on: http://stackoverflow.com/q/48032776
score: 0
type: Comment
has text: Just to note - you're getting into bad practices here... If you want to repeat prompting users for options then use a loop - calling the function again within the function is called recursion and while unlikely, if the user keeps making choices that do that - you'll eventually blow the stack. Not to mention it's completely unnecessary :)
type: QuestionComment

http://stackoverflow.com/q/48111638
favorite count: 0
has title: python deprecated pd.convert_objects(convert_numeric=True) works the alternative one malfunctions
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83317167
type: Question
has answer: http://stackoverflow.com/a/48113762
accepted answer: http://stackoverflow.com/a/48113762
tagged with: dataframe
has body: The following warning is thrown but i am getting the actual intended result ,when i try to change the code it fails. new_table = new_table.convert_objects(convert_numeric=True) new_table=new_table.replace(np.nan,0) # This is used to make - to 0 for calc Warning (from warnings module): new_table = new_table.convert_objects(convert_numeric=True) FutureWarning: convert_objects is deprecated. Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric. the new_table is nothing but a pandas dataframe it contains A B C D E 1 - 3 5 6 2 3 5 6 7 - - 5 5 5 5 4 - - - - - 4 - 4 9 - - 10 23 In this given data frame format since we have the string "-" further sum or diff or multiplication logics throws error if i use the below method . new_table = pd.to_numeric(new_table) #new_table=new_table.replace("-",0) new_table=new_table.replace(np.nan,0) Traceback (most recent call last): File line 107, in new_table = pd.to_numeric(new_table) File line 113, in to_numeric raise TypeError('arg must be a list, tuple, 1-d array, or Series') TypeError: arg must be a list, tuple, 1-d array, or Series What is the best way of handling this situation the first row shall be index in str format and others rows are numeric so that my arithmatic calculation will not be affected. Any help ?
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83347881

http://stackoverflow.com/a/60057427
type: Answer
answers question: http://stackoverflow.com/q/48034534
score: 0
has body: Standard input and output are file objects in Python. The Python 3 documentation says that, when these objects are created, if encoding is left unspecified then locale.getpreferredencoding(False) is called to fetch the locale's preferred encoding. Your system should have been set up with one or more "locales" when GNU/Linux was installed (I'm guessing from your paths that you are using some version of GNU/Linux). On a "sensible" setup, the default locale should allow UTF-8. But if you only did a "minimal" installation (for example as part of setting up a container), or something like that, then it is possible that the system has set locale to "C" (the ultimate fallback locale), which does not support UTF-8. Just because your terminal can accept UTF-8 (as demonstrated by using echo with a UTF-8 string), does not mean Python knows that UTF-8 is acceptable. If Python sees the locale set to "C" then it will assume only ASCII is allowed unless told otherwise. You can check the current locale by typing locale at the shell prompt, and change it by setting the LC_ALL environment variable. But before changing it you must check with locale -a to see which locales are available on your system, otherwise your change may not be effective and you may get the "C" locale anyway. If your system has not been set up with the locale you want, you can add it if you have root access: most GNU/Linux distributions provide options to do this when you (re)configure a package called locales, so for example on Debian/Ubuntu-based distros, sudo dpkg-reconfigure locales should show you the options. But sometimes you will be in the awkward position of having to write a Python script to run on a system that has not been set up with decent locales and there's nothing you can do about it because you don't have root and the sysadmin insists on giving you the absolute minimum. Then what do we do? Well there are options within Python itself. You could run export PYTHONIOENCODING=utf-8 before running Py…

http://stackoverflow.com/a/48068576
score: 0
has comment: http://stackoverflow.com/comment/83111239
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83111248
has body: You can use enumerate: def to_dictionary(filename): with open(filename) as f: first = {i:list(map(int, a.strip('\n').split())) for i, a in enumerate(f, start=1)} return {a:b[b.index(min(b)):]+b[:b.index(min(b))] for a, b in first.items()}
has comment: http://stackoverflow.com/comment/83111423
type: Answer
answers question: http://stackoverflow.com/q/48068546
accepted answer of: http://stackoverflow.com/q/48068546
has comment: http://stackoverflow.com/comment/83111377
has comment: http://stackoverflow.com/comment/83111562
upvote count: 1
has comment: http://stackoverflow.com/comment/83111270
downvote count: 1
has comment: http://stackoverflow.com/comment/83111451

http://stackoverflow.com/comment/82999625
comment on: http://stackoverflow.com/q/48015231
has text: Because it calculates `0` + first row + second row + .... If you want the sum, use `(Boston['rm'] > 7).sum()
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83299803
comment on: http://stackoverflow.com/q/48159663
type: Comment
type: QuestionComment
has text: Just a tip: never write code in your local language. Stick to English. If any developer will have to take over your code in the future, it will make it very difficult.
score: 0

http://stackoverflow.com/a/71463321
downvote count: 0
answers question: http://stackoverflow.com/q/48135624
score: 4
has body: Updating @Isabella answer, using current VSCode 1.65.1 and current python launcher, you can use py -version, for example py -3.8. Thus, you can make a folder .vscode containing a single file name called settings.json containing { "python.defaultInterpreterPath": "py -3.8", }
type: Answer
upvote count: 4

http://stackoverflow.com/comment/83151351
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48088265
has text: this is can be solved by using multiple np.where...
score: 0

http://stackoverflow.com/q/48081672
tagged with: gpgpu
favorite count: 0
has comment: http://stackoverflow.com/comment/83138516
has comment: http://stackoverflow.com/comment/83138376
has comment: http://stackoverflow.com/comment/83138659
has answer: http://stackoverflow.com/a/48083341
tagged with: python
has comment: http://stackoverflow.com/comment/83139393
has comment: http://stackoverflow.com/comment/83139982
has answer: http://stackoverflow.com/a/48082352
has comment: http://stackoverflow.com/comment/83140917
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48082352
downvote count: 0
has body: I am dealing with a simple question with numpy. I have two lists of matrices - say A,B - encoded as 3D arrays with shapes (n,p,q) and (n,q,r) respectively. I want to compute their element-wise dot product, that is a 3D-array C such that C[i,j,l] = sum A[i,j,:] B[i,:,l]. This is very simple mathematically speaking, but here are the rules I must follow: 1) I must only use numpy functions (dot, tensordot, einsum, etc.): no loop &amp; cie. This is because I want this to work on my gpu (with cupy) and loops are awful on it. I want all operations to be made on the current device. 2) Since my data can be quite large, typically A and B already take few dozens of Mb in memory, I don't want to build any items with bigger shapes than (n,p,q),(n,q,r),(n,p,r) (no intermediate 4D arrays must be store). For example, the solution I have found there , that is using: C = np.sum(np.transpose(A,(0,2,1)).reshape(n,p,q,1)*B.reshape(n,q,1,r),-3) is correct mathematically speaking, but implies the intermediate creation of a (n,p,q,r) array which is too big for my purpose. I had similar trouble with something like C = np.einsum('ipq,iqr-&gt;ipr',A,B) I don't know what are the underlying operations &amp; constructions, but it always leads to a memory error. On the other hand, something a bit naive like: C = np.array([A[i].dot(B[i]) for i in range(n)]) seems ok in terms of memory but is not efficient on my gpu: the list is build on the CPU it seems, and re-allocating it to gpu is slow (if there is a cupy-friendly way to write that, it would be a nice solution!) Thank you for your help !
has title: Numpy element-wise dot product without loop and memory error
has comment: http://stackoverflow.com/comment/83137801
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83138792
answer count: 2
possible better answer: http://stackoverflow.com/a/48083341
tagged with: arrays
has comment: http://stackoverflow.com/comment/83138045
has comment: http://stackoverflow.com/comment/83137942
upvote count: 2
has comment: http://stackoverflow.com/comment/83156077
has comment: http://stackoverflow.com/comment/83139000

http://stackoverflow.com/q/48090781
answer count: 2
has answer: http://stackoverflow.com/a/48396507
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Django translation makemessage error
has comment: http://stackoverflow.com/comment/83158394
has comment: http://stackoverflow.com/comment/83158950
accepted answer: http://stackoverflow.com/a/48396507
has body: I'm creating django multilingual website. Settings.py USE_I18N = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, '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', 'django.template.context_processors.i18n', ], }, }, ] 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', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ] from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('de', _('German')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) template: &lt;h5&gt;{% trans "Hello, this is testing page" %}&lt;/h5&gt; urls: from django.conf.urls.i18n import i18n_patterns from django.conf.urls import include, url urlpatterns = [ url(r'^rev/', rev, name="rev"), url(r'^userprofile/', userprofile, name="profile"), ] views: @login_required def rev(request): return render_to_response('rev.html', {'client': request.user.client, 'user': request.user}) @login_required @require_http_methods(["GET"]) def userprofile(request): return render(request, 'userprofile.html', { 'user': request.user, 'form': UserProfileForm(instance=request.user) }) So, using python makemessage -l de command I got next error: CommandError: errors happened while running msguniq msguniq: \u041d\u0435\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u0442\u044c \u04…
type: Question
possible better answer: http://stackoverflow.com/a/48091363
has answer: http://stackoverflow.com/a/48091363
has comment: http://stackoverflow.com/comment/83157376
has comment: http://stackoverflow.com/comment/83160313
has comment: http://stackoverflow.com/comment/83157737
score: 0

http://stackoverflow.com/q/48031510
tagged with: if-statement
type: Question
answer count: 2
has body: I'm working on a simple program that asks for 3 inputs and if all 3 inputs match then a welcome message is printed. (Initials == YNH, Age == 42, DOB == 1/27/74). Additionally, the length of the user's name (YoungNathanHeather) is printed as well as an input (color) that prints one of three different strings. I am having a problem where all three if statements are true and printing their strings even though the variable (color) is different when I input blue, pink, and yellow. Maybe I am missing something huge here with nesting a bunch of if statements, but does anyone have an idea whats going on here ? I expect to input "Yellow" and see only one string print. #checks if inputted information matches criteria. #if all inputted information matches variable criteria #(Initials == YNH, Age == 42, DOB == 1/27/74), then #prints a Welcome message for the user. if Initials == 'YNH': if Age == '42': if DOB == '1/27/74': print('Welcome Young Nathan Heather') print('Did you know that your name has ' +str((len('YoungNathanHeather'))) +' letters.') #Asks for a color and prints a response based on if the color is pink, yellow, or blue color = input("If you could describe your mood in a color, what would it be ?") if color == 'blue' or 'Blue': print('According to my research Master, Blue and Yellow together makes green. Green seems to be equal to money.') elif color == 'pink' or 'Pink': print('According to my research Master, Pink attracts women or makes a human into a women. Whatever comes first.') elif color == 'yellow' or "Yellow": print('According to my research Master, Yellow indicates a "mellow" mood. Prolong this mood if feasible.') else: print("My apologies Master. My research is shallow and I am not yet familiar with that mood's \"color\"") else: print('Sorry, Wrong Credentials Entered') else: print('Sorry, Wrong Credentials Entered') else: print('Sorry, Wrong Credentials Entered')
score: 0
duplicate of: http://stackoverflow.com/q/20002503
tagged with: python
has comment: http://stackoverflow.com/comment/83033265
has answer: http://stackoverflow.com/a/48031595
type: UnansweredQuestion
has title: Multiple if statements printing in python?
has answer: http://stackoverflow.com/a/48031597
linked to: http://stackoverflow.com/q/20002503

http://stackoverflow.com/q/48045888
type: UnansweredQuestion
tagged with: python
tagged with: matplotlib
downvote count: 1
type: Question
has title: Matplotlib clean all the text along the axis but leave the frame
upvote count: 0
score: -1
has body: I want to remove all the text and ticks around the x/y axis in matplotlib. But keep the frames and all the text within the figure e.g. legend etc. The final result should look like a box contains an image. Thanks.
tagged with: axis
answer count: 1
has answer: http://stackoverflow.com/a/48045931
favorite count: 0

http://stackoverflow.com/a/48063354
upvote count: 1
score: 1
has body: Perhaps fetching all &lt;a&gt; tags with the class external-link in your table helps. from bs4 import BeautifulSoup from urllib.request import urlopen import urllib.request, urllib.parse, urllib.error geral = urlopen("http://idg.receita.fazenda.gov.br/orientacao/tributaria /cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/dados-abertos-do-cnpj") bsObje = BeautifulSoup(geral, "lxml") estados = bsObje.findAll("table", {"class":"plain"})[0].findAll('a', {"class":"external-link"}) estados = {a.get('title'): a.get('href') for a in estados} print(estados) You may also get rid of that index if you are only interested in the first (maybe only) table by using find instead of findAll: estados = bsObje.find("table", {"class":"plain"}).findAll('a', {"class":"external-link"})
answers question: http://stackoverflow.com/q/48063165
has comment: http://stackoverflow.com/comment/83140462
downvote count: 0
has comment: http://stackoverflow.com/comment/83138409
type: Answer

http://stackoverflow.com/q/48121424
answer count: 1
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/83237997
has comment: http://stackoverflow.com/comment/83224325
has answer: http://stackoverflow.com/a/56386335
has comment: http://stackoverflow.com/comment/83225195
upvote count: 2
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83295671
tagged with: cross-platform
has body: I wrote some python code for a friend of mine and used pyinstall to package it up for him. The problem is I use windows and he uses a Mac. Is there anyway I can convert my script to run on his computer? Or is he going to need to install python himself? How do people with two different OSes usually work together?
has comment: http://stackoverflow.com/comment/83221675
type: Question
has title: PyInstaller Convert to macOS
downvote count: 0
has comment: http://stackoverflow.com/comment/83295630
favorite count: 0
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/83219819
linked to: http://stackoverflow.com/q/51225153

http://stackoverflow.com/comment/83242003
has text: Awesome.. Thanks!!
type: Comment
comment on: http://stackoverflow.com/a/48132229
score: 1
type: AnswerComment

http://stackoverflow.com/comment/83269218
comment on: http://stackoverflow.com/a/48145069
score: 0
type: AnswerComment
type: Comment
has text: @jezrael take a look. https://www.kaggle.com/bharathsh/checking-the-index-col-parameter/ index is still `int` rather than `str` index_col wont convert the dtypes I think. More probably a bug .

http://stackoverflow.com/a/48171528
has body: You can always leverage the fact that nan != nan: &gt;&gt;&gt; x = torch.tensor([1, 2, np.nan]) tensor([ 1., 2., nan.]) &gt;&gt;&gt; x != x tensor([ 0, 0, 1], dtype=torch.uint8) With pytorch 0.4 there is also torch.isnan: &gt;&gt;&gt; torch.isnan(x) tensor([ 0, 0, 1], dtype=torch.uint8)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48158017
type: Answer
score: 90
has comment: http://stackoverflow.com/comment/83364713
has comment: http://stackoverflow.com/comment/116310272
upvote count: 91
downvote count: 1
answers question: http://stackoverflow.com/q/48158017

seaborn
tags question: http://stackoverflow.com/q/48151629
tags question: http://stackoverflow.com/q/48122019
tags question: http://stackoverflow.com/q/48022199
tags question: http://stackoverflow.com/q/48162182
tag name: seaborn
tags question: http://stackoverflow.com/q/48145811
tags question: http://stackoverflow.com/q/48043365
tags question: http://stackoverflow.com/q/48171887
tags question: http://stackoverflow.com/q/48155217
tags question: http://stackoverflow.com/q/48139899
tags question: http://stackoverflow.com/q/48017438
tags question: http://stackoverflow.com/q/48101226
tags question: http://stackoverflow.com/q/48154910
tags question: http://stackoverflow.com/q/48051928
tags question: http://stackoverflow.com/q/48039241
tags question: http://stackoverflow.com/q/48145924
type: Tag
tags question: http://stackoverflow.com/q/48066588
tags question: http://stackoverflow.com/q/48166922

http://stackoverflow.com/comment/83246323
score: 2
comment on: http://stackoverflow.com/a/48134433
has text: No semicolons in Python.
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48088670
upvote count: 2
type: AcceptedAnswer
has body: A workaround solution, thanks to @spencerkclark, is available in this gist and reproduced here. fig = plt.figure() projection = ccrs.PlateCarree() axes_class = (GeoAxes, dict(map_projection=projection)) axgrid = AxesGrid(fig, 111, axes_class=axes_class, nrows_ncols=(2, 2), axes_pad=0.3, label_mode='') for n, ax in enumerate(axgrid): ax.set_xlim(-180, 180) ax.set_ylim(-90, 90) ax.set_xticks(np.linspace(-180, 180, 5), crs=projection) ax.set_yticks(np.linspace(-90, 90, 5), crs=projection) # Make ticklabels on inner axes invisible axes = np.reshape(axgrid, axgrid.get_geometry()) for ax in axes[:-1, :].flatten(): ax.xaxis.set_tick_params(which='both', labelbottom=False, labeltop=False) for ax in axes[:, 1:].flatten(): ax.yaxis.set_tick_params(which='both', labelbottom=False, labeltop=False) EDIT: this logic fails if the number of panels is less than nrows*ncols, e.g. if it's a 4x2 grid but only 7 panels. The following works for those cases also: def _hide_inner_ax_ticklabels(axgrid): """Produce 'L' shaped ticklabels: left row and bottom column only. Must do this manually when using axgrid + cartopy due to bug. See https://github.com/SciTools/cartopy/issues/939. """ total_panels = axgrid._nrows * axgrid._ncols blank_panels = total_panels - axgrid.ngrids newgrid = np.concatenate([axgrid, [None]*blank_panels]) axes = np.reshape(newgrid, axgrid.get_geometry()) for ax in axes[:-1, :].flatten(): try: ax.xaxis.set_tick_params(which='both', labelbottom=False, labeltop=False) except AttributeError: pass for ax in axes[:, 1:].flatten(): try: ax.yaxis.set_tick_params(which='both', labelbottom=False, labeltop=False) except AttributeError: pass
answers question: http://stackoverflow.com/q/48088669
accepted answer of: http://stackoverflow.com/q/48088669
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/83105559
comment on: http://stackoverflow.com/q/48066093
score: 0
type: QuestionComment
type: Comment
has text: Corrections? That is still incorrect syntax.

http://stackoverflow.com/comment/83314680
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48167037
has text: Ran your code with `webdriver.Chrome()` as I didn't have `IEDriver` and the code ran without any errors. Maybe the `IEDriver` is slow? If so, I'd recommend you to change to `chromedriver`
score: 0

http://stackoverflow.com/comment/83212585
comment on: http://stackoverflow.com/a/48117449
score: 0
type: Comment
has text: indeed, but how can it handle an array size of 3x3 for instance.....as I mention, it does not seem to produce the correct output.
type: AnswerComment

http://stackoverflow.com/comment/83143943
has text: @ Andersson - never came across lxml.html. I'll have to look through it and see how it goes. I'm assuming it has the functionality as grabbing a section of the page, loop through the specific criteria I'm looking for, then moves to the next section and so on. For example; grabs the Medium 10x10 unit description, price, old price, etc, then moves down to the 9x10 and repeats it for all medium, then moves to large.
type: AnswerComment
comment on: http://stackoverflow.com/a/48084009
score: 0
type: Comment

http://stackoverflow.com/q/48092750
score: -1
has answer: http://stackoverflow.com/a/48093439
answer count: 2
has comment: http://stackoverflow.com/comment/83160637
favorite count: 0
has answer: http://stackoverflow.com/a/48093024
has comment: http://stackoverflow.com/comment/83160064
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83160665
has title: Error inserting IP address into mysql
tagged with: mysql
accepted answer: http://stackoverflow.com/a/48093024
downvote count: 1
type: Question
tagged with: ip
upvote count: 0
possible better answer: http://stackoverflow.com/a/48093439
has comment: http://stackoverflow.com/comment/83159916
has body: I have tried many times with different codes to insert an ip address in mysql int unsigned field, any pointers please, i have looked at all the examples on google, nothing helps here is my code icecast_source_ip = "INET_ATON('" + icecast_source_ip +"')" print icecast_source_ip cnx = mysql.connector.connect(host=mysql_remote_host, user=mysql_remote_host_user, password=mysql_remote_host_password, database=mysql_remote_host_database) cursor = cnx.cursor() cursor.execute("INSERT INTO icecast_monitor.status_log (website_online, icecast_source_online, icecast_source_ip, icecast_no_listeners, centerpoint_online, centerpoint_connection, horsleypark_online, horsleypark_connection, system_ok) VALUES ('" + website_online + "','" + icecast_source_online + "','" + icecast_source_ip + "','" + icecast_no_listeners + "','" + centerpoint_online + "','" + centerpoint_connection + "','" + horsleypark_online + "','" + horsleypark_connection + "','" + system_ok + "') ") print 'Data inserted into Database' cnx.commit() cursor.close() cnx.close() and the error that i get Unexpected error 1064 (42000): 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 '60.241.175.9')','19','True','Main','True','Main','False')' at line 1

http://stackoverflow.com/q/48147272
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48147310
tagged with: pandas
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48147310
favorite count: 0
has body: Given the following example code: import pandas as pd import numpy as np np.random.seed(0) df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar','foo', 'bar', 'foo', 'foo'], 'B' : np.random.randint(0,100,8)}) What I want to do now is to add a new column C to the dataframe which contains the values which result from grouping the df by column A, sorting the groups by B, and calculating the differences of the values of B and the following value. Is this even possible with a few lines?
upvote count: 2
has title: Adding a column of differences from another column to groups of a dataframe
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/48054233
type: AnsweredQuestion
score: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48054437
tagged with: scrapy
type: Question
has body: I'm using Scrapy to try and perform a search on this website. The field I'm changing is Número do Processo na ORIGEM, with id 'idNumeroOriginario'. However, the Post method doesn't seem to change anything on the page. Here's the code: import scrapy from scrapy.utils.response import open_in_browser class MinimalSpider(scrapy.Spider): name = 'stj-spider' start_urls = ['https://ww2.stj.jus.br/processo/pesquisa/?aplicacao=processos.ea'] def parse(self, response): headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'browserName': 'mozilla', 'Connection': 'keep-alive', 'Referer': 'https://ww2.stj.jus.br/processo/pesquisa/?aplicacao=processos.ea', } yield scrapy.FormRequest.from_response( response, headers=headers, formid='idForm', formdata={'idNumeroOriginario': '1234'}, callback=self.after_search, ) def after_search(self, response): open_in_browser(response) print response.body I have also tried with requests, but to no avail. There seems to be a hundred hidden inputs that made it really hard. Anyways, thanks for any help.
has answer: http://stackoverflow.com/a/48054437
upvote count: 2
answer count: 1
has title: Scrapy's FormRequest not giving results
favorite count: 0
tagged with: python
tagged with: request

http://stackoverflow.com/comment/83375291
comment on: http://stackoverflow.com/q/48053030
type: QuestionComment
type: Comment
score: 0
has text: Which rule does this violate?

http://stackoverflow.com/a/48150559
score: 3
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48150512
upvote count: 3
answers question: http://stackoverflow.com/q/48150512
has body: Django's builtin filter safe will do that for you:
downvote count: 0

http://stackoverflow.com/comment/83064233
comment on: http://stackoverflow.com/a/48046368
has text: @Jean-FrançoisFabre A `defaultdict` will be faster, but the biggest problem in the code was that it was using `keys()`, especially if OP was using Python 2. Using a `defaultdict` might at best triple the speed by avoiding redundant key checks, but it does have the advantage that it eliminates the possibility of calling `keys()` by mistake.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83129185
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48076607
has text: Let me know when you post it so I can upvote.
score: 0

annotate
tag name: annotate
type: Tag
tags question: http://stackoverflow.com/q/48073293

http://stackoverflow.com/comment/83106808
comment on: http://stackoverflow.com/q/48066662
score: 2
has text: `np.concatenate((a, b.reshape(1, 1, -1).repeat(a.shape[0], axis=0)), axis=1)`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83215992
score: 1
has text: Where is the `-` in `-error` coming from? I think you have two different queries and you're looking at the wrong code. This one does not match what's in the error.
type: Comment
comment on: http://stackoverflow.com/q/48119528
type: QuestionComment

http://stackoverflow.com/comment/83054890
score: 0
has text: @PM2Ring Just had a look at your linked answer. Impressed. You do seem interested in the topic ;-]
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48041759

http://stackoverflow.com/a/48023541
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48023505
answers question: http://stackoverflow.com/q/48023505
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: __str__ must return a string value. If you return a unicode object instead, it'll be automatically encoded as ASCII. Encode explicitly instead: class Test(object): def __str__(self): d = { 'foo': u'中文' } return json.dumps(d, ensure_ascii=False).encode('utf8') Personally, I'd not use the __str__ method to provide a JSON encoding. Pick a different method name instead, like tojson().
score: 2

http://stackoverflow.com/q/48033687
type: Question
answer count: 1
score: 0
linked to: http://stackoverflow.com/q/45203872
has comment: http://stackoverflow.com/comment/83218952
tagged with: python
tagged with: artificial-intelligence
has body: I've trained my neural built with tensorflow network and got some overfit I'd like to reduce. I hoped learning the model on batches could help ad I tried to test this idea. I found tf.train.shuffle_batch() and fought this may do the thing. So I tried and it didn't work. Tensorflow's documentation doesn't help. I've found one topic, but the example there only prints arrays out. It was promising to use it to learn NN but in my case istead of getting data divided to n-element batches I got them multiplied n-times in additional dimension. Here is the code sample: nnInput = tf.placeholder(tf.float32, [None, input_width], "network_input") nnOutput = tf.placeholder(tf.float32, [None, output_width], "expected_labels") batch_readings, batch_labels = tf.train.shuffle_batch( [ tf.constant(train_readings), tf.constant(train_labels) ], batch_size = 15, num_threads = 4, capacity = 500, min_after_dequeue = 250, allow_smaller_final_batch = True ) sess.run(tf.global_variables_initializer()) for epoch in range(learning_steps): print("epoch:", epoch) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) print("Input data shapes:", train_readings.shape, train_labels.shape) for batch in range(10): x, y = sess.run([batch_readings, batch_labels]) print("Batch shapes:", x.shape, y.shape) sess.run(train, feed_dict = {nnInput : x, nnOutput : y}) coord.request_stop() coord.join(threads) and here is the output: epoch: 0 Input data shapes: (165, 60) (165, 1) Batch shapes: (15, 165, 60) (15, 165, 1) And the error list concludes with: ValueError: Cannot feed value of shape (15, 165, 60) for Tensor 'network_input_1:0', which has shape '(?, 60)' The conlusion is not surprising when I fed the NN with 3D array but why do I get such a batch when I expect x:(15, 60) and y:(15, 1)? Why do I get x:(15, 165, 60) y:(15, 165, 1) and how to get useful batches? I'm using tensorflow-gpu but hope this should work as well, right?
has title: How to use tf.train.shuffle_batch to train NN?
has comment: http://stackoverflow.com/comment/83233088
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50048576
type: UnansweredQuestion
tagged with: tensorflow

http://stackoverflow.com/a/48031565
type: Answer
accepted answer of: http://stackoverflow.com/q/48031314
score: 2
answers question: http://stackoverflow.com/q/48031314
upvote count: 2
has comment: http://stackoverflow.com/comment/83042366
has comment: http://stackoverflow.com/comment/83049145
type: AcceptedAnswer
downvote count: 0
has body: First I would get only a (without text() and extract()) and then I would use for to use text() and extract() with every a separatelly, and join() to concatenate elements to string with title. import scrapy class MySpider(scrapy.Spider): name = 'myspider' start_urls = ['https://www.indeed.cl/trabajo?q=Data%20scientist&amp;l='] def parse(self, response): print('url:', response.url) results = response.xpath('//h2[@class="jobtitle"]/a') print('number:', len(results)) for item in results: title = ''.join(item.xpath('.//text()').extract()) print('title:', title) # --- it runs without project and saves in `output.csv` --- from scrapy.crawler import CrawlerProcess c = CrawlerProcess({ 'USER_AGENT': 'Mozilla/5.0', }) c.crawl(MySpider) c.start() Result: number: 10 title: Data Scientist title: CONSULTOR DATA SCIENCE SANTIAGO DE CHILE title: Líder Análisis de Datos MCoE Minerals Americas title: Ingeniero Inteligencia Mercado, BI title: Ingeniero Inteligencia de Mercado, Business Intelligence title: Data Scientist title: Data Scientist title: Data Scientist (Machine Learning) title: Data Scientist / Ml Scientist title: Young Professional - Spanish LatAm

http://stackoverflow.com/comment/83111450
type: QuestionComment
comment on: http://stackoverflow.com/q/48068076
score: 0
has text: As far as I know I haven't done anything outside of documentations I've seen, I just loaded a .csv file without column headers and added them manually from a list. Clearly, I'm new to pandas, but confused how I strayed so far off the path. Updated. It returns `<class 'pandas.core.frame.DataFrame'> RangeIndex: 695 entries, 0 to 694 Data columns (total 1 columns): (label,) 695 non-null object dtypes: object(1) memory usage: 5.5+ KB None` Thanks
type: Comment

http://stackoverflow.com/comment/83191209
comment on: http://stackoverflow.com/q/48107708
score: 0
type: Comment
type: QuestionComment
has text: Refer https://stackoverflow.com/questions/28207761/where-does-flask-look-for-image-files

http://stackoverflow.com/comment/83389477
has text: Cool. As regards the intermittent randomness (which is probably worth a question of its own), I'd comment that the order of values in the list returned by a dictionary's `keys()` method is implementation-specific; in the reference CPython implementation, it's non-random but arbitrary and depends on the dictionary’s history of insertions and deletions—consequently, the last item in the list should have been consistent unless the order in which items were added to the dictionary differed. The regex would then have required that last item, if present, to be followed by an ASCII backspace.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48178830

http://stackoverflow.com/q/48058581
score: -1
answer count: 1
downvote count: 1
tagged with: javascript
favorite count: 0
tagged with: angularjs
tagged with: python
has title: How to send image as input to django view using angular frontend?
upvote count: 0
type: UnansweredQuestion
has body: I have an existing django web api with angular frontend, using which i can upload images and display them to the user.Now i want to extend this.On clicking the button "segment"(see image) it should pass the corresponding image to my python script on the backend, which does some processing on the image. I have my python script in the views.py file of the main app,which is some thing like this: from django.shortcuts import render def segment_image(request): if request.method == 'GET': form = segment_form() else: if form.is_valid(): info = request.POST['info_name'] output = script_function(info) ''' Here i am calling script_function,passing the POST data info to it''' return render(request, 'your_app/your_template.html', { 'output': output, }) return render(request, 'your_app/your_template.html', { 'form': form, }) '''here info is our image in some format''' def script_function(info): ... '''here goes my mian logic to process the image.''' ... return x,y,w,h I have never worked with images as inputs in angular,i dont know how to route the image using angularjs to my view.Now how can i implement this segmentImage() function in app.js file so that the function would call the corresponding view by passing this image as a POST argument. Below is my index.html file. Select Image: Upload There are no images available yet. Image {{ image.pk }} Delete Segment Below is my app.js file: // create a module called imageuploadFrontendApp, which relies on ngResource var myApp = angular.module('imageuploadFrontendApp', ['ngResource']); // Configure ngResource to always use trailing slashes (required for django) myApp.config(function($resourceProvider) { $resourceProvider.defaults.stripTrailingSlashes = false; }); // Main Controller myApp.controller('MainCtrl', function($scope, Images) { console.log('In main Control'); $scope.images = Images.query(); $scope.newImage = {}; $scope.uploadImage = function() { // call REST API endpoint Images.save($scope.newImage).$promise.then( function(re…
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/48058916

http://stackoverflow.com/q/48083981
has comment: http://stackoverflow.com/comment/83143220
possible better answer: http://stackoverflow.com/a/48100748
upvote count: 1
tagged with: python
has body: I am attempting to write a script which pulls data from a sqlite3 db and outputs only specific data which is of interest. I have written a function: def get_ip(db_file): cur = con.cursor() cur.execute('select "Computer Name","User", "IP Address1", "IP Address2", "IP Address3", "IP Address4" from SepData') ip_data = cur.fetchall() cur.close() return ip_data Which yields: [('user-PC1', 'upc1', '172.24.49.88', '0.0.0.0', '33.4.1.54', '0.0.0.0'), ('user-pc2', 'upc2', '64.24.49.90', '0.0.0.0', '0.0.0.0', '0.0.0.0'), ('user-pc3', 'upc3', '172.24.49.71', '0.0.0.0', '0.0.0.0', '0.0.0.0'), ('user-pc4', 'upc4', '172.24.89.101', '192.168.3.3', '0.0.0.0', '55.13.0.1'),] My intention is to pull global/public IPs and the user affiliated with them and store this data as an ordered list/dict. I believe there may be duplicate entries, so I think the only way to do this is with a list. If the user shows only private or non route-able IP's, Id like for this data to be ignored. Initially I attempted to do this within the SQL query but this is only doable as far as I can tell with the REGEXP function which does not come shipped with sqlite3 by default and may cause others to have trouble using the script. I am now attempting this with just python ipaddress library. I convert the list of tuples into a list of lists and am trying something like this: pubips = () iplist = get_ip('dbfile') itr = range(1,4) for host, user, ipaddr1, ipaddr2, ipaddr3, ipaddr4 in zip(iplist): for i in itr: if ipaddr+i.is_global(): pubips.insert(user, ipaddr+i) This code obviously doesn't work but gives general idea of what I am trying to accomplish. I am struggling to come up with a clean way of doing this and would appreciate any feedback. Thanks for reading
tagged with: ip-address
tagged with: dictionary
has title: Python3: Search List of tuples for values which have public IP addresses
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83142676
tagged with: list
has comment: http://stackoverflow.com/comment/83143280
score: 1
has comment: http://stackoverflow.com/comment/83142830
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48100748
has comment: http://stackoverflow.com/comment/83142785
accepted answer: http://stackoverflow.com/a/48085409
tagged with: sqlite
has comment: http://stackoverflow.com/comment/83142659
favorite count: 0
has answer: http://stackoverflow.com/a/48085409
has comment: http://stackoverflow.com/comment/83143189

http://stackoverflow.com/comment/83224329
comment on: http://stackoverflow.com/a/48123665
type: AnswerComment
type: Comment
has text: Parentheses in Python 2.7.+ are not required actually.
score: 1

image-size
tags question: http://stackoverflow.com/q/48015235
type: Tag
tag name: image-size

http://stackoverflow.com/comment/83097822
comment on: http://stackoverflow.com/q/48051283
score: 0
type: QuestionComment
has text: pywin32 is perfectly ok! Thank u so much, @eryksun !!
type: Comment

http://stackoverflow.com/comment/83149300
type: Comment
score: 2
has text: Thanks! Hadn't heard of mutation testing, that is super cool. I would still prefer a static analysis tool, though. I would prefer to be told "your code definitely handles all exceptions that may be raised" versus "your code doesn't break in all the situations you thought to test (or which could be caught via mutation testing)". I think it's a fundamental difference - one approach checks that you are handling all possibilities somehow, and the other checks that you're handling some possibilities (but ensures you handle them correctly). Ideally both approaches would be combined.
comment on: http://stackoverflow.com/a/48086804
type: AnswerComment

http://stackoverflow.com/comment/83274052
type: QuestionComment
comment on: http://stackoverflow.com/q/48143727
type: Comment
score: 0
has text: I am not able to upload csv files.can u guide how to upload?

http://stackoverflow.com/comment/138235775
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/62925227
has text: yeah, this is right. if you don't manually import other models, how does alembic know what models inherited `Base`. keyword here is, as this answer pointed out 'populate `Base.metadata`'. but, i wonder why the alembic docs doesn't make this clear. aren't splitting model files is the standard way of using sqlalchemy?

http://stackoverflow.com/comment/83332601
has text: @langme, provide some more info, e.g. HTML, page URL, etc... as it doesn't look like common case
comment on: http://stackoverflow.com/q/48173238
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85750101
has text: Classic Jupyter Notebook but as mentioned in OP I was having some anti-virus related issues with conda at that time. This has been resolved and so I was able to download Jupyter Widgets via conda. Thanks
type: Comment
comment on: http://stackoverflow.com/q/48133282
score: 0
type: QuestionComment

http://stackoverflow.com/q/48085001
type: Question
score: 0
has comment: http://stackoverflow.com/comment/83145091
answer count: 1
has comment: http://stackoverflow.com/comment/83145162
favorite count: 0
has body: Hi I am making a game where the sprite I control has to get past another sprite moving back and forth. I am trying to make an if statement that says if the sprite I control is past a certain point, i win the game writing something like if mysprite.get_position() &gt; (-100, 10): mysprite.say("I win!") does not seem to work. I'm trying to figure out how to compare where its position is on the grid. thanks!
has comment: http://stackoverflow.com/comment/83144991
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/83147014
has title: Trying to compare where my sprite is in pygame to end the game
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5292303
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48086509
has comment: http://stackoverflow.com/comment/83145275

http://stackoverflow.com/comment/83050109
type: QuestionComment
score: 0
has text: Once you've set things up, you need to notify the shell of your changes via [`SHChangeNotify`](https://msdn.microsoft.com/en-us/library/bb762118). Bear in mind that Explorer caches a filetype's open with actions under "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts". Sometimes it seems to ignore a change. You can delete the "OpenWithList" and "OpenWithProgIds" subkeys of an extension in this key prior to calling `SHChangeNotify`; I don't know a better way. But don't delete a "UserChoice" subkey. You have no right to override a user's explicit choice.
comment on: http://stackoverflow.com/q/48038146
type: Comment

http://stackoverflow.com/q/48100691
has comment: http://stackoverflow.com/comment/83188003
tagged with: pygame
has comment: http://stackoverflow.com/comment/83201603
favorite count: 0
has comment: http://stackoverflow.com/comment/83187982
has title: Moving Sprite issues
has body: When this part of the code has been run, it shows the sprite however when the arrow keys are pressed nothing moves, ive tried to use print statements to attempt to debug but nothing has come up, what is the issue and how do i solve it? Here ive added everything relating to the movement in my program the other files include the screen and the exit loop from spritechanges import * from lklk import * import pygame import time WHITE = (255, 255, 255) BLACK = (0, 0, 0, 0) clock = pygame.time.Clock() FPS = 120 # Create a surface/image and draw a circle onto it. sprite_image = pygame.Surface((50, 50)) pygame.draw.circle(sprite_image, WHITE, [25, 25], 20) # Create surface/image draw a line onto it width = 40 height = 60 # Create an instance of the Sprite class. class Sprite(pygame.sprite.Sprite): def __init__(self, pos): super(Sprite, self).__init__() # platform self.width = width self.height = height self.platform = pygame.Surface((width, height)) self.platform.fill(WHITE) # set a reference to the image rect self.rect = self.platform.get_rect() # Assign the global image to `self.image`. self.image = sprite_image # Create a rect which will be used as blit # position and for the collision detection. self.rect = self.image.get_rect() # Set the rect's center to the passed `pos`. self.rect.center = pos self._vx = 0 self._vy = 0 # Assign the pos also to these attributes. self._spritex = pos[0] self._spritey = pos[1] # set of sprites sprite can bump against self.level = None def update(self): self._gravity = 99 block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False) for block in block_hit_list: if self._vx &gt; 0: self.rect.right = block.rect.left elif self._vx &lt; 0: # Otherwise if we are moving left, do the opposite. self.rect.left = block.rect.right self.rect.y += self.change_y # Check and see if we hit anything block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False) for block in block_hit_list: # Reset our position base…
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48100769
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/48135674
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83186099
has comment: http://stackoverflow.com/comment/83201512
has answer: http://stackoverflow.com/a/48135674
possible better answer: http://stackoverflow.com/a/48100769
upvote count: 1

http://stackoverflow.com/comment/83143435
comment on: http://stackoverflow.com/a/48083291
score: 0
type: AnswerComment
type: Comment
has text: @lvdp Well, thank yourself and [Bryan's comment](https://stackoverflow.com/questions/48079022/python-tkinter-click-event-not-processed/48083291?noredirect=1#comment83132137_48079022). When the code was simplified it was much easier to understand.

http://stackoverflow.com/comment/90345733
type: Comment
has text: Is there a way to introduce a constraint through which we can say that the length of continued fraction should be at least > `k`?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48095912

http://stackoverflow.com/comment/83102490
has text: And `start ... & ...` does not do what you think it does either.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48063990

http://stackoverflow.com/a/53035201
has body: This issue for me was sometimes the video stream yielded nothing in which case the result of the line : ret, image_np = cap.read() will yield ret will be false. My fix was to do if ret == True; then run inference
type: Answer
answers question: http://stackoverflow.com/q/48088283
score: 0

http://stackoverflow.com/comment/83486771
score: 0
type: AnswerComment
has text: Firstly I don't have python3.6 from homebrew, and I don't even have python2.7 from homebrew. I uninstalled both of them and I still get this error with miniconda3. I think it has to do with system python. I tried the same thing you mentioned but that doesn't seem to help. Everything I've tried seems to indicate what I'm currently doing is fine. I have the same setup on multiple machines, and it works on two of them but not on the others.
type: Comment
comment on: http://stackoverflow.com/a/48242260

http://stackoverflow.com/comment/83309267
score: 0
type: Comment
has text: It prints something, though certainly emphatically *not* to standard output, if the assertion fails. You want diagnostics on stderr, not stdout.
type: AnswerComment
comment on: http://stackoverflow.com/a/48164616

http://stackoverflow.com/comment/83123282
type: AnswerComment
comment on: http://stackoverflow.com/a/48074653
type: Comment
has text: Yes, it's an XY problem, but hopefully the various answers here that show how to do this with a general list (that doesn't contain repeated items) will help some future readers.
score: 0

http://stackoverflow.com/q/48120086
answer count: 0
has comment: http://stackoverflow.com/comment/83220252
has comment: http://stackoverflow.com/comment/83217767
type: Question
has body: I'm sending a POST request to a Django server through Postman. This is what the body of my request looks like POST /update/ HTTP/1.1 Host: 127.0.0.1:8000 Content-Type: multipart/form-data; boundary=---- WebKitFormBoundary7MA4YWxkTrZu0gW Cache-Control: no-cache Postman-Token: 0764e56c-0fd8-fcce-5248-34f7d05f2748 ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="UploadDownloadSettings" dssssss ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="settings"; filename="settings.zip" Content-Type: application/zip When I try to access request.POST['UploadDownloadSettings'], the program says the key is not valid. When I loop through the keys in request.POST I get a bunch of keys from the zip file and the key name. According to the docs, this should parse out form-data. This seems like standard form data as far as I understand. https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpRequest.POST Am I misunderstanding the way the django post request works? Output of request.POST Key: ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition Value: form-data Key: name Value: "UploadDownloadSettings" Key: //actual filenames from the zip with their value Value: Blank Output of request.FILES: blank map Output of request.content_type: application/x-www-form-urlencoded
tagged with: python
score: 0
has title: Strange behaviour of request.POST in Django
tagged with: django
has comment: http://stackoverflow.com/comment/83221147
has comment: http://stackoverflow.com/comment/83217755
has comment: http://stackoverflow.com/comment/83219977
has comment: http://stackoverflow.com/comment/83237902
type: UnansweredQuestion

http://stackoverflow.com/comment/83233033
type: AnswerComment
has text: thanks for the answer, when i have to call tf.nn.softmax(logits) ?
type: Comment
comment on: http://stackoverflow.com/a/48127962
score: 0

http://stackoverflow.com/comment/83140108
type: QuestionComment
score: 0
has text: Use datetime library and look at strptime and strftime. -1 for pictures instead of data.
comment on: http://stackoverflow.com/q/48082629
type: Comment

http://stackoverflow.com/a/48021331
type: Answer
has body: It seems an exception is raised at _retry_request. I haven't encountered this error myself, but there's a thread on github discussing about the same error. https://github.com/google/google-api-python-client/issues/218 Try using httplib2shim, it seems oauth2client is still not replaced by google-auth. Another suggestion I found was to use the MEDIA /upload option for files over 10 MB. Docs for how to use /upload: https://developers.google.com/gmail/api/v1/reference/users/messages/send
score: 0
answers question: http://stackoverflow.com/q/48019198

coordinates
tags question: http://stackoverflow.com/q/48097730
tag name: coordinates
type: Tag
tags question: http://stackoverflow.com/q/48109264
tags question: http://stackoverflow.com/q/48131371

http://stackoverflow.com/comment/83282409
type: Comment
type: QuestionComment
has text: You want to delete every subkey that is None, and delete the keys that have no subkeys left ?
comment on: http://stackoverflow.com/q/48151953
score: 0

http://stackoverflow.com/a/48016717
has body: This should work: def max_df(df): m = None p = None for idx, item in enumerate(df.idxmax()): c = df.columns[item] val = df[c][idx] if m is None or val &gt; m: m = val p = idx, c return p This uses the idxmax function, then compares all of the values returned by it. Example usage: &gt;&gt;&gt; df A B 0 100 9 1 90 8 &gt;&gt;&gt; max_df(df) (0, 'A') Here's a one-liner (for fun): def max_df2(df): return max((df[df.columns[item]][idx], idx, df.columns[item]) for idx, item in enumerate(df.idxmax()))[1:]
type: Answer
answers question: http://stackoverflow.com/q/48016629
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/a/48060431
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48059523
accepted answer of: http://stackoverflow.com/q/48059523
score: 1
has body: How about: added_now = [] for edge in (t1,t2,t3): if not g.has_edge(*edge): g.add_edge(*edge) added_now.append(edge) added.append([aaa_binary[q],'p'+ str(i)]) for j in range(len(added)): if nx.shortest_path(g, added[j][0][0], added[j][0][3])!=added[j][0] or nx.shortest_path(g, aaa_binary[q][0], aaa_binary[q][3])!=aaa_binary[q]: for edge in added_now: g.remove_edge(*edge) added.remove([aaa_binary[q],'p'+ str(i)]) You just want to do the same for each edge that wasn't added.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/48028180
tagged with: pymongo
upvote count: 1
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/48028383
answer count: 1
downvote count: 0
favorite count: 0
has body: I have a mongodb database. I am currently writing a python script using pymongo to clean the data. My dataset has an attribute 'country'. I am trying to remove all tuples that's 'country' attribute is not the United States. I know how to use unset to remove attributes from a database, and I know how to delete an attribute using remove many. mongo_collection.delete_many({"Country":""}) mongo_collection.update({}, {'$unset': {'Country':1}}, multi=True) However, I cannot find any resources on how to remove all tuples that do not match a specific attribute value. Any insight would be greatly appreciated!!! Thank you!
has title: Pymongo - removing database tuples that do not have a specific attribute
tagged with: python
accepted answer: http://stackoverflow.com/a/48028383
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/48131266
type: Answer
accepted answer of: http://stackoverflow.com/q/48130372
score: 2
downvote count: 0
has body: I found a workaround for this. To run the application with uWSGI. You can use the Flask WSGI app with any WSGI container. Using Flask with uWSGI Here is an example: $ sudo pip3 install uwsgi $ uwsgi --socket 0.0.0.0:8080 --protocol=http --callable app --file app.py --master -p 4 # use 4 worker processes
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48130372

http://stackoverflow.com/q/48070977
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83115622
tagged with: python
has answer: http://stackoverflow.com/a/48071055
has comment: http://stackoverflow.com/comment/83115639
downvote count: 0
score: 1
type: Question
has body: After searching through multiple forums i still cant find an answer that i understand. I am making a simple text game and when writing a part of it i got this: "TypeError: 'str' object is not callable.". Heres the code: def tutorial(): print ("In this game your objective is to make out alive from the haunted house of torture.") print ("In each round, you will be faced with 3 questions, 3 choices each question.") print ("Now, are you ready to begin? (Yes or No)") begin = input() if begin == "No": def redo(): print ("Oh, than would you like to start the tutorial all over again?(Yes or No)") stog = input() if stog == "No": redo() if stog == "Yes": tutorial() def start(): print ("Hello! Would you like to start the tutorial? (Yes or No)") tutorial = input() if tutorial == "No": print ("Okay than, lets begin!!") start() if tutorial == "Yes": print ("Okay than, lets start the tutorial!!") tutorial() start() the exact error message i got was: Traceback (most recent call last): File "C:\Users\jeff\AppData\Local\Programs\Python\Python36-32\tester2.py", line 29, in &lt;module&gt; start() File "C:\Users\jeff\AppData\Local\Programs\Python\Python36-32\tester2.py", line 23, in start tutorial() TypeError: 'str' object is not callable i get the error after saying "yes" to the first question. help is appreciated, thanks.
has comment: http://stackoverflow.com/comment/83115650
has title: when trying to call a function, i got "TypeError: 'str' object is not callable"
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83115674

http://stackoverflow.com/q/48018420
type: Question
favorite count: 0
has body: I am using protobuf, I found after compiled to python file by protoc, the python classes are all dynamic, so the auto-completion is gone, it is not very convenient. I want to know if there is a way to compile protobuf to static python class, I mean with fixed attributes and methods.
tagged with: protocol-buffers
tagged with: python
has comment: http://stackoverflow.com/comment/83080801
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/86526326
type: UnansweredQuestion
has title: Can protobuf compiled to static python class?
downvote count: 1
score: 1

http://stackoverflow.com/q/48128922
type: AnsweredQuestion
score: 1
has body: I want to split a string based on space a = ' girl\n is' a.split() ['girl', 'is'] I found that after split, the '\n' will also disappear. My desired result is ['girl\n', 'is'] Then if I used .splitlines method, the result returned is also not what I want. a.splitlines(True) [' girl\n', ' is'] Do you have any suggestions? Thank you!
type: Question
has answer: http://stackoverflow.com/a/48128981
favorite count: 0
accepted answer: http://stackoverflow.com/a/48128981
has answer: http://stackoverflow.com/a/48128945
answer count: 4
has title: Python: how to split a string based on space but keep '\n'?
upvote count: 2
possible better answer: http://stackoverflow.com/a/48128945
tagged with: python
has comment: http://stackoverflow.com/comment/83234534
downvote count: 1
has answer: http://stackoverflow.com/a/48129252
has answer: http://stackoverflow.com/a/48129140

http://stackoverflow.com/q/48096029
has comment: http://stackoverflow.com/comment/83166768
has comment: http://stackoverflow.com/comment/83166804
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48096150
has comment: http://stackoverflow.com/comment/83166769
has answer: http://stackoverflow.com/a/48096643
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48096150
has title: Creating and rearranging a dictionary
has body: I am new to python! I have created a code which successfully opens my text file and sorts my list of 100's of words. I then have put these in a list labelled stimuli_words, which consists of no duplicates words, all lower case etc. However I now want to convert this list into a dictionary, where the keys are all possible 3 letter endings in my list of words, and the values are the words that correspond to those endings. For instance 'ing: going, hiring...', but I only want the words in which have more than 40 words corresponding to the last two characters. So far I have this code: from collections import defaultdict fq = defaultdict( int ) for w in stimuli_list: fq[w] += 1 print fq However it is just returning a dictionary with my words and how many times they occur which is obviously once. e.g 'going': 1, 'hiring': 1, 'driving': 1. Really would appreciate some help!! Thank You!!
possible better answer: http://stackoverflow.com/a/48096151
has answer: http://stackoverflow.com/a/48096151
type: Question

http://stackoverflow.com/a/48025215
has body: There are several major implications: Using self.__dict__ to add an attribute circumvents __setattr__, which might be overloaded with a certain behaviour that you might want to avoid in some places. In [15]: class Test(object): ...: def __init__(self, a, b): ...: self.a = a ...: self.__dict__['b'] = b ...: def __setattr__(self, name, value): ...: print('Setting attribute "{}" to {}'.format(name, value)) ...: super(Test, self).__setattr__(name, value) ...: In [16]: t = Test(1, 2) Setting attribute "a" to 1 You can see that nothing was printed for attribute b. It is less flexible in some cases In [9]: class WithSlots(object): ...: __slots__ = ('a',) ...: def __init__(self, a): ...: self.__dict__['a'] = a ...: In [10]: instance = WithSlots(1) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-10-c717fcc835a7&gt; in &lt;module&gt;() ----&gt; 1 instance = WithSlots(1) &lt;ipython-input-9-2d23b670e0fc&gt; in __init__(self, a) 2 __slots__ = ('a',) 3 def __init__(self, a): ----&gt; 4 self.__dict__['a'] = a 5 AttributeError: 'WithSlots' object has no attribute '__dict__' In [11]: class WithSlots(object): ...: __slots__ = ('a',) ...: def __init__(self, a): ...: self.a = a ...: ...: In [12]: instance = WithSlots(1) # -&gt; works fine You can't do that outside a class definition.
score: 6
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48025092
accepted answer of: http://stackoverflow.com/q/48025092
type: Answer
has comment: http://stackoverflow.com/comment/83020015
upvote count: 6
has comment: http://stackoverflow.com/comment/83020145

http://stackoverflow.com/comment/83127188
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48075841
has text: Do you really need lambdas here ? I suspect your lambdas are actually just calling another function, in which case you can just reference that other function directly in your dict.

http://stackoverflow.com/comment/83172288
score: 0
comment on: http://stackoverflow.com/a/48098534
has text: Sir the out_shp of strided4D, is that a formula of some kind?
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48090905
has comment: http://stackoverflow.com/comment/83156116
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48091580
tagged with: python
has body: Consider following MCVE: import sys import argparse parser = argparse.ArgumentParser() parser.add_argument("-t", "--test") parser.add_argument("-o", "--other") assert sys.argv == ['mcve.py', '-o', '-t 123'] parsed = parser.parse_args() assert parsed.other == "-t 123" And its' invocation: lrogalsk-mac01:src lrogalsk$ python mcve.py -o "-t 123" usage: mcve.py [-h] [-t TEST] [-o OTHER] mcve.py: error: argument -o/--other: expected one argument As you can see, values in shell are interpreted correctly and passed to Python process as separate command line arguments. Nevertheless, argparse parsing mechanism still rejects this value (likely because it begins with match of another parameter, -t). Changing invocation to space-prepended value (see below) and adjusting assertions in MCVE script makes it work, but this for me is merely workaround and not an actual solution. lrogalsk-mac01:src lrogalsk$ python mcve.py -o " -t 123" Is there any known way of fixing this behaviour in argparse? Set-up details: lrogalsk-mac01:src lrogalsk$ python --version Python 2.7.10
has comment: http://stackoverflow.com/comment/83156550
has comment: http://stackoverflow.com/comment/83157208
type: Question
tagged with: argv
answer count: 1
linked to: http://stackoverflow.com/q/16174992
score: 0
tagged with: argparse
duplicate of: http://stackoverflow.com/q/16174992
has comment: http://stackoverflow.com/comment/83156175
has title: argparse - valid argument value falsely ignored

http://stackoverflow.com/q/48044203
has comment: http://stackoverflow.com/comment/83059364
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48044354
has answer: http://stackoverflow.com/a/48044546
type: Question
has title: Searching a document for numbers and printing the line above
downvote count: 5
score: -4
has body: I have existing data in a file that looks like this: d893ecee58ee4d6f1ca56a358d2e6287 69 ae0d10efd7663c734b9ea66cec5aaa44 100 c9136ba49f4b1a8e89d6ed35cac95f7c 100 67c1431d8a06d7b2e31g86874b757eeb 0 8478b9587875f65d5afe54f541bada61 11 What i'd like to do is search the document for any line with a number value greater than 30 and print the line above that number. Here's what I have now : with open ('somefile.txt','r') as f, open('newfile.txt','w') as fnew: for i, line in enumerate(f): if line.startswith('1' or '2' or '3' or '4' or '5' or '6' or '7' or '8' or '9' or '10' or '11' or '12' or '13' or '14' or '15' or '16' or '17' or '18' or '19' or '20' or '21' or '22' or '23' or '24' or '25' or '26' or '27' or '28' or '29' or '30'): fnew.write(line -1) I know this isn't the cleanest script but i just want something that works.
has comment: http://stackoverflow.com/comment/83059353
has answer: http://stackoverflow.com/a/48044349
has comment: http://stackoverflow.com/comment/83059343
possible better answer: http://stackoverflow.com/a/48044667
favorite count: 0
has comment: http://stackoverflow.com/comment/83059479
has answer: http://stackoverflow.com/a/48044667
answer count: 5
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48044299
accepted answer: http://stackoverflow.com/a/48044349

http://stackoverflow.com/q/48137595
score: 0
has answer: http://stackoverflow.com/a/48138176
has body: I follow this tutorial to install tensorflow in my windows 7, I adopte the conda proposetion: conda create -n tensorflow python=3.5 , when I imported the library in python it worked but when I did the same thing with notebook and Ipython I got this error: ModuleNotFoundError: No module named 'tensorflow' even when I restart the Kernel I got the same Error. UPDATE: When I run the command os.environ in the both windows I can notice that they don't have the same contain (notebook doesn't contain the Tensorflow environment variable)
has comment: http://stackoverflow.com/comment/83252683
answer count: 3
has answer: http://stackoverflow.com/a/48137752
has comment: http://stackoverflow.com/comment/83252774
tagged with: python
tagged with: jupyter-notebook
has title: Tensorflow works in Python terminal but neither in notebook jupyter nor in Ipython
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83252601
has comment: http://stackoverflow.com/comment/83252644
has comment: http://stackoverflow.com/comment/83252752
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48137920
tagged with: anaconda
has comment: http://stackoverflow.com/comment/83252701
tagged with: ipython
type: Question

http://stackoverflow.com/comment/83311755
type: AnswerComment
comment on: http://stackoverflow.com/a/48165920
type: Comment
has text: @voland Valid approach, too. Downside of the enire dynamic approach is, of course, `O(N)` lookup as compared to `O(1)` dict lookup. But with a limited number of classes that shouldn't be an issue.
score: 0

http://stackoverflow.com/q/48018017
has body: I will be hosting a service that will be acting somewhat like a proxy for something I am a client to. So I want my ProxyService (a twisted.protocol server) to takes lots of actors (clients). On the server side of things, I need a global connection (only need 1 connection to it for all clients) to an ExistingService (code I didn't write, and I'm a client to it). When the ExistingService says something interesting, I need to broadcast it to all actors. When an actor says something to my ProxyService, I need to check if it looks good to me. If it does, I need to inform the ExistingService. I think I know how to solve this using global variables, but just wondering if better way to push the messages.
tagged with: events
tagged with: python
has answer: http://stackoverflow.com/a/48118256
has title: Python Twisted best way to signal events to a proxy
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/48118256
has comment: http://stackoverflow.com/comment/83017163
tagged with: twisted
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: asynchronous
favorite count: 0
tagged with: proxy
type: Question

persian
tags question: http://stackoverflow.com/q/48053799
tags question: http://stackoverflow.com/q/48067894
tag name: persian
type: Tag

http://stackoverflow.com/q/48045185
has body: I have a set of 10 3D vectors (as x,y,z values) and i was asked to find two principal component vectors of this vectors' array. How can do it? What are the calculations? I couldn't be able to find a simple math operations for this problem. I found PCA functions in MATLAB and some python libraries but i was asked to do all the calculations. Thanks for answers...
score: -1
has comment: http://stackoverflow.com/comment/83068038
type: Question
has comment: http://stackoverflow.com/comment/83073228
tagged with: vector
has answer: http://stackoverflow.com/a/48048486
tagged with: arrays
has comment: http://stackoverflow.com/comment/83068263
answer count: 1
tagged with: statistics
has title: Two Principal Component Vectors of 3D Vectors' Array
has comment: http://stackoverflow.com/comment/83064758
favorite count: 0
has comment: http://stackoverflow.com/comment/83062299
accepted answer: http://stackoverflow.com/a/48048486
downvote count: 2
upvote count: 1
tagged with: python
tagged with: matlab
type: AnsweredQuestion

http://stackoverflow.com/a/48049702
answers question: http://stackoverflow.com/q/48049635
has body: Use melt + set_index + sort_index - df.melt('column1', var_name='newCol')\ .set_index(['column1', 'newCol'])\ .sort_index().value column1 newCol A column2 0.020 column3 0.760 B column2 0.045 column3 1.300 C column2 0.230 column3 0.320 D column2 0.130 column3 0.670 Name: value, dtype: float64 Works with v0.20 and above. For older versions, use pd.melt instead.
type: Answer
has comment: http://stackoverflow.com/comment/83071749
downvote count: 0
has comment: http://stackoverflow.com/comment/83071586
score: 1
has comment: http://stackoverflow.com/comment/83071551
accepted answer of: http://stackoverflow.com/q/48049635
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/83074833
type: QuestionComment
has text: Is the kernel you are using in your jupyter notebook the conda environment in which the `bcolz` module is installed ? Because, on my computer, even when I launch the notebook inside a conda environment, the default kernel is always `Python 3` and not the conda environment.
comment on: http://stackoverflow.com/q/48050873
score: 0
type: Comment

http://stackoverflow.com/comment/83184843
type: QuestionComment
comment on: http://stackoverflow.com/q/48097015
has text: Is `A-B-C-D-B-C-E-B-F` an acceptable path from `A` to `F`?
score: 0
type: Comment

http://stackoverflow.com/q/48070833
has title: python hasattr() to differentiate a method and an attribute
downvote count: 0
has comment: http://stackoverflow.com/comment/83115571
possible better answer: http://stackoverflow.com/a/48070926
answer count: 3
accepted answer: http://stackoverflow.com/a/48070905
has comment: http://stackoverflow.com/comment/83115477
favorite count: 0
has answer: http://stackoverflow.com/a/48070926
has body: As some good people showed me that callable() can be used to solve this problem, I still found it to be a different question, because anyone that has this question in mind will not found the answer because he won't connect this directly to callable(). Plus I found a possible way to go around without using callable(), which is to use type() as showed in one of the answers from myself. Assume I create a simple class as Cls class Cls(): attr1 = 'attr1' def __init__(self, attr2): self.attr2 = attr2 def meth1(self, num): return num**2 obj = Cls('attribute2') print(hasattr(obj, 'attr1')) # &gt;&gt;&gt; True print(hasattr(obj, 'attr2')) # &gt;&gt;&gt; True print(hasattr(obj, 'meth1')) # &gt;&gt;&gt; True From what I learned, an attribute is a variable inside a class, and a method is a function inside a class. They are not the same. Apparently, there is no hasmethod() to be called by python. And it seems that hasattr() really gives all True to my test on 'attr1', 'attr2', 'meth1'. It does not differentiate from an attribute or a method. And if I use dir(), the attributes and methods will all show up in the output, and you can't really tell which one is what type either. Can someone please explain me why?
has answer: http://stackoverflow.com/a/48070905
score: 6
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/83115395
type: AnsweredQuestion
tagged with: oop
has answer: http://stackoverflow.com/a/48071126
linked to: http://stackoverflow.com/q/111234
type: Question

http://stackoverflow.com/comment/83320625
type: Comment
type: QuestionComment
has text: In that case the answer is no. Your code doesn't divide a list into any two halves. Have you written tests or anything that demonstrates what result your code generates?
comment on: http://stackoverflow.com/q/48169568
score: 0

http://stackoverflow.com/a/48133435
score: 0
type: AcceptedAnswer
has body: Reading found at https://docs.python.org/2/install/index.html With the quantumworldX installed, unzip the tar file. Next, open up a terminal/command prompt in the extracted folder. Or you can open a terminal and use the cd command to change directories to the extracted folder. After your terminal is in the folder, run the command: python setup.py install This will install quantumworldX as a module in python. However, before you are ready to import the module, you must have the required modules installed as well. The listed modules comes in the folder /quantumworldX.egg-info under "requires". They include: Numpy, Scipy, Matplotlib and Cycler. To install these modules, go back into your terminal and use pip as follows: pip install numpy pip install scipy pip install matplotlib pip install cycler Each after the other finishes. After you have setup.py installed and the prerequisites, you can test if you have it properly installed by running import quantumworldX as qwx in an IDLE. If you get no error, you have properly installed quantumworldX and may use it accordingly.
type: Answer
accepted answer of: http://stackoverflow.com/q/48132991
answers question: http://stackoverflow.com/q/48132991

http://stackoverflow.com/q/48050833
upvote count: 5
has answer: http://stackoverflow.com/a/48051442
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83073892
possible better answer: http://stackoverflow.com/a/48054236
type: Question
has answer: http://stackoverflow.com/a/48054236
answer count: 2
score: 5
favorite count: 0
has body: I've been wondering if there is a way to remove the title bar of a popup window: From this To this Thanks in advance! Edit: Code reference for future use: &lt;MyPopup@Popup&gt;: size_hint: None, None size: 300, 200 title: 'Close' title_color: 0.7, 0, 0, 0.9 separator_color: 0.4, 0.4, 0.4, 1 title_align: 'center' BoxLayout: orientation: 'vertical' padding: 5, 5, 5, 5 cols: 2 Label: color: 0.7, 0, 0, 0.9 center_x: root.center_x center_y: root.center_y text: 'Are you sure you want to exit?' BoxLayout: size_hint: 1, 0.6 Button: color: 0.7, 0, 0, 0.9 background_color: 0.4, 0.4, 0.4, 0.05 text: 'Yes' on_release: exit() Button: color: 0.7, 0, 0, 0.9 background_color: 0.4, 0.4, 0.4, 0.05 text: 'No' on_release: root.dismiss()
has title: How to remove popup title in kivy
tagged with: python
tagged with: kivy
accepted answer: http://stackoverflow.com/a/48051442

http://stackoverflow.com/q/48072537
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48072609
upvote count: 3
has answer: http://stackoverflow.com/a/48072609
has body: I have pandas dataframe in the following format: d = {'item_code': ['A', 'B', 'C', 'A', 'A', 'B', 'B', 'A', 'C'], 'year': ['2010', '2010', '2010', '2010', '2010', '2011', '2011', '2011', '2011']} df = pd.DataFrame(data=d) df This is how my dataframe looks like: item_code year 0 A 2010 1 B 2010 2 C 2010 3 A 2010 4 A 2010 5 B 2011 6 B 2011 7 A 2011 8 C 2011 I have used groupby to list each year and its corresponding items. df.groupby(['year', 'item_code']).size() This is the result: year item_code 2010 A 3 B 1 C 1 2011 A 1 B 2 C 1 dtype: int64 I want to get the top items in a year. For example for the year 2010 the top item is A. Similarly, for year 2011 the top item is B. How can I get that? And lets say I want to get the top N items for each year. How can I do that too?
has title: Pandas Dataframe groupby year and find top item
type: Question
score: 3
has answer: http://stackoverflow.com/a/48072571
tagged with: dataframe
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48072571

http://stackoverflow.com/comment/83097283
score: 0
has text: The Gender and Grade columns are examples. In reality the end user would be entering a dataset for this thing to analyse it. They may enter 2 columns, they may enter 10. Who knows. The code just needs to account for the fact that these two columns can vary by the number of columns and the number of categorical data inside them. I was just wondering if there was a elegant way of doing it without loops. What do you mean by a vote?
type: Comment
comment on: http://stackoverflow.com/a/48062053
type: AnswerComment

http://stackoverflow.com/q/48044859
tagged with: pandas
score: 2
answer count: 1
has title: Groupby and perform aggregation with multiple functions in pandas
downvote count: 0
has body: I have the following dataframe: date in out balance 01/01/2017 50 70 100 02/01/2017 100 10 190 ... ... ... ... I am creating a summary file (grouped by month) with the following code: df2 = df.groupby(pd.TimeGrouper(freq='M')) df2 = df.agg({'total_in': 'sum', 'total_out': 'sum', 'balance': 'last'}) However, I also want to create 'largest in' and 'largest out' columns. I tried the following df2 = df2.agg({'total_in': 'sum', 'total_out': 'sum', 'largest in': 'max', 'largest out': 'max', 'balance': 'last'}) However, this throws a Key Error for the new columns. I had hoped that I could create new columns in the Agg statement, but this appears not to be the case. Now I could off course add this columns in the normal database - but those values would be relatively meaningless on a per day basis, and it seems to be a waste of processing power / something that should be able to be done more efficiently. Is there a better way to do this?
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48044918
type: Question
tagged with: group-by
has comment: http://stackoverflow.com/comment/83060825
tagged with: dataframe
has comment: http://stackoverflow.com/comment/83060800
accepted answer: http://stackoverflow.com/a/48044918
tagged with: pandas-groupby

md5
tags question: http://stackoverflow.com/q/48129929
type: Tag
tag name: md5

http://stackoverflow.com/q/48015235
has answer: http://stackoverflow.com/a/48019383
tagged with: image-size
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48419329
has answer: http://stackoverflow.com/a/55089132
has comment: http://stackoverflow.com/comment/82999669
has comment: http://stackoverflow.com/comment/83006781
tagged with: pytorch
score: 1
tagged with: machine-learning
upvote count: 1
type: Question
has body: Can anyone help me how to fix this error? RuntimeError: invalid argument 2: size '[-1 x 400]' is invalid for input of with 1597248 elements at /Users/soumith/miniconda2/conda-bld/pytorch_1503975723910/work/torch/lib/TH/THStorage.c:37 class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(trainloader, 0): # get the inputs inputs, labels = data # wrap them in Variable inputs, labels = Variable(inputs), Variable(labels) # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.data[0] if i % 5 == 4: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 5)) running_loss = 0.0 print('Finished Training')
tagged with: torch
answer count: 3
has title: I get this error on pytorch "RuntimeError: invalid argument 2: size '[-1 x 400]"

http://stackoverflow.com/q/48101564
tagged with: scipy
type: Question
answer count: 2
score: 4
tagged with: filter
has answer: http://stackoverflow.com/a/48101718
upvote count: 4
favorite count: 0
tagged with: fft
has comment: http://stackoverflow.com/comment/83178997
tagged with: frequency
has body: Is there a way to create a quick bandpass filter via scipy or librosa in Python 3.6 for a 16KHz wav file to filter noise outside of human voice band of 300-3400Hz ? Here is a sample wav file with background noise at low frequency. UPDATE: Yes, I have already seen/tried How to implement band-pass Butterworth filter with Scipy.signal.butter . Unfortunately, the filtered sound is horribly deformed. Essentially, the whole code does this: lo,hi=300,3400 sr,y=wavfile.read(wav_file) b,a=butter(N=6, Wn=[2*lo/sr, 2*hi/sr], btype='band') x = lfilter(b,a,y) sounddevice.play(x, sr) # playback What am I doing wrong or how can this be improved so that the background noise is filtered out correctly. Here is the visualization of the original and filtered file using the link above. The visualization looks reasonable, but it sounds horrible :( How can this be fixed?
has answer: http://stackoverflow.com/a/48102936
accepted answer: http://stackoverflow.com/a/48102936
possible better answer: http://stackoverflow.com/a/48101718
tagged with: python
linked to: http://stackoverflow.com/q/12093594
type: AnsweredQuestion
has title: Create a band-pass filter via Scipy in Python?
downvote count: 0

http://stackoverflow.com/q/48135246
has comment: http://stackoverflow.com/comment/83247713
has comment: http://stackoverflow.com/comment/83247778
has title: list indices must be integers or slices not tuple
type: Question
score: 0
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83247737
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: I'm trying to reorganize my data to a specific format, and found stuck at the error message. I'm looking into a 16-columned csv file and I want to merge column 1-5 into a single column while also appending 10th column right next to it, while discarding the rest of the columns. I have about 30 of such csv files and would like to process all of them into a single comprehensive list. File names are iterative yet they can be defined by the number in the middle. Ptrain0dataset, Ptrain50dataset, Ptrain100dataset ... Here's the code I'm juggling with: clist=[] for i in range(0,17): a=i*50 with open('Ptrain' + str(a) + 'dataset,csv', 'r') as f: temp=f.readlines() temp2=[] for i in temp: j=i.replace('""', '') temp2.append(j.split(',')) for j in temp2: clist[str(a), j[0:5], j[9]] f.close() stacktrace: File "&lt;ipython-input-23-e7da8e2724f8&gt;", line 1, in &lt;module&gt; runfile('pfiles') File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "pfiles/aa.py", line 35, in &lt;module&gt; clist[str(a), j[0:5], j[9]] I can't seem to figure out whats the mistake in here.
has answer: http://stackoverflow.com/a/48135273
accepted answer: http://stackoverflow.com/a/48135273
type: AnsweredQuestion

http://stackoverflow.com/q/48027290
linked to: http://stackoverflow.com/q/32834946
has body: I have a Panda series of closing price of a stock, display as below: closingprice[date1] date1 &gt; 1/3/2017 151.732605 1/9/2017 152.910522 1/27/2017 153.945938 &gt; 2/23/2017 167.495438 3/6/2017 158.808716 3/9/2017 157.894333 &gt; 3/10/2017 157.513321 3/13/2017 156.7323 3/21/2017 158.856354 &gt; 3/24/2017 158.132462 4/3/2017 158.780151 4/12/2017 162.085281 I need to look for what is the closing price for 30 days later, e.g, I have 2017-01-03 and I would need to have 2017-02-02 closing price. So I did: date2 = date1 + pd.DateOffset(days=30) i have the new Service which shows below: closingprice[date2] &gt; 2/2/2017 159.731018 2/8/2017 160.418427 2/26/2017 NaN 3/25/2017 NaN &gt; 4/5/2017 159.065903 4/8/2017 NaN 4/9/2017 NaN As you can see, some date which are not located on business date and given me as NaN. If that's the case, how can I get the next business date price if the 30 days located on a weekend or holiday? e.g: Feb 26th nan need to replace to Feb 27th closing price.
answer count: 1
has answer: http://stackoverflow.com/a/48030930
type: UnansweredQuestion
tagged with: python
has title: Python Panda Series Next Market Date
type: Question
tagged with: series
score: 0
tagged with: pandas

http://stackoverflow.com/comment/83155535
comment on: http://stackoverflow.com/q/48017719
type: QuestionComment
type: Comment
score: 1
has text: Have you read some documents like [Creating your own Aggregate Functions](https://docs.djangoproject.com/en/2.0/ref/models/expressions/#creating-your-own-aggregate-functions) and/or [http://harkablog.com/inside-the-django-orm-aggregates.html](http://harkablog.com/inside-the-django-orm-aggregates.html) and/or [https://stackoverflow.com/questions/10340684/group-concat-equivalent-in-django](https://stackoverflow.com/questions/10340684/group-concat-equivalent-in-django) ? You may override something like the Concat function to reach your goal.

http://stackoverflow.com/a/48099646
has comment: http://stackoverflow.com/comment/83177523
type: AcceptedAnswer
has body: I'm new to plotly, but I infer the bars are centered on the ticks (the dates), and so plot is in fact showing the range you specify. (I agree that this is somewhat surprising behavior, aesthetically.) You can show the whole bar by changing the range you display using pandas.tseries.offsets.DateOffset: https://pandas.pydata.org/pandas-docs/stable/timeseries.html#dateoffset-objects import pandas as pd import plotly.offline as py from pandas.tseries.offsets import * n = 30 df = pd.DataFrame({"A": list(range(n))}, index=pd.date_range(start="2017-12-01", periods=n)) data = [{'x': df.index, 'y': df["A"], 'type': 'bar'}] layout = dict(xaxis=dict(range=[df.index[-10] + DateOffset(hours = -12), df.index[-1] + DateOffset(hours = 12)])) fig = dict(data=data, layout=layout) py.plot(fig) Output:
answers question: http://stackoverflow.com/q/48098331
accepted answer of: http://stackoverflow.com/q/48098331
score: 2
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/48139940
linked to: http://stackoverflow.com/q/39777648
has comment: http://stackoverflow.com/comment/83258246
has comment: http://stackoverflow.com/comment/100933405
tagged with: python
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/51722579
has answer: http://stackoverflow.com/a/48140121
has answer: http://stackoverflow.com/a/51722579
has comment: http://stackoverflow.com/comment/83258015
has body: I have been referring to the below article Spark cast column to sql type stored in string I am looking for the equivalent code in pyspark. The problem is that the answer in the above post uses classof[DataTypes] but DataTypes class is not available in pyspark. What I am trying to do is create the Schema dynamically. so, I have a List as below: &gt;&gt;&gt; sourceToHiveTypeList ['TimestampType', 'TimestampType', 'StringType', 'StringType', 'IntegerType', 'DoubleType'] and I have defined a UDF def TableASchema(columnName, columnType): return StructType([ StructField(columnName[0], getattr(pyspark.sql.types,columnType[0]), nullable = True), StructField(columnName[1], getattr(pyspark.sql.types,columnType[1]), nullable = True), StructField(columnName[2], getattr(pyspark.sql.types,columnType[2]), nullable = True), StructField(columnName[3], getattr(pyspark.sql.types,columnType[3]), nullable = True), StructField(columnName[4], getattr(pyspark.sql.types,columnType[4]), nullable = True), StructField(columnName[5], getattr(pyspark.sql.types,columnType[5]), nullable = True) ]) When I call the above UDF, I get error: &gt;&gt;&gt; schema = TableASchema(headerColumns, sourceToHiveTypeList) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in TableASchema AttributeError: 'module' object has no attribute 'TimestampType()'
type: Question
accepted answer: http://stackoverflow.com/a/48140121
has title: Converting string name to sql datatype in spark
tagged with: pyspark
answer count: 2
tagged with: apache-spark
linked to: http://stackoverflow.com/q/45981469

http://stackoverflow.com/a/48024741
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48019791
has body: job will never be in locals() because it is a local variable, and you are checking it before it is set. When the function returns, all local variables are unset, so the next time you call the function it will again be unset. Since you appear to be using classes, you should use a class variable, and initialize it to None class Whatever(): def __init__(self, ...): self.job = None ... def req_timer(self, option=None): if self.job is not None: ... Also, you have a lot of duplicated code that can be removed. For example, you might want to consider rewriting the function like this to reduce the replication: def req_timer(self, option): seconds_map = { "15 minutes": "*/15", "10 minutes": "*/10", "5 minutes": "*/5", "-": None, } scheduler = apscheduler.schedulers.background.BackgroundScheduler() if self.job is not None: self.job.remove_job('option_timer') self.job = None seconds = seconds_map.get(option, None) if seconds is not None: self.job = scheduler.add_job(self.req_client, 'cron', second=seconds, id='option_timer') scheduler.start()
has comment: http://stackoverflow.com/comment/83083033
type: Answer
has comment: http://stackoverflow.com/comment/83081714
has comment: http://stackoverflow.com/comment/83082284
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48019791

http://stackoverflow.com/q/48060598
score: 1
upvote count: 1
type: Question
has title: Using namespace in django for anchor tag
answer count: 2
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/48088671
downvote count: 0
tagged with: url
has answer: http://stackoverflow.com/a/48060744
favorite count: 0
has body: I am nobish in django ,started django before 3 weeks.I am facing a issue regarding url in anchor tag in html page.I am including all files music urls.py from django.conf.urls import url from . import views app_name = 'music' urlpatterns = [ url(r'^$', views.index,name='music index'), url(r'^albums/$', views.albums,name='albums'), url(r'^albums/(?P<album_id>[0-9]+)/details/$',views.album,name='details') ] main urls.py from django.conf.urls import include,url from django.contrib import admin urlpatterns = [ url(r'^$', include('music.urls')), url(r'^music/', include('music.urls')), url(r'^admin/', admin.site.urls), ] music views.py from django.shortcuts import render , get_object_or_404 from .models import Albums,Music def index(request): return render(request,'music/index.html',{}) def albums(request): all_albums = Albums.objects.all() return render(request,'music/index.html',{'allalbums' : all_albums}) def album(request,album_id): single_album = get_object_or_404(Albums,pk=album_id) return render(request,'music/details.html' ,{'album' : single_album}) index.html This is music Page {% for album in allalbums %} {{ album.album_name}} {% endfor %} settings.py INSTALLED_APPS = [ 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] but when I run this code ,I am getting this issue(attaching image) ..and one more thing .. I am using linux, django 1.11.7 version
possible better answer: http://stackoverflow.com/a/48060744
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48088671

http://stackoverflow.com/comment/83114583
type: AnswerComment
type: Comment
has text: that's a good alternative. But I want to know why it is being sorted.
comment on: http://stackoverflow.com/a/48066813
score: 0

http://stackoverflow.com/a/48088491
has body: I didn't test how far this is valid, but I have found a simple solution which seems to be working. By using bytes() function, it works somehow as strings. I can pass it to the lib in question like this. Thanks for the help everyone. Cheers.
score: 0
answers question: http://stackoverflow.com/q/48087091
type: Answer

http://stackoverflow.com/q/48133762
tagged with: python
score: 1
upvote count: 1
type: Question
tagged with: blender
tagged with: octree
tagged with: database
tagged with: point-cloud-library
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83246712
has answer: http://stackoverflow.com/a/48135596
has title: Creating a wavefront .obj file from Regular Grid Database
favorite count: 0
has body: I attempting to import a regular grid database into a 3D scene for visualization/simulation. The easiest way to do this I believe is to convert the Regular Grid Database into a format (e.g., wavefront .obj) that can be imported into Blender for example. The Regular Grid Data base has the following format: first line has three integers for example 3072 3072 10 The first line has three integers, denoting the dimensions of the grid. In the example above, the grid is 3072 x 3072 x 10 boxes. Assume 1 meter voxel cubes The reminder of the file has six columns 3072 3072 10 1437 1437 1 500 314.781433 4.82E-05 1437 1438 1 500 314.781433 4.82E-05 1437 1439 1 500 314.781433 4.82E-05 1437 1440 1 500 314.781433 4.82E-05 1437 1441 1 500 314.781433 4.82E-05 1437 1442 1 500 314.781433 4.82E-05 1437 1443 1 500 314.781433 4.82E-05 1437 1444 1 500 314.781433 4.82E-05 .... where The remainder of the file consists of lines with six columns of data. The first three columns indicate the voxel index (counting from 0). The fourth column indicates a material ID corresponding to an entry in a separate Material Database file (.mat). The fifth column indicates temperature in Kelvin. The final column indicates concentration in parts per million (ppm). To simplify the problem lets assume that we have a single material (material ID 500). If I can get this into a .obj file format then I can write a code to update other materials. Does anyone know of a way to do this other than by brute force? I can do it by brute force by generating a 3D grid then stepping through the regular grid file and checking to see if it is populated with a material property or not but this still does not solve the problem of getting it into a wavefront .obj file format. I grateful for your counsel here. Sambler offered some code to generate the grid in Blender directly. I was unable to get this to run in blender so I have modified it. This code runs in blender and produces outputs to the console. However I have not been suc…
type: UnansweredQuestion

http://stackoverflow.com/comment/83263557
comment on: http://stackoverflow.com/q/48142098
type: Comment
type: QuestionComment
score: 0
has text: So you have some input string and then you want the character counts of that string to be the weights to the random selection of characters for a different string?

http://stackoverflow.com/q/48086586
has comment: http://stackoverflow.com/comment/83148784
has comment: http://stackoverflow.com/comment/83148846
has comment: http://stackoverflow.com/comment/83148554
upvote count: 2
has comment: http://stackoverflow.com/comment/83148223
has body: I have a numpy array of points with shape (1000,3) where axis 1 takes on values [x,y,1] The points are at discrete values on a grid so an example array looks like: array=([1,2,1],[4,5,1],[2,3,1],...,[xN,yN,1]) I would like to dilate this 2d array, and by this I mean, for each [x,y,1] coordinate in the array, if [x±1,y±1,1] is not in the array append it to the array. currently I'm doing this with the following code: np.append(array, [array[:,0],array[:,1]+1,1]) np.append(array, [array[:,0]+1,array[:,1],1]) np.append(array, [array[:,0]+1,array[:,1]+1,1]) np.append(array, [array[:,0]-1,array[:,1],1]) np.append(array, [array[:,0],array[:,1]-1,1]) np.append(array, [array[:,0]-1,array[:,1]-1,1]) np.append(array, [array[:,0]+1,array[:,1]-1,1]) np.append(array, [array[:,0]-1,array[:,1]+1,1]) then I am using np.unique(array) to reduce down to unqiue elements. This method works, but it is too slow to run on large arrays with more than 100000 points, and it doesn't feel like a smooth solution. There must be a way to do this without duplicating so many points then having to find all unique instances. Is there a different (read:faster) way to do what I am doing?
type: Question
has comment: http://stackoverflow.com/comment/83148186
has comment: http://stackoverflow.com/comment/83149154
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48088529
has comment: http://stackoverflow.com/comment/83149169
has comment: http://stackoverflow.com/comment/83148313
tagged with: numpy
tagged with: array-broadcasting
score: 2
answer count: 1
downvote count: 0
has title: How to dilate a numpy array
has comment: http://stackoverflow.com/comment/83150272
favorite count: 0
has comment: http://stackoverflow.com/comment/83149100
has comment: http://stackoverflow.com/comment/83148278
has comment: http://stackoverflow.com/comment/83148604
tagged with: python
has answer: http://stackoverflow.com/a/48088529
has comment: http://stackoverflow.com/comment/83148262
has comment: http://stackoverflow.com/comment/83150032
has comment: http://stackoverflow.com/comment/83148252

http://stackoverflow.com/comment/83060392
comment on: http://stackoverflow.com/q/48044540
score: 1
type: Comment
type: QuestionComment
has text: Essentially I don't think you'd want `Frame` and `Canvas` as siblings to same parent `Tk`. You probably want to have `Frame` as a child _to_ `Canvas`.

http://stackoverflow.com/comment/85884817
has text: @cᴏʟᴅsᴘᴇᴇᴅ nope .....I received couple of downvote recent day ...have no idea about it ...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48158984

http://stackoverflow.com/a/48072552
answers question: http://stackoverflow.com/q/48072131
has comment: http://stackoverflow.com/comment/83119569
has body: Assignment Statements assigns reference of source variable to target variable. Let walk through an example to understand more &gt;&gt;&gt; a = 5 &gt;&gt;&gt; b = 6 &gt;&gt;&gt; a = b In this example b is source variable and a is the target variable. Now memory address for both of these variables are same. We can confirm this as well &gt;&gt;&gt; hex(id(a)), hex(id(b)) &gt;&gt;&gt; ('0x1002739e0', '0x1002739e0') Another test to confirm this is to use is operator &gt;&gt;&gt; a is b &gt;&gt;&gt; True Now coming back to your example. First statement &gt;&gt;&gt; a, b = b, a + b Assignes b to a and (a+b) to b. This happens as a single operation so both variables are different. We can apply above tests to confirm this &gt;&gt;&gt; a is b &gt;&gt;&gt; False &gt;&gt;&gt; hex(id(a)), hex(id(b)) &gt;&gt;&gt; ('0x1002739e0', '0x2008739t0') The second statement &gt;&gt;&gt; a = b &gt;&gt;&gt; b = a + b Assignes b to a and then (a+b) to b. These are two different statements, so at first step a and b are already identical. Thus the second statement is equivalent to b = b + b.
type: Answer
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/83088536
comment on: http://stackoverflow.com/a/48058157
type: AnswerComment
type: Comment
has text: Yes. It is an escape character *used in combination with other characters*, such as your own example `\n`. Why is this confusing you?
score: 0

http://stackoverflow.com/comment/83035754
comment on: http://stackoverflow.com/q/48032739
has text: read: [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/)
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48154910
has title: Seaborn jointplot: fixing bin range in marginals
downvote count: 0
has answer: http://stackoverflow.com/a/48187299
answer count: 1
tagged with: python
favorite count: 0
tagged with: seaborn
type: UnansweredQuestion
upvote count: 1
has body: I would like to fix the bin range for both the x- and y- marginal distributions on a hexbin plot, because I want to overlay the marginals with a plot of another distribution. I can set the number of bins using g=sns.jointplot(x='age',y='value',data=joint_data, space=0, color='g', kind='hex', stat_func = None, marginal_kws=dict(bins=num_bins)) and I can set the specific bins along both axes using g=sns.jointplot(x='age',y='value',data=joint_data, space=0, color='g', kind='hex', stat_func = None, marginal_kws=dict(bins=numpy.linspace(x_min, x_max,100)) but I want to define different ranges for the axes separately. There doesn't appear to be a marginal_kws for the axes individually.
has comment: http://stackoverflow.com/comment/83305803
score: 1
type: Question

http://stackoverflow.com/q/48070505
type: Question
answer count: 2
tagged with: neural-network
downvote count: 0
has answer: http://stackoverflow.com/a/48088160
possible better answer: http://stackoverflow.com/a/48080685
has body: I'm attempting to write a simple NN module, with 2 layers, first layer ReLU activation, output softmax with 3 classes (one-hot encoded). It seems theres something wrong with the way I'm using the softmax function, but I'm not sure what's going on. X is 178x13 Y is 178x3 Dataset I'm using is fairly simple, and can be found here. I keep getting the error: RuntimeError: dimension out of range (expected to be in range of [-2, 1], but got 3) . . import pandas as pd import numpy as np import torch from torch.autograd import Variable from sklearn.preprocessing import LabelBinarizer # Read in dataset, specifying that this set didn't come with column headers x = pd.read_csv('Datasets/wine.data', header=None) # Rename columns x.columns = ['Class', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10', 'A11', 'A12', 'A13'] y = x'Class'.values #turn class labels into one-hot encoding one_hot = LabelBinarizer() y = Variable(torch.from_numpy(one_hot.fit_transform(y)), ) x = Variable(torch.from_numpy(x.iloc[:, 1:14].values).float()) N, D_in, H, D_out = y.shape[0], x.shape[1], 20, 3 # Implement neural net with nn module model = torch.nn.Sequential( torch.nn.Linear(D_in, H), torch.nn.ReLU(), torch.nn.Linear(H, D_out), torch.nn.LogSoftmax(dim=3) ) loss_fn = torch.nn.NLLLoss learning_rate = 1e-4 optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) for t in range(500): y_pred = model(x) loss = loss_fn(y_pred, y) print("Iteration: %d | Loss: %.3f" % (t, loss)) optimizer.zero_grad() loss.backward() optimizer.step()
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/48088160
tagged with: python
has title: PyTorch Softmax Dimensions error
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83117567
tagged with: pytorch
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48080685

http://stackoverflow.com/q/48049621
type: AnsweredQuestion
score: 3
tagged with: list
upvote count: 3
has answer: http://stackoverflow.com/a/48049648
type: Question
has answer: http://stackoverflow.com/a/48049646
tagged with: nested-loops
downvote count: 0
accepted answer: http://stackoverflow.com/a/48049648
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has title: Unable to iterate "csv.reader" repeatedly - empty result on second iteration
possible better answer: http://stackoverflow.com/a/48049643
has answer: http://stackoverflow.com/a/48049643
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I have created list1 to include the unique values from a particular column by appending values identified as unique to it in order to perform a sort of "sum if". Below is the scenario I am struggling with, the inner loop, iterating through the csv rows is only executing once. Is there some special characteristic that makes iterating through rows in a csv file in the inner loop of a nested loop problematic? csv contents: Field1 row1 row2 row3 Code: datafile = open(r"my_file.csv", "r") myreader = csv.reader(datafile, delimiter=",") list1 = ["A", "B", "C"] for x in list1[:]: print(x) for y in myreader: print(y) Expected result: A row1 row2 row3 B row1 row2 row3 C row1 row2 row3 Actual result: A row1 row2 row3&lt; B C It appears only the initial iteration of the inner loop is working. If I replace the csv with another list it works fine: datafile = open(r"my_file.csv", "r") myreader = csv.reader(datafile, delimiter=",") list1 = ["A", "B", "C"] list2 = ["row1", "row2", "row2"] for x in list2[:]: print(x) for y in list2: print(y) gives expected result And I can iterate through the csv rows in a single loop no problem with the below: x = 0 for y in myreader: x = x + 1 print(y[2] + " INNER") So why won't it all work together?

http://stackoverflow.com/comment/83465118
type: Comment
score: 0
type: AnswerComment
has text: You are really helpful! However, I would like to perform dimensionality reduction on train_x. How can I convert the train_x and train_y back to the original format and save as 'newFile.txt'?
comment on: http://stackoverflow.com/a/48138509

http://stackoverflow.com/q/48045173
has comment: http://stackoverflow.com/comment/83065772
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/83066392
has comment: http://stackoverflow.com/comment/83066309
tagged with: tkinter
has title: How to draw a grid on the canvas and then prompt the user to enter data?
score: 0
has body: I'm learning how to use Anaconda because I want the statistics functions. However, I would like to do all of the work and data entry on the canvas with tkinter. Eventually, draw normal distributions. I am unsure how to draw a grid on the canvas and then prompt the user to enter data into four cells and then process the data all on the canvas. I would like this to eventually be a stand alone program. import tkinter as tk import numpy import math def fishers(): cell_a = input("Enter Cell A value: ") cell_b = input("Enter Cell B value: ") cell_c = input("Enter Cell C value: ") cell_d = input("Enter Cell D value: ") cell_a = float(cell_a) cell_b = float(cell_b) cell_c = float(cell_c) cell_d = float(cell_d) fenum = math.factorial(cell_a+cell_b)*math.factorial(cell_c+cell_d)* math.factorial(cell_a+cell_c)*math.factorial(cell_b+cell_d) feden = math.factorial(cell_a)*math.factorial(cell_b)*math.factorial(cell_c)* math.factorial(cell_d)*math.factorial(cell_a+cell_b+cell_c+cell_d) fe = fenum/feden print ("Fishers Exact: =\t {:&gt;8.4f}\n".format(fe)) #This is test code to see if I can write into the canvas self.fishers.canvas.create_text(100,10,fill="darkblue",font="Times 20 italic bold", text="We will enter the data here.") class Window(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.main_window() self.widgets() # All main window parameters go here def main_window(self): self.master.title("Quick-Statistics Calculator") self.master.geometry("1000x800") self.pack() def widgets(self): main_menu = tk.Menu(self.master, tearoff=0) self.master.config(menu=main_menu) # Create File Menu and Drop Down file = tk.Menu(main_menu, tearoff=0) file.add_command(label="Save") file.add_separator() file.add_command(label="Exit", command=exit) main_menu.add_cascade(label="File", menu=file) # Create Edit Menu and Drop Down edit = tk.Menu(main_menu, tearoff=0) edit.add_command(label="Undo") main_menu.add_cascade(label="Edit", menu=edit) #Create Means …
answer count: 1
has answer: http://stackoverflow.com/a/48047465
type: UnansweredQuestion
tagged with: canvas
has comment: http://stackoverflow.com/comment/83066344
has comment: http://stackoverflow.com/comment/83065787

http://stackoverflow.com/comment/124825074
comment on: http://stackoverflow.com/a/48065041
type: Comment
has text: This answer is now outdated. See the more modern solution using `observed=True` argument to `groupby`.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/83495031
has text: Is the warning a part of the API? The docs do not seem to give any guarantee that the warning will remain the same throughout versions, so this approach seems a bit fragile to me.
comment on: http://stackoverflow.com/a/48102207
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83129947
score: 0
type: QuestionComment
has text: Have you looked into using a virtual environment? See https://stackoverflow.com/questions/1534210/use-different-python-version-with-virtualenv
type: Comment
comment on: http://stackoverflow.com/q/48077808

http://stackoverflow.com/comment/83151627
score: 0
comment on: http://stackoverflow.com/q/48088490
type: Comment
type: QuestionComment
has text: did you try running with `python -tt yourscript.py`? This will throw an error if you've accidentally mixed tabs and spaces.

http://stackoverflow.com/q/48032057
type: AnsweredQuestion
score: 1
type: Question
has answer: http://stackoverflow.com/a/48032069
downvote count: 0
has comment: http://stackoverflow.com/comment/83034231
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/48032085
accepted answer: http://stackoverflow.com/a/48032069
possible better answer: http://stackoverflow.com/a/48032098
has answer: http://stackoverflow.com/a/48032098
has title: Conditional inside int(x) method even though it doesn't take Boolean values
upvote count: 1
tagged with: python
has body: I am studying the Python built-in method int(x), which casts a variable to int. The documentation is at https://docs.python.org/2/library/functions.html#int. In a code I found: errors += int(update != 0.0) This code simply increases or decreases an error variable. What i see is a conditional as a variable, even though the method doesn't take Boolean values. How is this possible?

http://stackoverflow.com/a/48123665
has comment: http://stackoverflow.com/comment/83224520
has comment: http://stackoverflow.com/comment/83224329
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48123641
has body: If you are using Python 2.7 or higher, you should use print as a function. Here is example usage: print('Block #{} has been added to the blockchain!'.format(block_to_add.index))
score: 0
type: Answer

http://stackoverflow.com/comment/83272559
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48147195
has text: Why would you expect the addresses to increase?

http://stackoverflow.com/q/48071239
tagged with: runtime-error
score: 0
tagged with: logfile
answer count: 1
has answer: http://stackoverflow.com/a/48071458
tagged with: exception
has title: How to create a log file for a python code?
tagged with: python
has comment: http://stackoverflow.com/comment/83116102
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48071458
has body: How to create a log file for a python code ? I have created an .exe file of a python code I need to save the exceptions into a separate log file.
type: Question
tagged with: error-log

http://stackoverflow.com/comment/83222071
comment on: http://stackoverflow.com/a/48118960
type: AnswerComment
score: 0
type: Comment
has text: That's pretty good! The only problem is that it generates beyond the max value. My aim was: (1) If the starting number is e.g. 44, then 8 random numbers should be generated, because my rule says "if the number is <51, then generate 8 random numbers. But the highest value of these 8 numbers is determined by the starting number, and thus when using 44, the random numbers should be like: 2, 14, 13, 28, 34, 38, 9, 43 (with being the highest number 43; all numbers above the starting number are not allowed).

http://stackoverflow.com/comment/83162503
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48093976
type: QuestionComment
has text: I usually put my common code in a separate `lib` directory and import it.

http://stackoverflow.com/comment/83055320
has text: I ran into similar problems with roots and fractions. I employ two strategies. Use the `decimal` module, to increase float point accuracy. But mainly I don't test `if x == int(x)`, but work instead solely with integers: `if i ** x == n`. Python has (theoretically) unlimited precision for integers. But i am a Python newbie, maybe professionals have better suggestions.
score: 0
comment on: http://stackoverflow.com/q/48042029
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48115954
has comment: http://stackoverflow.com/comment/83282036
has comment: http://stackoverflow.com/comment/83274209
has comment: http://stackoverflow.com/comment/83340941
has body: with selenium first, you can find the elements that you want to check with find_elements_by_xpath method and get the text out of it with .text and iterate through that text. right click on element and inspect than on inspection find XPath xpath_for_element=your path element_to_check_for_keyword = driver.find_elements_by_xpath(xpath_for_element) text_to_check_for_keyword=element_to_check_for_keyword.text then you can iterate through text_to_check_for_keyword to check if that keyword exists and you can create a while loop with time.sleep to set checking time for your own code above. edit: first of all, think of XPath as the path of that HTML element, so every element under the same category has similar paths. for example, India times have many sections on their webpage right? but you can iterate through all sections XPath by using * for example in the middle there is a TOP News section with a list. xpath of the let say 6th element is //*[@id="pageContent"]/div[1]/div/div[6]/div[2]/ul/li[1]/ul/li[6]/a so in order to reach every element in that section you use //*[@id="pageContent"]/div[1]/div/div[6]/div[2]/ul/li[1]/ul/li[*]/a that * gives you all elements of that area. after that, you do that for every section like Comments, Market news, and others and iterate.
answers question: http://stackoverflow.com/q/48113622
has comment: http://stackoverflow.com/comment/83267948
score: 0
has comment: http://stackoverflow.com/comment/83744265
type: Answer

http://stackoverflow.com/comment/83353437
has text: VGG is fine at the moment, for now I just want my setup to be running, perfomance comes much later. My setup now runs, a bit worse than the reference Linux version, but within the given limitations. The basic question however remains... What is the roi_pooling doing for patches smaller than the target size... Therefore I cannot mark your answer as "answer", I hope you understand that :/
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48166585
type: Comment

http://stackoverflow.com/comment/83251590
has text: The code, as it is formatted, will give error since segment_tree is a global function that needs to be defined so in the function.
comment on: http://stackoverflow.com/q/48137037
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48134269
downvote count: 3
tagged with: photo
type: Question
score: 3
has answer: http://stackoverflow.com/a/66160716
has comment: http://stackoverflow.com/comment/83245948
has comment: http://stackoverflow.com/comment/83266607
possible better answer: http://stackoverflow.com/a/56061136
linked to: http://stackoverflow.com/q/36555088
answer count: 7
has title: python pyinstaller bundle image in GUI to onefile EXE?
has answer: http://stackoverflow.com/a/56061136
has answer: http://stackoverflow.com/a/48199502
favorite count: 0
has body: I've successfully created an EXE file from python tkinter GUI which includes images. see the following code: lblLogo=Label(main) lblLogo.grid(row=3,column=11,rowspan=4) try: filelocation="C:/Documents/Python/ScreenPartNumberProgram/" KasonLogo=PhotoImage(file=filelocation+"KasonLogo.png") KasonLogo=KasonLogo.zoom(25,20) KasonLogo=KasonLogo.subsample(50,50) lblLogo.config(image=KasonLogo) icon=PhotoImage(file=filelocation+"KasonLogo.png") main.tk.call('wm','iconphoto',main._w,icon) except: print("warning: could not load photos") lblLogo.config(text="[KasonLogo.png]") the exe file opens and works perfectly on my computer. I used this command to get the .exe: pyinstaller --onefile --noconsole myscript.py The only problem is this file requires the image to be in the same folder or it doesn't show on the label. How can I get the image bundled into the EXE without requiring an external file? Thanks in advance edit: I looked at the links provided,did more research, and still haven't solved the issue. The program works only if the image is in the same folder. I'd really like to make it work without requiring an external image file. the resource_path technique doesn't seem to work for me either... I also tried modifying my code to use PIL's ImageTk and same issue. program loads image only if the external image file is in the folder with it.
tagged with: python
has answer: http://stackoverflow.com/a/72447439
upvote count: 6
has answer: http://stackoverflow.com/a/77642324
has answer: http://stackoverflow.com/a/77642634
tagged with: exe
type: AnsweredQuestion
tagged with: tkinter
has answer: http://stackoverflow.com/a/71136425
accepted answer: http://stackoverflow.com/a/48199502

http://stackoverflow.com/comment/83112827
type: QuestionComment
comment on: http://stackoverflow.com/q/48069455
score: 0
has text: so how would i fix it
type: Comment

http://stackoverflow.com/comment/83156531
type: QuestionComment
comment on: http://stackoverflow.com/q/48089903
has text: @zabusa can you be more elaborate and point me to right resources for my problem
score: 0
type: Comment

http://stackoverflow.com/comment/83031201
has text: I've looked at that and found no clear solution from the answers given there.
score: 0
comment on: http://stackoverflow.com/q/48029920
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83025604
score: 0
type: AnswerComment
type: Comment
has text: @davidjbeiler Okay, you mean you have NaNs in your data which you want to replace with 0?
comment on: http://stackoverflow.com/a/48027798

http://stackoverflow.com/a/48032312
answers question: http://stackoverflow.com/q/48026589
score: 0
has body: gridfs.GridFS.put isn't a context manager. It doesn't define __enter__ and __exit__ methods of the context management protocol. Using it directly without some modification as a context manager will result in an AttributeError. Using gridfs.GridFS.put as-is saves you few lines of code and more importantly having to manage opening and closing the GridFile.
type: Answer

http://stackoverflow.com/a/48118994
downvote count: 0
answers question: http://stackoverflow.com/q/48118870
type: Answer
upvote count: 1
score: 1
has body: You want to find the value of List[List[4]] First, let's substitute the inner part List[4] and it will equal 5 as we count from 0 in python so you have: list[0] = 1 list[1] = 1 list[2] = 2 list[3] = 3 list[4] = 5 and so on. So now after getting the inner part we can easily figure out the overall question as follows: List[List[4]] = List[5] = 8

http://stackoverflow.com/q/48037237
tagged with: python
tagged with: object
has body: I think I need help with my code, I can't tell what the error is or where to fix it. The following are a number of classes that handle a basic deck of playing cards and what it's suppose to do is randomly pick cards from the deck object and put them in the hand object, and then delete the objects from the hand object, so that the next hand I create won't pick up duplicates. Maybe this is an obtuse way of thinking about it, but it seemed to be the best way of managing a deck of cards as it would be in the real world. The problem is either in the logging method, or in the create_hand() method. When I look at my hand after I run my code, I see the cards in my hand are still in the deck, if I go to the report in the log. Instead, there are different cards that have been removed. It reports the right number of cards taken out of the deck, but it also only reports that hearts are taken out in the tallies that count the number of cards according to suit. However, my hand has a random assortment of unique cards, with unique values and suits. So that part works. class Suit(Enum): HEARTS = "Hearts" CLUBS = "Clubs" DIAMONDS = "Diamonds" SPADES = "Spades" class Card: def __init__(self, suit, value): self.suit = suit self.value = value if self.suit == 1: self.suit = Suit.HEARTS elif self.suit == 2: self.suit = Suit.CLUBS elif self.suit == 3: self.suit = Suit.DIAMONDS else: self.suit = Suit.SPADES #and a host of magic methods that are irrelevant class Deck: def __init__(self, deck_size): self.deck_size = deck_size self.deck = [] card_suit = 1 card_value = 2 while len(self.deck) &lt; self.deck_size: self.deck.append(Card(suit=card_suit, value=card_value)) card_value += 1 if card_value &gt; 14: card_suit += 1 card_value = 2 def log_deck(self): logging.info("Deck cards: {}".format(len(self.deck))) hearts = clubs = diamonds = spades = 0 for card in self.deck: if card.suit == Suit.HEARTS: hearts += 1 elif card.suit == Suit.CLUBS: clubs += 1 elif card.suit == Suit.DIAMONDS: diamonds +=…
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48055217
type: Question
answer count: 2
has title: Randomly swapping instance objects from one list to another
has answer: http://stackoverflow.com/a/48037383
upvote count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/59576167
type: Answer
has body: One of the possible ways to load weights locally is as follows: vgg = vgg16.VGG16(weights=&lt;path_to_weights_file&gt;) This will work fine. And there is no need to modify the vgg16.py file at all.
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/48129804
downvote count: 0

http://stackoverflow.com/a/48100763
has comment: http://stackoverflow.com/comment/83250530
score: 0
has comment: http://stackoverflow.com/comment/83259048
has comment: http://stackoverflow.com/comment/83182051
has comment: http://stackoverflow.com/comment/83241443
has comment: http://stackoverflow.com/comment/83181480
type: Answer
has comment: http://stackoverflow.com/comment/83180707
answers question: http://stackoverflow.com/q/48098611
has body: Buildozer is a Python module that does some actions to pack your app. This module being run by Python version it installed to. In your case you has Python 2 with buildozer installed to it. Requirements in buildozer.spec have nothing to do with your current environment. This requirements says to buildozer which recipes/modules it should download, compile if needed and pack inside your Android app. python3crystax means that buildozer will pack Python 3 located in Crystax NDK (and already compiled for Android) inside your Android app to run it's code.

http://stackoverflow.com/a/48171827
score: 2
has comment: http://stackoverflow.com/comment/83323253
has comment: http://stackoverflow.com/comment/83323400
has body: You need z=df.loc[(df['geneID'] != 'g2') | (df['transcriptLength'] == y)].copy(), i.e. you want 'or' instead of 'and'. So anything outside of g2, you keep, and if it's in g2, you want it not to have transcriptLength y. As currently written, you reject anything unless it is both not in g2 and does not have that transcriptLength.
accepted answer of: http://stackoverflow.com/q/48170811
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48170811
upvote count: 2
type: Answer

http://stackoverflow.com/q/48098785
has comment: http://stackoverflow.com/comment/83172778
has title: Detecting number crossing line in computer vision
accepted answer: http://stackoverflow.com/a/48099842
upvote count: 0
has comment: http://stackoverflow.com/comment/83172611
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48099842
has comment: http://stackoverflow.com/comment/83173562
linked to: http://stackoverflow.com/q/8655277
favorite count: 0
linked to: http://stackoverflow.com/q/5873566
has comment: http://stackoverflow.com/comment/83173496
has comment: http://stackoverflow.com/comment/83173230
type: Question
has body: I have a college assignment which considers openCV that I have to solve but we had close to none lectures on computer vision. Namely we are given around 10 videos in which numbers are crossing 2 lines if they cross one line then they are added to the sum, if they cross second line they will be subtracted from the sum. Videos: https://drive.google.com/drive/folders/0B1ZJXQY32LBUU3FiTS14a3NZd1U What I know at the moment is that I would need to use Hough transformation to find lines. And that I will need somehow to detect the numbers. What my questions are how will I detect that number has crossed the line? which number has crossed it? detect overlap between numbers crossing one line?
downvote count: 2
tagged with: python
tagged with: computer-vision
score: -2
answer count: 1
tagged with: opencv
tagged with: conv-neural-network

http://stackoverflow.com/comment/83318834
score: 0
comment on: http://stackoverflow.com/q/48169101
has text: @tripleee Thanks to the missing piece you pointed me, I finally managed to do it, see here: https://stackoverflow.com/a/48169788/1422096, but the bad news is that the recipient server is rejecting me ;) `Recipient address rejected: Access denied`.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83242912
comment on: http://stackoverflow.com/a/48119756
type: AnswerComment
type: Comment
score: 1
has text: Even though this is a nice attempt to solve the problem, I am not sure if the OP is going to switch to it. We've already gone through multiple [rounds of reviews](https://codereview.stackexchange.com/q/180772/24208) with this code and even [suggested a working Scrapy spider](https://codereview.stackexchange.com/a/182196/24208) which is going to outperform both of the OP's and this solution by a serious margin. I don't know the OP's motivation but I think here he wanted to get more understanding why his approach does not scrape all the data. Does yours and how do you know? Thanks.

http://stackoverflow.com/comment/83297525
score: 0
type: AnswerComment
type: Comment
has text: how do i do, does not equal 3rd line?
comment on: http://stackoverflow.com/a/48158697

http://stackoverflow.com/comment/83099687
type: QuestionComment
comment on: http://stackoverflow.com/q/48060799
has text: I am still confusing with what did you say. Sorry I am quite new in this case. I just tried with my own codes but it didn't work at all. `print(predicted_label) if predicted_label=='positive': img=Image.fromarray(predicted_label) img=Image.convert('L') img.save(saveincorrect + '/' + f) else: img=Image.fromarray(predicted_label) img=Image.convert('L') img.save(savecorrect + '/' + f)`
score: 0
type: Comment

http://stackoverflow.com/comment/88884081
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49277025
type: Comment
has text: It works, kind of, but leads to a memory overflow problem. As a result, I cannot use your solution.

http://stackoverflow.com/a/48174004
score: 1
has comment: http://stackoverflow.com/comment/83330749
upvote count: 1
answers question: http://stackoverflow.com/q/48173166
has comment: http://stackoverflow.com/comment/83335355
type: Answer
has body: A bit longer then Joe's solution, but I like functions more. I did not correct your code, because certain parts were missing - rewriting seemed a better option keeping to stuff you did use. After gianluca answer "what" to do I implemented an example of that for you. I use the with open(...) as f: instead of your type of file reading as it automatically will close/flush/dispose of the filehandle when leaving the following block. Its the recommed way to operate with files. Dictionariesis a data structure for fast key/value access and better suited to your problem then simple strings. See also reading-and-writing-files Reading the whole file input loop until done, modifying the dict then (if needed) saving it. Breaking up funcionality into funcitons is that have a limited scope and are easier to understand helps keep the code cleaner. def readFile(fn): """Read the file given as by filename fn. Expected format: one key:value per line, key being a name, value a string as age. Returns a dictionary of the parsed contents key:value if no errors occure. Returs False on IOError or FileNotFoundError""" try: with open(fn,"r") as f: lines = f.read().split("\n") # read all, split at linebreaks print(lines) # debugging output rv = {} for l in lines: # parse all lines item =l.split(":",2) # split each if item is not None and len(item)==2: # must be 2 parts rv[item[0]] = item[1] # put key/valu into dict return rv # return dict except IOError: return False # error - return false except FileNotFoundError: pass # error - no file, thats ok return {} # no file found, return empty dict def saveFile(fn,famil): """Saves a dictionary famil as filename fn. Produced format: one key:value per line, key being a name, value a string as age. Overwrites existing file of same name with new contents.""" with open(fn,"w+") as f: for i in famil: # for all keys in dict f.write(i + ":" + famil[i] + "\n") # write file fileName = "FamilyAges.txt" # consistent filename family = readFile(fileName) # read it …
downvote count: 0

http://stackoverflow.com/a/48052162
accepted answer of: http://stackoverflow.com/q/48052125
type: Answer
answers question: http://stackoverflow.com/q/48052125
upvote count: 13
score: 12
type: AcceptedAnswer
downvote count: 1
has body: Some things to note here - If you're using only two columns, calling apply over 4 columns is wasteful Calling apply is wasteful and inefficient, because it is slow, uses a lot of memory, and offers no vectorisation benefits to you In apply, you're dealing with scalars, so you do not use the .str accessor as you would a pd.Series object. title.contains would be enough. Or more pythonically, "lip" in title. gender.isnull sounds completely wrong to the interpreter because gender is a scalar, it has no isnull attribute Option 1 np.where m = df.gender.isnull() & df.title.str.contains('lip') df['gender'] = np.where(m, 'women', df.gender) df category gender sub-category title 0 health&beauty women makeup lipbalm 1 health&beauty women makeup lipstick 2 NaN women NaN lipgloss Which is not only fast, but simpler as well. If you're worried about case sensitivity, you can make your contains check case insensitive - m = df.gender.isnull() & df.title.str.contains('lip', flags=re.IGNORECASE) Option 2 Another alternative is using pd.Series.mask/pd.Series.where - df['gender'] = df.gender.mask(m, 'women') Or, df['gender'] = df.gender.where(~m, 'women') <!- -> df category gender sub-category title 0 health&beauty women makeup lipbalm 1 health&beauty women makeup lipstick 2 NaN women NaN lipgloss The mask implicitly applies the new value to the column based on the mask provided.

http://stackoverflow.com/q/48091492
favorite count: 0
has title: python offline plotly saves the file always in default file name how to save in differrent name
tagged with: python-3.x
upvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/48093839
tagged with: plotly
score: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48093839
type: Question
tagged with: python
has body: I have the following code to graph using plotly offline . import plotly from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import plotly.graph_objs as go init_notebook_mode(connected=True) #import plotly.plotly as py ...... ...... ...... fig = dict(data=data, layout=layout) iplot(fig, filename = 'result.html') plot(fig,show_link = True) This stores the html output in a local drive where the python files is available but it always stores with the default file name called temp-plot.html This overwrites the file all time . How to save the file in desired name in html format using offline plotly what is the change in the code that would resolve this issue.

http://stackoverflow.com/comment/83117273
score: 0
type: Comment
type: QuestionComment
has text: @JohnGordon I'm using the DHT22 and the MAX31855. The MAX31855 works well, but the DHT22 isn't working. There must be a two second delay between each reading for the DHT22.
comment on: http://stackoverflow.com/q/48071393

http://stackoverflow.com/a/48068677
has body: IIUC, your index is not continue , when you create the pd.Series, it auto assign the index from 0 to len(s)-1, dataframe assign is base on the index , index miss match will create the NaN df=pd.DataFrame({'col':[1,2,3]},index=[1,2,3]) s=pd.Series([d*2 for d in df.col]) df['New']=s df Out[170]: col New 1 1 4.0 2 2 6.0 3 3 NaN df['New2']=s.values df Out[172]: col New New2 1 1 4.0 2 2 2 6.0 4 3 3 NaN 6
answers question: http://stackoverflow.com/q/48068607
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83111020
has comment: http://stackoverflow.com/comment/83110984
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48068607

http://stackoverflow.com/comment/83084775
score: 0
has text: The `statistics` module lives in a file called `statistics. py`. Having your own module of the same name in the local folder takes precedence.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48045947

http://stackoverflow.com/a/48033454
has body: set saves only unique values arr=[0, 2, 1, 1, 2] arr = [(s, arr.count(s)) for s in set(arr)] # [(0, 1), (1, 2), (2, 2)] update (thanks to @JonClements) s = {} for i, v in enumerate(arr): s.setdefault(v % 3, []).append(i) print(s) # {0: [0], 1: [2, 3], 2: [1, 4]}
accepted answer of: http://stackoverflow.com/q/48033318
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83036973
type: Answer
has comment: http://stackoverflow.com/comment/83037119
has comment: http://stackoverflow.com/comment/83037202
answers question: http://stackoverflow.com/q/48033318
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83037145

http://stackoverflow.com/q/48142702
tagged with: python
accepted answer: http://stackoverflow.com/a/48142765
has body: I'm new to Python and Pycharm, so I'm having trouble being able to use nltk. I downloaded nltk using command prompt on windows. I'm able to run from nltk.book import * from the command prompt, but when I try to do it in Pycharm it doesn't recognize nltk. I only have one version of Python installed (3.6.4). If anyone could give me some information on this I would appreciate it. I've watched videos and read previous posts on here, but none of them worked. Thanks in advance.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83263584
upvote count: 2
score: 1
downvote count: 1
type: Question
tagged with: nltk
has title: Python nltk won't work on Pycharm
has answer: http://stackoverflow.com/a/48142765
answer count: 1
favorite count: 0
tagged with: pycharm

http://stackoverflow.com/comment/83265165
type: QuestionComment
has text: To get the most out of the site it is important to [ask good questions](http://stackoverflow.com/help/how-to-ask), that includes creating a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example.
comment on: http://stackoverflow.com/q/48143529
type: Comment
score: 1

http://stackoverflow.com/a/54817830
answers question: http://stackoverflow.com/q/48172185
type: Answer
has body: I have a one-liner solution. Use the .option_add() method after declaring ttk.Combobox. Example: cbb = ttk.Combobox(root, justify='center', values=(0, 1, 2)) # original cbb.option_add('*TCombobox*Listbox.Justify', 'center') # new line added
downvote count: 0
score: 5
upvote count: 5

http://stackoverflow.com/q/48123648
possible better answer: http://stackoverflow.com/a/48126181
accepted answer: http://stackoverflow.com/a/48123734
has answer: http://stackoverflow.com/a/48126181
answer count: 2
tagged with: sqlite
score: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/48123734
linked to: http://stackoverflow.com/q/48103235
type: AnsweredQuestion
tagged with: python-3.x
has body: I'm a really rookie python(3.X) student. I'm working on some simple script to training my skill. In the last one, I'm printing out some results for my Blood Bowl 2 PC-game league thanks to an external site (mordreck.com/goblinspy/) who collects stas for me without I have to learn the game developer's API and makes them avaible for download like an sqlite database. I use a really simple csv with this structure, where every row is a different toruanment/league I play: Turnament name, torunament's sqlite db link. And I also have this script that checks the csv, gather the sqlite link, download the DB, and check the league last results and some other info's (like the datetime the match ends), This is the script (I know, is really uncorrect, long and "basic" but I'm still learning how to improve my skills and makes better codes! Sorry!): ### IMPORT STATEMENT ### import csv, sys, os, urllib.request, sqlite3, datetime, pandas, time ### VARIABLES ### datapath = os.path.dirname(sys.argv[0]) + ('\\data\\') #!!!HARDOCDED PATH!!!! datafile = 'sqlcompetitions.csv' #!!!HARDOCDED PATH!!!! ### DEFINING FUNCTIONS ### def sql_reader(db_file): #SIMPLY AN SQL READER try: conn = sqlite3.connect(db_file) return (conn) except: print("Something goes wrong!") return None def downloader(pathname, file): #READ THE CSV, AND DOWLOAD THE SQLITE DB FOR EVERY LINK IN ROW with open (pathname + file, newline='') as competitionscsv: next(competitionscsv) competitions = csv.reader(competitionscsv, delimiter=',') for row in competitions: filename = pathname + row[0] print('collecting data from %s \n' % row[0]) sqlfile = urllib.request.urlretrieve(row[1], filename +'.sqlite') print ('data collected for season: '+ row[0] + '!\n') def extract_matches(path): #READ EVERY .SQLITE file in the folder and extract values I'm looking for for files in os.listdir(path): if files.endswith('.sqlite'): db = sql_reader(path + files) cursor = db.cursor() cursor.execute("SELECT finished, tvhome, idracehome, coachhome, te…
has title: Date comparison code implementation in python (plus some general code optimization)
type: Question

http://stackoverflow.com/comment/83226174
type: Comment
type: QuestionComment
has text: You should import at the beginning of your source file!
score: 3
comment on: http://stackoverflow.com/q/48124627

http://stackoverflow.com/comment/121863360
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48151386
has text: Great solution! BTW: dicts are now ordered in Python, but it can be changed in the future Python releases. So, probably OrderedDict is more robust.

http://stackoverflow.com/q/48090648
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Flask Restful Reqparse required=True Error handling
answer count: 0
has comment: http://stackoverflow.com/comment/83436833
upvote count: 1
type: Question
has body: I am using flask_restful.reqparse for parsing arguments. Now I want "name" argument must be required. So I wrote this: from flask_restful import reqparse parser = reqparse.RequestParser() name= parser.add_argument("name", required=True, help="name is missing") Now I want to handle error that name is not there in request. How can I do this? Currently, I am sending this request using cURL curl -X POST \ http://localhost:5000/user \ -H 'cache-control: no-cache' \ -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' It shows 400 Bad Request, I want to send a json response instead of this. How can I do that?
score: 1
tagged with: flask-restful
tagged with: python-2.7
downvote count: 0
tagged with: flask

http://stackoverflow.com/q/48156691
has comment: http://stackoverflow.com/comment/83292407
has comment: http://stackoverflow.com/comment/83292598
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83292640
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83292337
tagged with: tuples
tagged with: args
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48156818
tagged with: list
has comment: http://stackoverflow.com/comment/83292680
accepted answer: http://stackoverflow.com/a/48156818
has title: How to validate the length of nested tuple passed to a function?
possible better answer: http://stackoverflow.com/a/48156832
answer count: 3
has comment: http://stackoverflow.com/comment/83292384
has answer: http://stackoverflow.com/a/48156832
upvote count: 1
has body: I am building a function that accepts the list of tuples. For example: my_list = [ ("str1", 1, 11), ("str2", 2, 22), ("str3", 3, 33), ("str4", 4, 44) ] I want to create a function with definition such that it will ONLY accept the parameters with the size of each nested element as "3". How can I define my function to accept list only of my desired nested length? Here is the sample code snippet of what I am trying to achieve (I know it is syntactically incorrect): def newattr_ratio(data, *(name,idx,idy)): for name,idx,idy in *(name,idx,idy): data[name]= data[data.columns[idx]]/data[data[columns[idy]]] How can I create a function with such parameter definition?
has comment: http://stackoverflow.com/comment/83292467
has comment: http://stackoverflow.com/comment/83292377
has comment: http://stackoverflow.com/comment/83292773
has answer: http://stackoverflow.com/a/48156712

http://stackoverflow.com/comment/83241022
score: 1
has text: You should use built-in `bisect` module.
comment on: http://stackoverflow.com/a/48130571
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48031595
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48031510
type: Answer
has body: When you say, if color == 'blue' or 'Blue': it's interpreted as, if (color == 'blue') or ('Blue'): which is true if color == 'blue' is true, or if 'Blue' is true. Blue is always true. Same with the other colors You could do something like: if color in [ 'blue', 'Blue']: Which will check whether color exists within the list of colors. But what about 'BlUe', 'bLuE', etc? Here's an even better solution. if color.lower() == "blue": Now it matches any capitalization of blue! Next, consider this part: if Initials == 'YNH': if Age == '42': if DOB == '1/27/74': print('Welcome Young Nathan Heather') ... ... ... else: print('Sorry, Wrong Credentials Entered') else: print('Sorry, Wrong Credentials Entered') else: print('Sorry, Wrong Credentials Entered') That's a lot of repetition, but also a lot of unnecessary indentation, and that makes the code harder to read and harder to debug. Why not something more like: if Initials == 'YNH' and Age == '42' and DOB == '1/27/74': print('Welcome Young Nathan Heather') ... ... ... else: print('Sorry, Wrong Credentials Entered') Do it that way, and your code will be easier to read, and easier to write too!

http://stackoverflow.com/comment/83233852
score: 0
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow. It's great that you edited your question with code, but... python has very specific formatting rules. And without properly formatting the code you posted, it's impossible to read it. Please edit again to format correctly, with correct indentation.
comment on: http://stackoverflow.com/q/48128378

http://stackoverflow.com/comment/83319030
has text: My question is, is this the right way to get group elements, to give us sum=S.
comment on: http://stackoverflow.com/q/48169568
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83022073
has text: The documentation for the run function says "The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle."
type: AnswerComment
comment on: http://stackoverflow.com/a/48026188
type: Comment
score: 1

http://stackoverflow.com/q/48045952
answer count: 2
upvote count: 1
downvote count: 1
has body: I'm trying to create a script that matches all numbers, including any number(s) with a leading $ (e.g. $12), a trailing % (e.g. 12%), a decimal inside (e.g. 1.24550), or a comma inside (e.g. 1,250,000), or a space in between (e.g $12,500 1234) When I try to put this all together into one line, I can't get it to work correctly. One issue was that it kept grabbing letters/words and unnecessary white space. I tried experimenting, unsuccessfully, with different anchors as a way of resolving the letters/white space issue. I came up with this: ^\$?\.?\d+\.?\,?\d+\.?\,?\%?\s?\d+$ This works for most input, however, it won't work with input like: asbdf 12234 It just skips the numbers altogether. If I remove the anchors, then it will match the numbers, but will also grab a bunch of white space so I'm not sure what to do here.
has answer: http://stackoverflow.com/a/48046008
has answer: http://stackoverflow.com/a/48045996
favorite count: 0
accepted answer: http://stackoverflow.com/a/48045996
possible better answer: http://stackoverflow.com/a/48046008
tagged with: python
tagged with: regex
type: AnsweredQuestion
type: Question
has title: Using Regex in Python to capture any number(s) with a leading $, a trailing %, or any number with a decimal, a comma or space
score: 0

http://stackoverflow.com/comment/83061976
type: QuestionComment
has text: try this driver.get(" https ://www.google.com")
score: 0
comment on: http://stackoverflow.com/q/48045412
type: Comment

http://stackoverflow.com/comment/83296980
score: 0
comment on: http://stackoverflow.com/q/48144690
type: Comment
type: QuestionComment
has text: Thank you @RoadRunner Yep- this works perfect.

variables
tag name: variables
tags question: http://stackoverflow.com/q/48081103
tags question: http://stackoverflow.com/q/48164539
tags question: http://stackoverflow.com/q/48053907
type: Tag
tags question: http://stackoverflow.com/q/48024806
tags question: http://stackoverflow.com/q/48145435
tags question: http://stackoverflow.com/q/48100313
tags question: http://stackoverflow.com/q/48040033
tags question: http://stackoverflow.com/q/48066179
tags question: http://stackoverflow.com/q/48126858
tags question: http://stackoverflow.com/q/48156384
tags question: http://stackoverflow.com/q/48085291
tags question: http://stackoverflow.com/q/48054569
tags question: http://stackoverflow.com/q/48134261
tags question: http://stackoverflow.com/q/48023680

http://stackoverflow.com/comment/83255799
score: 0
type: Comment
type: AnswerComment
has text: @ayhan Oh nice! using `filter`. Will you add an answer?
comment on: http://stackoverflow.com/a/48139154

http://stackoverflow.com/comment/83031518
has text: By "my server" you mean "my WSGI server"?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48030571
score: 0

http://stackoverflow.com/comment/83060802
comment on: http://stackoverflow.com/q/48044687
type: QuestionComment
has text: I've tried using raw_input and still get the same result
type: Comment
score: 0

http://stackoverflow.com/comment/83171457
score: 0
type: Comment
type: QuestionComment
has text: No, pseudoinverse() is called just with the matrix, the algorithm in R just uses that. In C I use 1E-15.
comment on: http://stackoverflow.com/q/48097973

http://stackoverflow.com/comment/83330812
type: QuestionComment
has text: What does the lower-left corner say your interpreter is set to? If that doesn't point to the interpreter you are expecting then click on it and change it. If it does then please file an issue.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48135624

http://stackoverflow.com/q/48158528
tagged with: encryption
has comment: http://stackoverflow.com/comment/83296713
tagged with: python
has comment: http://stackoverflow.com/comment/83297521
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48159293
tagged with: java
has comment: http://stackoverflow.com/comment/83296689
has comment: http://stackoverflow.com/comment/83297493
downvote count: 1
has comment: http://stackoverflow.com/comment/83296562
type: Question
has body: I have created the following python code import base64 from django.conf import settings from Crypto.Cipher import AES BS = 16 def pad(s): return s + (BS - len(s) % BS) * chr(BS - len(s) % BS) def unpad(s): return s[0:-s[-1]] class AESCipher: def __init__(self): self.key = settings.SECRET_KEY def encrypt(self, raw): raw = pad(raw) iv = settings.SECRET_IV.encode('utf-8') cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(cipher.encrypt(raw)) def decrypt(self, enc): enc = base64.b64decode(enc) iv = settings.SECRET_IV.encode('utf-8') cipher = AES.new(self.key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(enc)) def encryptstring(self, raw): raw = self.encrypt(raw) raw = raw.decode('utf-8') return raw def decryptstring(self, raw): raw = raw.encode('utf-8') raw = self.decrypt(raw) raw = raw.decode('utf-8') return raw This code returns a base64 encrypted string (i.e. VgRaS+J3MSmguabaf+9fJw==). I have also created a java function, that should create the same thing, but it doesn't match. public void login() { SecretKeySpec keySpec; IvParameterSpec ivSpec; Cipher cipher; String key = ""; String iv = ""; try { keySpec = new SecretKeySpec(key.getBytes(), "AES"); ivSpec = new IvParameterSpec(iv.getBytes()); cipher = Cipher.getInstance("AES/CBC/NoPadding"); String test = "Test"; String newString = ""; char paddingChar = ' '; int size = 16; int x = test.length() % size; int padLength = size - x; for (int i = 0; i &lt; padLength; i++) { newString += paddingChar; // test += paddingChar; } newString += test; byte[] res; cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); res = cipher.doFinal(newString.getBytes()); for(int i = 0; i &lt; res.length; i++) { System.out.print(res[i] + ", "); } System.out.println(""); System.out.println(bytesToHex(res)); String base = Base64.encodeToString(res, Base64.DEFAULT); System.out.println(base); // TODO: VgRaS+J3MSmguabaf+9fJw== // OyuUHNsBQ3Zuy4UGY4fUdQ== } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (NoSuchAlg…
upvote count: 0
has comment: http://stackoverflow.com/comment/83297617
score: -1
has title: Android AES encryption with python AES encryption
has answer: http://stackoverflow.com/a/48159293
answer count: 1
has comment: http://stackoverflow.com/comment/83296616
has comment: http://stackoverflow.com/comment/83296813
favorite count: 0
has comment: http://stackoverflow.com/comment/83296654

http://stackoverflow.com/comment/83090552
has text: you absolutely correct and i already work with but this is an old legacy that i need to maintained. anyway, thank you it was helpful
score: 0
comment on: http://stackoverflow.com/q/48059093
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83063655
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48045303
type: Comment
has text: And just out of curiosity is it possible to restore `app.ui` file from `app.py` file also? As I am not able to find anything related to this anywhere also @ekhumoro

http://stackoverflow.com/q/48130524
has comment: http://stackoverflow.com/comment/83247283
tagged with: pyqt5
type: Question
has comment: http://stackoverflow.com/comment/83240110
linked to: http://stackoverflow.com/q/35527439
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48131549
has body: Hi im trying to understand threading in pyqt5. Iv'e outlined the process i use currently. Is this the correct way or is there a better way? Note, i am a complete threading noob. This is how i pass data from GUI object. For example a combobox has changed, i have a self.comboBox.activated.connect(comboBoxChanged) in GUI class and then that corresponding function sets SharedVars.comboBoxChanged = True and then in one of the threadloops i check and see if SharedVars.comboBoxChanged == True and if it is do self.updateOtherStuffWhenComboBoxChanged.emit(getData()) and SharedVars.comboBoxChanged = False class SharedVars(): ... #This is my GUI class class Ui_MainWindow(QThread, SharedVars): def setupUi(self, MainWindow): #self.table stuff #this is the class i start threads, get a response and update the GUI class MainUIClass(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super().__init__() self.setupUi(self) self.threadclass = ThreadClass() self.threadclass.start() self.threadclass.updateTable.connect(self.updateTable) self.threadclass2 = ThreadClass2() self.threadclass2.start() self.threadclass2.etc.connect(self.etc) def updateTable(self, val): #print("update self.table stuff") def etc(self, val): #print("update other stuff on gui") #my first thread. If i have network calls that block i use several threads class ThreadClass(QtCore.QThread, SharedVars): updateTable = pyqtSignal(list) def __init__(self, parent=None): super().__init__() def run(self): def getData(): ... return [data] while True: self.updateTable.emit(getData()) #my second thread class ThreadClass2(QtCore.QThread, SharedVars): etc = pyqtSignal(list) def __init__(self, parent=None): super().__init__() def run(self): def getData(): ... return [data] while True: self.etc.emit(getData()) if __name__ == "__main__": a = QtWidgets.QApplication(sys.argv) app = MainUIClass() app.show() sys.exit(a.exec_()) Perhaps there is a better way. Perhaps i can send a signal directly from GUI object to thre…
type: UnansweredQuestion
tagged with: multithreading
has title: Is my way of using QThread correct/optimal?
tagged with: python
tagged with: qthread

http://stackoverflow.com/comment/83223173
comment on: http://stackoverflow.com/q/48123133
type: QuestionComment
has text: You can force a garbage collection run with `gc.collect` as explained [here](https://stackoverflow.com/q/1316767/289011) but you're not guaranteed that those objects will be actually freed immediately (they actually won't be at all they're still referenced somehow,) As you can see by reading the links provided in that other SO question I linked, garbage collection is not trivial (at all) Also, python might actually mark the memory as "free" but still keep it internally allocated (see [this other thread about it](https://stackoverflow.com/q/15455048/289011) )
type: Comment
score: 2

http://stackoverflow.com/comment/83017787
type: Comment
has text: Your file path is wrong. The file is located in `path`, not in `os.getcwd()`.
comment on: http://stackoverflow.com/q/48024253
type: QuestionComment
score: 3

http://stackoverflow.com/q/48170112
has body: I am trying to import some specific libraries using python. it should be easy like importing numpy for example like so: import osgeo.gdal, gdal from osgeo.gdalconst import * But it seemed to me like the packages gdal and osgeo are missing so I went to the project interpreter to add these packages, Sadly i did not find the package osgeo and the package gdal could not be installed ... I looked it up in the net but it seems that there is no exact way to solve the matter. I am using Ubuntu 16,04 with python 2.7.12 and PS GDAL is Geospatial Data Abstraction Library This the error message that I am getting: Collecting gdal Using cached GDAL-2.2.3.tar.gz Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/GDAL.egg-info writing pip-egg-info/GDAL.egg-info/PKG-INFO writing top-level names to pip-egg-info/GDAL.egg-info/top_level.txt writing dependency_links to pip-egg-info/GDAL.egg-info/dependency_links.txt writing manifest file 'pip-egg-info/GDAL.egg-info/SOURCES.txt' warning: manifest_maker: standard file '-c' not found Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pycharm-packaging347/gdal/setup.py", line 339, in &lt;module&gt; **extra ) File "/usr/lib/python2.7/distutils/core.py", line 151, in setup dist.run_commands() File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands self.run_command(cmd) File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command cmd_obj.run() File "build/bdist.linux-x86_64/egg/setuptools/command/egg_info.py", line 180, in run File "build/bdist.linux-x86_64/egg/setuptools/command/egg_info.py", line 207, in find_sources File "build/bdist.linux-x86_64/egg/setuptools/command/egg_info.py", line 291, in run File "build/bdist.linux-x86_64/egg/setuptools/command/egg_info.py", line 320, in add_defaults File "build/bdist.linux-x86_64/egg/setuptools/command/sdist.py", line 130, in add_defaults File "/usr/lib/python2.7/distutils/cmd.py", line 31…
has answer: http://stackoverflow.com/a/48188778
type: Question
tagged with: gdal
answer count: 1
has comment: http://stackoverflow.com/comment/83321485
score: -7
has comment: http://stackoverflow.com/comment/83320240
linked to: http://stackoverflow.com/q/15004590
has title: How can I install GDAL in Ubuntu 16,04 with python 2.7.12 using pip?
downvote count: 7
tagged with: python
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/83334048
type: UnansweredQuestion
tagged with: pip
has comment: http://stackoverflow.com/comment/83319699

http://stackoverflow.com/comment/83217073
has text: Please, search other answers: https://stackoverflow.com/questions/31324005/django-1-8-sending-mail-using-gmail-smtp Be sure that in settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48023948
score: 1

http://stackoverflow.com/comment/83311299
has text: Marvelous, this has got me on the right track. Thanks. Function on line 6 should be tf.get_default_graph()
comment on: http://stackoverflow.com/a/48159232
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48076753
tagged with: dask
tagged with: python
has comment: http://stackoverflow.com/comment/83136499
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has body: I have the following code trying to calculate the square root of a dask series my_dask_df['a_column'] = numpy.sqrt(my_dask_df['a_column']) What I get is the following exception: ValueError: Not all divisions are known, can't align partitions. Please use `set_index` to set the index. How can I calculate the square root of a dask series?
has answer: http://stackoverflow.com/a/48081287
accepted answer: http://stackoverflow.com/a/48081287
upvote count: 1
answer count: 1
has title: Square root on dask series
favorite count: 0

http://stackoverflow.com/comment/83030456
type: Comment
comment on: http://stackoverflow.com/q/48030071
type: QuestionComment
has text: yeap. it's a 'Kernel error'. at the jupyter it shows 'kernel dead'
score: 0

http://stackoverflow.com/comment/83150268
comment on: http://stackoverflow.com/q/48087010
type: QuestionComment
score: 0
has text: thanks, I will use that
type: Comment

http://stackoverflow.com/comment/83226623
has text: @EduardFlorinescu it's so that when I select a parent element of the link and do a click.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48124409

http://stackoverflow.com/comment/83222020
type: QuestionComment
score: 2
has text: you can find the documentation under [random](https://docs.python.org/3.4/library/random.html) , [round](https://docs.python.org/3.4/library/stdtypes.html)
comment on: http://stackoverflow.com/q/48122608
type: Comment

http://stackoverflow.com/q/48048727
has body: I have the following lines of code: param0 = { 'max_depth': 3, 'eta': 0.075, 'objective': 'binary:logistic', 'min_child_weight': 5, 'silent': 1, 'eval_matric': "auc", 'subsample': 0.6, 'gamma': 0.5, } Which defines a pythons dictionary (for a ml model, if it interests anyone). I would like to know what is the most elegant way (and simple) to create this param0 dictionary parameter from an outsource file. (i.e. from an xml file, json file or just a simple text file that i can configure outside the program). I'd need to know how the outsource file will look like (structure). I need to know the code reading the outsource file.
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 2
has title: Configurate python dictionary from outsource file
downvote count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/48048768
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48048768

http://stackoverflow.com/a/48111280
accepted answer of: http://stackoverflow.com/q/48108723
has comment: http://stackoverflow.com/comment/83200756
answers question: http://stackoverflow.com/q/48108723
has comment: http://stackoverflow.com/comment/83201561
upvote count: 2
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: Use the perplexity parameter of the TSNE. The default value of the perplexity is 30, it seems that's too much for your case, even though the documentation states that TSNE is quite insensitive to this parameter. The perplexity is related to the number of nearest neighbors that is used in other manifold learning algorithms. Larger datasets usually require a larger perplexity. Consider selecting a value between 5 and 50. The choice is not extremely critical since t-SNE is quite insensitive to this parameter. X = TSNE(n_components=2, perplexity=2.0).fit_transform( data )
score: 2

http://stackoverflow.com/comment/83374862
comment on: http://stackoverflow.com/q/48166292
type: Comment
type: QuestionComment
has text: func.coalesce() works very well, it is from SQL "SELECT COALESCE()". Learn a lot from you,Thanks. And could you add an answer so I can choose yours as best.
score: 0

http://stackoverflow.com/comment/83123581
type: QuestionComment
type: Comment
has text: Yes. That's the right way to do it.
score: 0
comment on: http://stackoverflow.com/q/48074091

time-series
tags question: http://stackoverflow.com/q/48114587
tags question: http://stackoverflow.com/q/48080042
tags question: http://stackoverflow.com/q/48144727
type: Tag
tags question: http://stackoverflow.com/q/48034625
tags question: http://stackoverflow.com/q/48042951
tags question: http://stackoverflow.com/q/48100919
tags question: http://stackoverflow.com/q/48054298
tags question: http://stackoverflow.com/q/48155564
tags question: http://stackoverflow.com/q/48172881
tags question: http://stackoverflow.com/q/48023982
tags question: http://stackoverflow.com/q/48044939
tags question: http://stackoverflow.com/q/48055536
tag name: time-series
tags question: http://stackoverflow.com/q/48040529
tags question: http://stackoverflow.com/q/48161024
tags question: http://stackoverflow.com/q/48139274

mongoose
tags question: http://stackoverflow.com/q/48158277
type: Tag
tag name: mongoose

http://stackoverflow.com/comment/83077152
score: 0
type: Comment
has text: Wow, this really works! I had come close with my own custom reply (not shown here), but I see you're using a number of trick I'd never had dreamt of (such as the delay). I notice that when the main code is placed within a method, nam must be made a member of the object or it will go out of scope and disappear with the c-lib still relying on it being present.
comment on: http://stackoverflow.com/a/48052082
type: AnswerComment

http://stackoverflow.com/comment/83225799
type: QuestionComment
has text: 1) So you managed to find `itertools-combinations` to get the combinations 5 out of 36, but you have difficulties to find all 4 out of 36 combinations? Really? 2) Why not use `range(1, 37)` as your num_list?
score: 0
comment on: http://stackoverflow.com/q/48124328
type: Comment

http://stackoverflow.com/q/48105256
has answer: http://stackoverflow.com/a/48105402
type: Question
has title: 2D array indexing error in Python
possible better answer: http://stackoverflow.com/a/48105312
has answer: http://stackoverflow.com/a/48105312
tagged with: arrays
has body: I'm playing with 2D arrays to make a random sequence generator. I'm trying to generate 10 lists of 6 integers each, without replacement, inside a 2D array. The integers allowed are between 0 and 100. However, I keep getting list index out of range errors, and can't work out why. Here's my code: import random numbers = [i for i in range(100)] picked = [] unpicked = [] lines = [[0 for x in range(6)] for j in range(10)] for i in range(10): for j in range(6): unpicked = [x for x in numbers+picked if x not in picked] lines[i][j] = unpicked[random.randint(0,99)] picked.append(lines[i][j])
score: 0
accepted answer: http://stackoverflow.com/a/48105402
answer count: 3
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83186363
tagged with: python
has answer: http://stackoverflow.com/a/48105679
type: AnsweredQuestion

http://stackoverflow.com/comment/83216363
comment on: http://stackoverflow.com/q/48119907
type: Comment
has text: `df['range_id'].rank(method='dense')` .
type: QuestionComment
score: 0

http://stackoverflow.com/q/48098692
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83172447
score: -4
has body: This is a function from my program: def display_ap(): global var_set global var_requestedby global var_content global var_due global var_ap_set if var_ap_set == True: print("[***]\n") print("Set: "+ str(var_set)+"\n") print("Requested by: "+ str(var_requestedby)+"\n") print("Content: "+ str(var_content)+"\n") print("Due: "+ str(var_due)+"\n") print("have values have been set correctly? - "+ str(var_ap_set)+"\n") print("values have been set correctly; list ready to generate") I need var_set, var_requestedby, var_content and var_due to be exported to a .txt file in that order, one on top of the other. how would I go about writing the export function part of the program.
type: Question
has comment: http://stackoverflow.com/comment/83172367
has comment: http://stackoverflow.com/comment/83172536
has title: How to export variables to a .txt file from python
has comment: http://stackoverflow.com/comment/83172423
answer count: 2
downvote count: 4
has answer: http://stackoverflow.com/a/48101286
has comment: http://stackoverflow.com/comment/83173256
has comment: http://stackoverflow.com/comment/83172715
upvote count: 0
has comment: http://stackoverflow.com/comment/83172509
has answer: http://stackoverflow.com/a/63209203

http://stackoverflow.com/a/48069851
has body: If you want to know whether PHP has the compile builtin function to compile the PHP code, there is no. PHP is a interpreted language, PHP code need interpreter to run it, and the interpreter has the executing environment for it. But if you want to realize your requirement, here is some way to achieve it: PHC phc is an open source compiler for PHP with support for plugins. In addition, it can be used to pretty-print or obfuscate PHP code, as a framework for developing applications that process PHP scripts, or to convert PHP into XML and back, enabling processing of PHP scripts using XML tools. bcompiler To encode entire script in a proprietary PHP application To encode some classes and/or functions in a proprietary PHP application To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe. To do the feasibility study for a PHP to C converter 3.Project Zero It supports the PHP compile.
score: 0
answers question: http://stackoverflow.com/q/48069491
type: Answer

http://stackoverflow.com/q/48090227
has answer: http://stackoverflow.com/a/48106072
upvote count: 2
has body: How can I create a column in a pandas dataframe with is the gradient of another column? I want the gradient to be run over a rolling window, so only 4 data points are assessed at one time. I am assuming it is something like: df['Gradient'] = np.gradient(df['Yvalues'].rolling(center=False,window=4)) However this gives error: raise ValueError('Length of values does not match length of ' 'index') ValueError: Length of values does not match length of index Any ideas? Thank you!!
has title: Rolling Gradient for Pandas Dataframe column
answer count: 2
tagged with: pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/83154814
type: UnansweredQuestion
tagged with: rolling-computation
tagged with: python
has answer: http://stackoverflow.com/a/48090491
score: 2
downvote count: 0
tagged with: gradient
has comment: http://stackoverflow.com/comment/83154889
type: Question
linked to: http://stackoverflow.com/q/231767

http://stackoverflow.com/comment/83239885
has text: OK, I think it is data problem. Are data confidental? If not, can you sent me your csv to my email in my profile?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48125512
type: AnswerComment

http://stackoverflow.com/q/48169129
has answer: http://stackoverflow.com/a/69989463
has answer: http://stackoverflow.com/a/49435154
tagged with: amazon-s3
accepted answer: http://stackoverflow.com/a/48178208
linked to: http://stackoverflow.com/q/39329580
tagged with: google-cloud-storage
answer count: 4
tagged with: google-cloud-platform
type: AnsweredQuestion
tagged with: airflow
downvote count: 0
has title: Copy from Google Cloud Storage Bucket to S3 Bucket
favorite count: 0
possible better answer: http://stackoverflow.com/a/58497354
type: Question
score: 3
has answer: http://stackoverflow.com/a/58497354
has answer: http://stackoverflow.com/a/48178208
tagged with: python
upvote count: 3
has body: I have set up an airflow workflow that ingests some files from s3 to Google Cloud storage and then runs a workflow of sql queries to create new tables on Big Query. At the end of the workflow I need to push the output of the one final Big Query table to Google Cloud Storage and from there to S3. I have cracked the the transfer of the Big Query table to Google Cloud Storage with no issues using the BigQueryToCloudStorageOperator python operator. However it seems the transfer from Google Cloud Storage to S3 is a less trodden route and I have been unable to find a solution which I can automate in my Airflow workflow. I am aware of rsync which comes as part of the gsutil and have gotten this working (see post Exporting data from Google Cloud Storage to Amazon S3) but I am unable to add this into my workflow. I have a dockerised airflow container running on a compute engine instance. Would really appreciate help solving this problem. Many thanks!

http://stackoverflow.com/comment/83043953
type: Comment
type: QuestionComment
has text: File "/home/ubuntu/workspace/project/application.py", line 70, in URL keywords = item["keywords"]["text"] TypeError: string indices must be integers
score: 0
comment on: http://stackoverflow.com/q/48036929

http://stackoverflow.com/a/48023853
upvote count: 0
score: -1
answers question: http://stackoverflow.com/q/48023680
type: Answer
downvote count: 1
has body: Use groups in your regular expression. Please read python regex documentation

http://stackoverflow.com/comment/87219509
has text: can you also explain what is the difference between initializable and reinitializable iterators?
comment on: http://stackoverflow.com/a/48601819
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83240327
comment on: http://stackoverflow.com/a/48131324
score: 0
type: AnswerComment
type: Comment
has text: You can specify another one earlier or later (or not at all), just the order they were specified will identify what user will be there in the end and what capabilities, properties and data from social networks he will have. It can be empty, or may have the methods specified in the docs (the link I provided). What matters is if a custom method is specified, it has to be placed properly (in the beginning if the check precedes all other checks, in the end if it has to happen in the end).

http://stackoverflow.com/a/48050072
upvote count: 6
has comment: http://stackoverflow.com/comment/102442966
has comment: http://stackoverflow.com/comment/102440657
has body: WordNet indexes concepts (aka Synsets) not words. Use lemma_names() to access root words (aka Lemma) in WordNet. &gt;&gt;&gt; from nltk.corpus import wordnet as wn &gt;&gt;&gt; for ss in wn.synsets('phone'): # Each synset represents a diff concept. ... print(ss.lemma_names()) ... ['telephone', 'phone', 'telephone_set'] ['phone', 'speech_sound', 'sound'] ['earphone', 'earpiece', 'headphone', 'phone'] ['call', 'telephone', 'call_up', 'phone', 'ring'] Lemma being the root form or a word shouldn't have additional affixes so you'll not find plural or different form of the words as you have listed in the list of words you wanted. See also: https://simple.wikipedia.org/wiki/Lemma_(linguistics) https://en.wikipedia.org/wiki/WordNet All synonyms for word in python? Also, words are ambiguous and may need to be disambiguated by context or my Parts-of-Speech (POS) before you can get "similar" words, e.g you see that "phone" in the verb meaning is not exactly the same meaning as phone as in the "noun". &gt;&gt;&gt; for ss in wn.synsets('phone'): # Each synset represents a diff concept. ... print(ss.lemma_names(), '\t', ss.definition()) ... ['telephone', 'phone', 'telephone_set'] electronic equipment that converts sound into electrical signals that can be transmitted over distances and then converts received signals back into sounds ['phone', 'speech_sound', 'sound'] (phonetics) an individual sound unit of speech without concern as to whether or not it is a phoneme of some language ['earphone', 'earpiece', 'headphone', 'phone'] electro-acoustic transducer for converting electric signals into sounds; it is held over or inserted into the ear ['call', 'telephone', 'call_up', 'phone', 'ring'] get or try to get into communication (with someone) by telephone
has comment: http://stackoverflow.com/comment/102472226
answers question: http://stackoverflow.com/q/48049619
downvote count: 0
score: 6
type: Answer

http://stackoverflow.com/q/48127152
has title: What is the error in this function?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83239475
score: -4
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83230936
has body: I have to create a function that returns the sum of all the population belonging to this excel file, but I always obtain 0. What's wrong? Here's the file [1]: https://i.sstatic.net/eUVoB.png This is the code: def howmanyPeople(filename): """ howmanyPeople(String) -&gt; int Receives the filename as an input and returns a number with the total population (sum of all countries) """ openFile = open(filename, 'r') result = 0 openFile.readline() #Skips the first line (header) for line in openFile: populationArray = line.split(",") #Returns a list with the line divided where there is a comma if (len(populationArray) == 3): #Checks if the name is double result += int(populationArray[1]) else: result += int(populationArray[2]) return result openFile.close()
has comment: http://stackoverflow.com/comment/83230982
has comment: http://stackoverflow.com/comment/83230949
downvote count: 5
type: Question
has comment: http://stackoverflow.com/comment/83230899
answer count: 1
has comment: http://stackoverflow.com/comment/83230904
has comment: http://stackoverflow.com/comment/83230912
has comment: http://stackoverflow.com/comment/83230910
has comment: http://stackoverflow.com/comment/83233624
has answer: http://stackoverflow.com/a/48128637
favorite count: 0
has comment: http://stackoverflow.com/comment/83231019

http://stackoverflow.com/q/48166183
has title: python3 dictionary get.key - TypeError: 'int' object is not subscriptable
type: Question
has body: I have a problem which my novice knowledge cannot solve. I'm trying to copy some python-2.x code (which is working) to python-3.x. Now it gives me an error. Here's a snippet of the code: def littleUglyDataCollectionInTheSourceCode(): a = { 'Aabenraa': [842.86917819535, 25.58264089252], 'Aalborg': [706.92644963185, 27.22746146366], 'Aarhus': [696.60346488317, 25.67540525994], 'Albertslund': [632.49007681987, 27.70499807418], 'Allerød': [674.10474259426, 27.91964123274], 'Assens': [697.02257492453, 25.83386400960], 'Ballerup': [647.05121493736, 27.72466920284], 'Billund': [906.63431520239, 26.23136823557], 'Bornholm': [696.05765684503, 28.98396327957], 'Brøndby': [644.89390717471, 28.18974127413], } return a and: def calcComponent(data): # Todo: implement inteface to set these values by # the corresponding 'Kommune' T = float(data.period) k = 1.1 rH = 1.0 # import with s/\([^\s-].*?\)\t\([0-9.]*\)$/'\1':'\2',/ myDict = littleUglyDataCollectionInTheSourceCode(); #if data.kommune in myDict: # https://docs.djangoproject.com/en/1.10/ref/unicode/ key = data.kommune.encode("utf-8") rd = myDict.get(key.strip(), 0) laP = float(rd[0]) # average precipitation midV = float(rd[1]) # Middelværdi Klimagrid print(("lap " + str(laP))) print(("mid V" + str(midV))) It gives the error: line 14, in calcComponent laP = float(rd[0]) # average precipitation TypeError: 'int' object is not subscriptable I've tried different approaches and read dozens of aticles with no luck. Being a novice it is like tumbling in the dark.
has answer: http://stackoverflow.com/a/48211385
possible better answer: http://stackoverflow.com/a/48166492
tagged with: python-2.7
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/83311672
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48166487
accepted answer: http://stackoverflow.com/a/48166487
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48166492
type: AnsweredQuestion

http://stackoverflow.com/comment/83106203
type: Comment
has text: Thanks for your answer! The issue is, I want to be as DRY as possible so I'm again trying to utilize the global variable I've set in request in my custom context processor. However, when I do `context['mysite_name'] = RequestContext(self.request).get('mysite_name')`, it returns None. `mysite_name` is used successfully in templates so I'm kind of at odds on why this isn't working.
type: AnswerComment
comment on: http://stackoverflow.com/a/48063839
score: 0

http://stackoverflow.com/q/48103647
answer count: 0
upvote count: 2
type: UnansweredQuestion
has title: Python urllib submit form
score: 2
tagged with: forms
has comment: http://stackoverflow.com/comment/83182871
tagged with: urllib
type: Question
downvote count: 0
favorite count: 0
tagged with: python
has body: What is the best way to click the 'Confirm Order' button on this form? Is it possible to do a ".click()" with urllib? CONFIRM ORDER * UPDATE * Getting "HTTP Error 412: Precondition Failed" with the following: ...Something I am doing wrong? ...Do ALL values of the form need to be submitted? url = "https://account.microsoft.com/rewards/redeem/checkout?productId=000800000042" request = urllib2.Request(url = url, headers = self.httpHeaders) request.add_header("Referer", bingCommon.BING_URL) with self.opener.open(request) as response: referer = response.geturl() page = helpers.getResponseBody(response) emailAddress = re.search('input id=\"email-input\" name=\"emailPreference\" type=\"hidden\" value=\"(.+)\"',page).group(1) token = re.search('input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"(.+)\" /',page).group(1) challenge = re.search('input name="challenge.RequestId" type="hidden" value="(.+)\"',page).group(1) print emailAddress, token, challenge postFields = urllib.urlencode({ "__RequestVerificationToken" : token, "emailPreference" : emailAddress, "email" : "", "shouldUpdateProfile" : "true", "isModernRewardsUser" : "true", "firstName" : "", "lastName" : "", "challenge.RequestId" : challenge }) request = urllib2.Request(url, postFields, self.httpHeaders) #request.add_header("Referer", bingCommon.BING_URL) with self.opener.open(request) as response: referer = response.geturl() page = helpers.getResponseBody(response)

http://stackoverflow.com/comment/83146134
comment on: http://stackoverflow.com/a/48084892
score: 0
type: AnswerComment
has text: @Nae what was your input that had an incorrect output? It's not doing that for me, although I did change it slightly.
type: Comment

http://stackoverflow.com/comment/83559378
type: QuestionComment
has text: No, sir, I have not.
comment on: http://stackoverflow.com/q/48104577
score: 0
type: Comment

http://stackoverflow.com/comment/83034874
score: 1
type: QuestionComment
has text: A simple `df1.merge(df2, on=['Date', 'upc'])` would work, would it not?
type: Comment
comment on: http://stackoverflow.com/q/48031445

http://stackoverflow.com/q/48120881
favorite count: 0
tagged with: python
tagged with: pycairo
has comment: http://stackoverflow.com/comment/83219193
tagged with: igraph
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83218467
downvote count: 0
has body: I am trying to import igraph but it keeps throwing this error at me: &gt;&gt;&gt; import igraph Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/site-packages/igraph/__init__.py", line 36, in &lt;module&gt; from igraph.clustering import * File "/usr/local/lib/python3.6/site-packages/igraph/clustering.py", line 36, in &lt;module&gt; from igraph.drawing.colors import ClusterColoringPalette File "/usr/local/lib/python3.6/site- packages/igraph/drawing/__init__.py", line 27, in &lt;module&gt; from igraph.drawing.graph import DefaultGraphDrawer File "/usr/local/lib/python3.6/site- packages/igraph/drawing/graph.py", line 27, in &lt;module&gt; from igraph.drawing.edge import ArrowEdgeDrawer File "/usr/local/lib/python3.6/site-packages/igraph/drawing/edge.py", line 17, in &lt;module&gt; cairo = find_cairo() File "/usr/local/lib/python3.6/site- packages/igraph/drawing/utils.py", line 413, in find_cairo module = __import__(module_name) File "/usr/local/lib/python3.6/site-packages/cairocffi/__init__.py", line 41, in &lt;module&gt; cairo = dlopen(ffi, 'cairo', 'cairo-2') File "/usr/local/lib/python3.6/site-packages/cairocffi/__init__.py", line 38, in dlopen raise OSError("dlopen() failed to load a library: %s" % ' / '.join(names)) OSError: dlopen() failed to load a library: cairo / cairo-2 I have tried to follow this guide to install cairo but it throws this error and doesn't solve the igraph import issue: error: mandatory image surface backend feature could not be enabled I have also tried to install pycairo but that resulted in no module founds: cairo, which brought me back to square one. I tried running sudo port install cairo as per https://cairographics.org/download/ instructions. But that results in Error: Port cairo not found My sys config: MacOS High Sierra 10.13.1 Python 3.6 python-igraph 0.7.1 I am clueless as to what can be the issue. Any help would be highly appreciated. Thank you :)
type: Question
has answer: http://stackoverflow.com/a/48190455
accepted answer: http://stackoverflow.com/a/48190455
tagged with: cairo
score: 1
has comment: http://stackoverflow.com/comment/83218436
upvote count: 1
answer count: 1
has title: OSError importing python-igraph

http://stackoverflow.com/comment/83075367
score: 0
type: AnswerComment
has text: In Ruby insertion order is maintained.
type: Comment
comment on: http://stackoverflow.com/a/48051599

http://stackoverflow.com/a/48079617
has body: Switching to iFrames catches a lot of people out, but if you have content that is loaded from a different domain (in this case the Captcha) then you need to switch to that with driver.switchTo().frame(&lt;integer of frame or id&gt;); Then you will be be able to interact the selector of your choice.
type: Answer
answers question: http://stackoverflow.com/q/48074233
score: 0

http://stackoverflow.com/comment/83214532
score: 0
type: Comment
has text: How exactly isn't it working?
type: QuestionComment
comment on: http://stackoverflow.com/q/48091060

http://stackoverflow.com/a/65118276
upvote count: 40
has comment: http://stackoverflow.com/comment/131983251
has comment: http://stackoverflow.com/comment/131082082
has comment: http://stackoverflow.com/comment/127534974
downvote count: 0
score: 40
answers question: http://stackoverflow.com/q/48121916
type: Answer
has body: One-line numpy solution for downsampling (by 2): smaller_img = bigger_img[::2, ::2] And upsampling (by 2): bigger_img = smaller_img.repeat(2, axis=0).repeat(2, axis=1) (this asssumes HxWxC shaped image. note this method only allows whole integer resizing (e.g., 2x but not 1.5x))
has comment: http://stackoverflow.com/comment/123754122

http://stackoverflow.com/q/48133372
tagged with: user-interface
downvote count: 0
favorite count: 0
has body: I'm trying to teach myself to code in python after programming in C# for a few years now. I find the transition quite hard so far, but hope that with some persistence I will eventually understand python My problem: after experimenting with programs like wxglade and wxformbuilder I was charmed by the way those programs provide you with a nice seperate GUI file so that you can put all your functions in a seperate main file. However, I would like to apply the same principle to tkinter GUIs, but I can't figure it out, nor can I find documentation about it. Let's say I have two files: GUI.py: from tkinter import * class BotGUI: def __init__(self, master): # ***** Creation of the frame for all items to be on ***** xWidth=800 yWidth=500 margin=100 outer_frame=Frame(master, width=xWidth, height=yWidth, bg='lightgray') outer_frame.pack(ipadx=margin, ipady=margin) button1 = Button(outer_frame, text = "Print something", command = printcommand) button1.pack() #Virtual event handlers def printcommand(self, event): event.Skip() and then a file called Main.py: from tkinter import * import GUI class GUI_Functions(GUI.BotGUI): def __init__(self,parent): GUI.BotGUI.__init__(self, parent) def printcommand(self, event): print("The bind was successful!") if __name__ == '__main__': root = Tk() GUI_Frame = GUI.BotGUI(root) root.mainloop() The above code results in the error: NameError: global name 'printcommand' is not defined I just cannot figure out how to get this working for a tkinter GUI. Hope someone can help me out a bit! (GUI creation is so much easier in C# with visual studio :( )
has title: Having TKinter GUI in seperate .py file and binding functions to buttons in the GUI file
answer count: 4
has answer: http://stackoverflow.com/a/48141481
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83260869
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48133522
has answer: http://stackoverflow.com/a/60544848
score: 1
has answer: http://stackoverflow.com/a/48134729
has comment: http://stackoverflow.com/comment/83257095
type: Question

http://stackoverflow.com/a/48085352
answers question: http://stackoverflow.com/q/48074642
score: 5
downvote count: 0
type: Answer
has body: An easy way is to use the built-in levenstein function. For example, ( spark.createDataFrame([("apple",), ("aple",), ("orange",), ("pear",)], ["fruit"]) .withColumn("substring", func.lit("apple")) .withColumn("levenstein", func.levenshtein("fruit", "substring")) .filter("levenstein &lt;= 1") .toPandas() ) returns fruit substring levenstein 0 apple apple 0 1 aple apple 1 If you want to use a vanilla Python function, like something from an NLTK package, you'll have to define a UDF that takes a string and returns a boolean.
upvote count: 5

http://stackoverflow.com/a/48116550
answers question: http://stackoverflow.com/q/48115455
accepted answer of: http://stackoverflow.com/q/48115455
upvote count: 2
has comment: http://stackoverflow.com/comment/83219428
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
has body: Use pandas. It is waaaay easier : url = 'https://www.quandl.com/api/v3/datasets/EOD/V.csv?api_key=Fa1P1yZLGnGSsXktrvzL' df = pd.read_csv(url, parse_dates=True,index_col=0) df = df.rename(columns={'Close':'Stock Price'}) s = df['Stock Price'] s_to_plot = s.sort_index(ascending=True).tail(100) ax = s_to_plot.plot(title='End of Day Visa Stock Prices for US Exchange') ax.set_ylabel('Stock Price')

http://stackoverflow.com/q/48169791
score: 1
favorite count: 0
has title: How to change the value of a tensor which is not a tf.Variable in TensorFlow?
type: Question
has comment: http://stackoverflow.com/comment/83324944
answer count: 2
possible better answer: http://stackoverflow.com/a/48169888
tagged with: variable-assignment
tagged with: python
has answer: http://stackoverflow.com/a/48169914
has answer: http://stackoverflow.com/a/48169888
has comment: http://stackoverflow.com/comment/83325625
upvote count: 1
has body: I know that there is a tf.assign function in TensorFlow, but this function is mainly aimed at mutable tensor (tf.Variable). How to modify the value of the tensor? For example, the following code, import numpy as np import tensorflow as tf X = tf.placeholder(tf.float32, shape=[None, 32, 32, 3]) conv1 = tf.layers.conv2d(X, filters=64, kernel_size=(3, 3), padding='same',name='conv1') relu1 = tf.nn.relu(conv1) conv2 = tf.layers.conv2d(relu1, filters=64, kernel_size=(3, 3), padding='same',name='conv2') relu2 = tf.nn.relu(conv2) init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) tensor = sess.graph.get_tensor_by_name(u'conv2/Conv2D:0') feature_map = tf.reduce_mean(tensor[:,:,:,24]) image = np.random.uniform(size=(1,32,32,3)) sess.run([feature_map], feed_dict={X: image}) How to modify the value of feature_map and do not affect its derivation? More specifically, when I change the value of feature_map, it does not affect its derivation process. For example, y = a^2, y'= 2a, I just need to change a = 1 to a = 2. Other_op = tf.gradients(feature_map, X) Different feature_map would achieve the different values, but it does not destroy the graph structures of operation.
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/48169914
tagged with: neural-network
has comment: http://stackoverflow.com/comment/83325278
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/83325999
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/48158783
has comment: http://stackoverflow.com/comment/83297155
has body: Edit: Misread, thought that you have multiple lists of numbers and generally asking how to find those numbers that are present in all of them. Will keep the original answer below, though, as some people still found it helpful to some degree. Yes, it's called set intersection and can be used on the set data type. Demo: &gt;&gt;&gt; s = set((1, 2, 3)) &gt;&gt;&gt; s2 = set((2, 3, 4)) &gt;&gt;&gt; s3 = set((3, 4, 5)) &gt;&gt;&gt; s &amp; s2 {2, 3} &gt;&gt;&gt; s &amp; s2 &amp; s3 {3} If your current data is stored in lists, converting it to sets is just a matter of passing the lists to the set() constructor: &gt;&gt;&gt; numbers = [2, 7, 9, 10] &gt;&gt;&gt; set(numbers) {2, 7, 9, 10} Mind, though, that if a list contains duplicates, that information will get lost, and each duplicated element will only be present once in the resulting intersection.
has comment: http://stackoverflow.com/comment/83297203
type: Answer
score: 2
upvote count: 3
downvote count: 1
answers question: http://stackoverflow.com/q/48158745

http://stackoverflow.com/a/48171902
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48171159
has body: Syntax in the browser is nearly identical, but of course it's JavaScript, not Python. You could use the request-promise NPM module: const request = require('request-promise') let url = "https://www.woolworths.com.au/apis/ui/Search/products" let payload = { 'Filters': '[]', 'IsSpecial': 'false', 'Location': '/shop/search/products?searchTerm=banana', 'PageNumber': '1', 'PageSize': '24', 'SearchTerm': 'banana', 'SortType': 'TraderRelevance' } request .post({ url, json: payload, headers: {'Content-Type': 'application/json'} }) .then(res =&gt; console.log(res)) .catch(err =&gt; console.log(err)) You will need to print out or otherwise parse your data inside your then method, since JavaScript executes this asynchronously, not synchronously like Python does. The question of how to include a JavaScript module in the browser is a separate one, but you can find plenty of examples on this site and via Google. There is also the fetch API which has good browser support at this point, and doesn't require you to bring in an outside module. The syntax is very similar, you can read more on MDN here.
has comment: http://stackoverflow.com/comment/83341415

http://stackoverflow.com/a/49435154
has comment: http://stackoverflow.com/comment/85961307
score: -1
has comment: http://stackoverflow.com/comment/85899530
has body: Google recommends using it's transfer service for transfers between cloud platforms. You can programatically setup a transfer using their python API. This way the data is transferred directly between S3 and google cloud storage. The disadvantage of using gsutil and rsync is that the data will have to go through the machine/instance which executes the rsync command. This can be a bottle neck. Google Cloud Storage Transfer Service Doc
type: Answer
downvote count: 2
upvote count: 1
answers question: http://stackoverflow.com/q/48169129

http://stackoverflow.com/comment/83306297
type: QuestionComment
has text: Is that the complete error traceback? I would expect a bit more.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48162292

http://stackoverflow.com/comment/83069365
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48048773
has text: anyway what is key_function(x): for?, and what's groupby(sorted(enumerate(totalist), key=key_function), key_function): use for?

http://stackoverflow.com/comment/83071869
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48049961
type: Comment
has text: @JoeIddon Thanks. Yeah I know. Old habits die hard, I suppose.

http://stackoverflow.com/a/48074222
has body: Use cumsum with multiple by mul: df['C'] = df['A'].cumsum().mul(df['B']) df['D'] = df'A', 'B'.prod(1).cumsum() Or: df = df.assign(C=df['A'].cumsum().mul(df['B']), D=df['A'].mul(df['B']).cumsum()) print (df) A B C D 0 1 2 2 2 1 3 4 16 14 2 5 6 54 44 3 7 8 128 100 4 9 10 250 190 EDIT: For reverse values is simpliest use iloc[::-1]: df = df.assign(C=df['A'].iloc[::-1].cumsum().mul(df['B']), D=df'A', 'B'.iloc[::-1].prod(1).cumsum()) print (df) A B C D 0 1 2 50 190 1 3 4 96 188 2 5 6 126 176 3 7 8 128 146 4 9 10 90 90 EDIT1: df = pd.DataFrame({'A':[1,3,5,7,9], 'B':[2,4,6,8,10]}) df['C']=df['A'].iloc[::-1].cumsum().mul(df['B']) df['D']=df'A', 'B'.iloc[::-1].prod(1).cumsum() print (df) A B C D 0 1 2 50 190 1 3 4 96 188 2 5 6 126 176 3 7 8 128 146 4 9 10 90 90 #create index by column A x = df.set_index('A') print (x) B C D A 1 2 50 190 3 4 96 188 5 6 126 176 7 8 128 146 9 10 90 90 #get index of minimal value by D column print (x['D'].idxmin()) 9
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83126199
answers question: http://stackoverflow.com/q/48074166
has comment: http://stackoverflow.com/comment/83172801
type: Answer
accepted answer of: http://stackoverflow.com/q/48074166
has comment: http://stackoverflow.com/comment/83166087
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83140922
has comment: http://stackoverflow.com/comment/83138742

http://stackoverflow.com/comment/83229203
type: Comment
has text: `list` has no attribute `split` :)
comment on: http://stackoverflow.com/a/48126248
type: AnswerComment
score: 0

http://stackoverflow.com/q/48030309
favorite count: 0
has answer: http://stackoverflow.com/a/67728665
has answer: http://stackoverflow.com/a/48030455
tagged with: python
has body: I'm building a networkx graph using data retrieved from a Postgres DB using psycopg2. I can create the graph just fine, but I'm wondering if there is a more efficient and/or Pythonic way to do it. Current code: DG = nx.DiGraph() cur.execute(edgeQuery) for row in cur: self.DG.add_edge( row[0], # fnode row[1], # tnode weight=row[3], # cost name=row[4] ) The networkx documentation indicates multiple edges can be created at once by feeding in an ebunch. I could create an ebunch by iterating the cursor results, but that wouldn't be any more efficient than my current solution. I feel like there's got to be a more efficient way to translate my cursor results into networkx edges. Maybe something like zip? I'd also like to identify a pythonic way to do it for ease of future maintenance (and to satisfy my own curiosity).
type: UnansweredQuestion
upvote count: 1
tagged with: psycopg2
tagged with: networkx
score: 1
has title: How can I efficiently create a networkx graph from psycopg2 query results?
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/a/48094065
answers question: http://stackoverflow.com/q/48093968
upvote count: 1
downvote count: 1
has body: You should use something like: if re.match(r'^5545', hand): print(hand) The ^ means the beginning of the line.
score: 0
type: Answer

awk
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/48098636

http://stackoverflow.com/a/48071277
type: Answer
answers question: http://stackoverflow.com/q/48071193
upvote count: 1
has body: Django add method using only to add instance to many-to-one or many-to-many related objects set. In you case Leads.add(lead) is unnecessary and you can remove it without any problems this line will add new Lead object itself: lead = Leads.objects.create( listing = listing_address, company = listing.l_company, )
score: 1
has comment: http://stackoverflow.com/comment/83116364
accepted answer of: http://stackoverflow.com/q/48071193
has comment: http://stackoverflow.com/comment/83116302
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83116520

http://stackoverflow.com/q/48104143
has comment: http://stackoverflow.com/comment/83193106
has comment: http://stackoverflow.com/comment/83184104
has comment: http://stackoverflow.com/comment/83185016
linked to: http://stackoverflow.com/q/28075743
has answer: http://stackoverflow.com/a/48110087
has comment: http://stackoverflow.com/comment/83185194
score: 0
linked to: http://stackoverflow.com/q/42286219
tagged with: matrix
answer count: 1
tagged with: inverse
linked to: http://stackoverflow.com/q/40563668
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83221638
has comment: http://stackoverflow.com/comment/83220351
tagged with: python
has title: Inverse of a 4x3 matrix in python
has comment: http://stackoverflow.com/comment/83184346
has comment: http://stackoverflow.com/comment/83185692
has comment: http://stackoverflow.com/comment/83184215
upvote count: 1
has comment: http://stackoverflow.com/comment/83183951
has body: I'm reimplementing a closed source 3d library called noesis. It exposes a python file with all of the basic classes. All of the implementation details are actually hidden. The implementation is compiled so I can't preview it. I want to implement one of the fuctions from that library called mat43Inverse. I know normally it's not possible to inverse a 4x3 matrix, but this function exists. Sample usage from a noesis plugin: #4x3 matrix class NoeMat43: # ... def inverse(self): #returns mat43 return noesis.mat43Inverse(self) source of exposed classes file: https://github.com/majimboo/mviewer/blob/master/noesis/plugins/python/inc_noesis.py#L478 noesis module is a compiled cpython module. (https://github.com/majimboo/mviewer/blob/master/noesis/plugins/NoesisPython.dll) boneMtx = NoeMat43(( NoeVec3((m01, m02, m03)), NoeVec3((m11, m12, m13)), NoeVec3((m21, m22, m23)), NoeVec3((m04, m14, m24)) )).inverse() I prepared a set of correct results by calling the native function and printing the result. input = NoeMat43(( NoeVec3((2.5, 3.6, 4.7)), NoeVec3((2.9, 3.1, 4.3)), NoeVec3((6.5, 7.6, 8.7)), NoeVec3((1.1, 9.4, 3.2)) )) result = input.inverse() expected = NoeMat43(( NoeVec3((0.04392901062965393, 0.05095765367150307, 0.1142154261469841)), NoeVec3((0.044815145432949066, 0.038590818643569946, 0.09460975229740143)), NoeVec3((0.04042314738035202, 0.036982882767915726, 0.07482582330703735)), NoeVec3((-0.8928132057189941, -0.714801549911499, -0.6315471529960632)) )) noeassert('mat43Inverse', result, expected) Correct results 1. input: ( (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0) ) inverse result: ( (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 0.0) ) 2. input: ( (2.5, 3.6, 4.7), (2.9, 3.1, 4.3), (6.5, 7.6, 8.7), (1.1, 9.4, 3.2) ) invserse result: ( (0.04392901062965393, 0.05095765367150307, 0.1142154261469841), (0.044815145432949066, 0.038590818643569946, 0.09460975229740143), (0.04042314738035202, 0.036982882767915726, 0.07482582330703735), (-0.8928132057189941, -0.7…
downvote count: 1
has comment: http://stackoverflow.com/comment/83184342
type: Question
has comment: http://stackoverflow.com/comment/83185150
tagged with: math

http://stackoverflow.com/comment/83267306
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48144610
type: Comment
has text: The python module you are running and the pip modules are probably not tied to each other. Make sure, pip installed the right packages for the python executable you are currently using.

http://stackoverflow.com/comment/83129305
type: AnswerComment
comment on: http://stackoverflow.com/a/48077080
type: Comment
has text: i tired the above code, but i'm unable to get the index of last values if not followed by 0
score: 0

http://stackoverflow.com/comment/90807796
comment on: http://stackoverflow.com/a/51749538
score: 0
type: AnswerComment
has text: i've updated all the packages then i got this error. The only solution that works for me is this answer. Ty.
type: Comment

http://stackoverflow.com/comment/83059816
has text: @Razär: no. Al lists are iterable. But the *elements* of the list should be iterable in case you want iterable unpacking. In case you iterate over a list in Python, you *only* iterate over the *elements*. Not the index. In case you want the index as well, you can use `enumerate(..)`.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48044422
score: 3

http://stackoverflow.com/a/70943369
score: 0
has body: Maybe orthogonal to the question; but if you use softmax together with cross entropy loss, it is then trivial to add sample weights, see: http://d2p0dj726sqh0a.cloudfront.net/api/gluon/_autogen/mxnet.gluon.loss.SoftmaxCrossEntropyLoss.html
type: Answer
answers question: http://stackoverflow.com/q/48044595

http://stackoverflow.com/comment/83130492
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48078218
has text: Specifically, what's in the file, what numbers are you inputting, and what do you expect the corresponding results to be?
score: 0

http://stackoverflow.com/comment/83035331
has text: Thanks, that fixed it. I have that piece of code in all my networking code, doing asyncio for the first time I just forgot about it.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48032506

http://stackoverflow.com/comment/97014739
comment on: http://stackoverflow.com/a/55130919
score: 3
type: AnswerComment
has text: Even though what you have written is related to the question. The question is: *"How to check if pytorch is using the GPU?"* and not *"What can I do if PyTorch doesn't detect my GPU?"* So I would say that this answer does not really belong to this question. But you may find another question about this specific issue where you can share your knowledge. If not you could even write a question and answer it yourself to help others with the same issue!
type: Comment

http://stackoverflow.com/q/48066126
has comment: http://stackoverflow.com/comment/83106145
tagged with: pycryptodome
tagged with: python
has title: Padding is incorrect. AES Python encryption
tagged with: aes
has answer: http://stackoverflow.com/a/48066203
accepted answer: http://stackoverflow.com/a/48066203
downvote count: 0
score: 6
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83111587
upvote count: 6
tagged with: padding
answer count: 1
favorite count: 0
has body: I'm trying to put together a simple encryption using python. This is the encrypt: from Crypto.Cipher import AES from Crypto.Util.Padding import pad from Crypto.Util.Padding import unpad BLOCK_SIZE = 32 def encrypt(message): obj = AES.new(b'This is a key123', AES.MODE_CBC, b'This is an IV456') return obj.encrypt(pad(message, BLOCK_SIZE)) Encryption seems to work as it returns this: b'V=\t7I\x99\xa5\x06*\xa1={\x95+\xc1h\xfeY\xc2\xb5\xcf3F:\x88\xa6g\x94d\x87\xd7U' However for decryption I use: def decrypt(ciphertext): obj2 = AES.new(b'This is a key123', AES.MODE_CFB, b'This is an IV456') return obj2.decrypt(unpad(ciphertext, BLOCK_SIZE)) But it shows: Padding is incorrect This is the entire file I'm trying to put together: import sys from Crypto.Cipher import AES import importlib try: importlib.import_module('psutil') except ImportError: import pip pip.main(['install', 'psutil']) finally: globals()['psutil'] = importlib.import_module('psutil') def collect_stats(): try: cpu = psutil.cpu_percent(interval=1) memory = psutil.virtual_memory().percent disk = psutil.disk_usage('/').percent str_to_send_back = "{} {} {}".format(cpu, memory, disk) str_to_send_back = str_to_send_back.encode() str_to_send_back = encrypt(str_to_send_back) except Exception as e: print('Oops this error happened in collect_stats() inside client.py: ' + str(e)) def encrypt(message): obj = AES.new(b'This is a key123', AES.MODE_CBC, b'This is an IV456') return obj.encrypt(message) def decrypt(ciphertext): obj2 = AES.new(b'This is a key123', AES.MODE_CFB, iv) return obj2.decrypt(ciphertext) if __name__ == '__main__': collect_stats()
tagged with: encryption

http://stackoverflow.com/q/48082851
score: 0
has body: In Python 3 I'm reading links with "fixed-width files". Example import requests pagina = requests.get('http://idg.receita.fazenda.gov.br/orientacao/tributaria/cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/consultas/download/F.K03200UF.D71214AC') only_text = pagina.text only_text '0107398403000180BOI GORDO AGROPECUARIA COMERCIO E REPRESENTACOES LTDA - EPP \n02073984030001802 49SELMA ELIANA MEDEIROS RIBEIRO \n02073984030001802 22MARCELO LUIZ SANCHES \n0103173169000131CONSELHO ESCOLAR BOM JESUS ... \n0129235225000109MD CONFECCOES EIRELI - ME \n02292352250001092 65MARCELO AMARO DA SILVA \n' I need to read each line of "only_text" separately to extract strings in certain positions on each line I've tried this, but the command takes one character at a time instead of each line for linha in only_text: print(linha) 0 1 0 7 3 9 8 4 0 3 0 0 0 1 8 0 B O I ... Please, how can I isolate and read each line separately?
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/83140273
tagged with: python-requests
type: Question
has title: How to read one line at a time in generated texts with request?
has comment: http://stackoverflow.com/comment/83140487

http://stackoverflow.com/comment/83313581
type: Comment
comment on: http://stackoverflow.com/a/48167268
type: AnswerComment
has text: You are wrong. m.transmission[(m.transmission["Site In"]=="Mid")|(m.transmission["Site Out"]=="Mid") ]`*** KeyError: 'Site In'`
score: 0

http://stackoverflow.com/comment/83215860
type: Comment
comment on: http://stackoverflow.com/q/48119634
has text: @juanpa.arrivillaga, I want to loop over obj_i = A(*args) and if args[0] is another object of type A, then I want obj_i to become a reference.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83140558
type: AnswerComment
comment on: http://stackoverflow.com/a/48081763
score: 0
has text: Thank you. I'll take your advice. Nevertheless upon trying I came across 2 issues. Consider query_str = " select * from my_table a where my_column like {v_like} ".format(v_like=my_var) 1. try with my_var = '%rie' or '''%rie''' (3 single quotes) or " '%rie' ", only in the last one will my quote be kept and not second. Is it normal ? 2. With 3rd option I get my query well as select * from my_table a where my_column like '%rie' . Yet read_sql failed with "not all arguments converted during string formatting".Apparently it thinks %rie is another argument. Escaping with '%%rie' also fail.Any idea
type: Comment

http://stackoverflow.com/a/48044751
answers question: http://stackoverflow.com/q/48038974
score: 2
downvote count: 0
has body: To actually install the BS library, you'll need to use Pip. That will get it working in Cloud9. When you use the function in Lambda, it will require a deployment package that also includes the BS library. The error you are getting probably relates to the library not existing in the Lambda environment. If Cloud9 doesn't make it easy to export a deployment package, you might have to upload code manually.
has comment: http://stackoverflow.com/comment/83110100
upvote count: 2
type: Answer

http://stackoverflow.com/a/48171740
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48167165
answers question: http://stackoverflow.com/q/48167165
has body: I am particularily interested in an aging with a half Gaussian function. So this seems to work: from scipy.stats import norm import math def half_gaussian_convolution(input): normal_weighting = norm.pdf(np.array(range(-len(input) + 1, 1)), scale=(len(input) - 1) / 1.6448536269514722) normal_weighting = normal_weighting / np.sum(normal_weighting) return np.sum(normal_weighting * input) ser.rolling(window=4, center=False).apply(func=half_gaussian_convolution)
type: Answer
has comment: http://stackoverflow.com/comment/83343719
has comment: http://stackoverflow.com/comment/83465857

http://stackoverflow.com/comment/83147774
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48086032
score: 0
has text: @user8834780 hi, thanks for trying to help! but may i understand why the query must be shared? since the query does run, that means the problem is not within the query, right?

http://stackoverflow.com/q/48144747
has title: keras numpy error with load_img function
has comment: http://stackoverflow.com/comment/83267756
tagged with: python
accepted answer: http://stackoverflow.com/a/48144902
type: AnsweredQuestion
score: 0
tagged with: tensorflow
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48144902
has body: I am getting an error from the from keras.preprocessing.image.load_img function. Its saying an numpy object has no attribute 'load_img'. I'm not quite sure why its connecting this function in a keras module to an numpy object. Pretty new at python so maybe I'm missing something. Below I have included a link to the picture of the error received. Your time and help is greatly appreciated. Screen Shot
tagged with: deep-learning
answer count: 1
tagged with: keras

http://stackoverflow.com/comment/83227952
comment on: http://stackoverflow.com/a/48124960
type: AnswerComment
has text: Going to guess additionally that the pair should be appended inside the `for` loop, but otherwise good catch with the local variable.
score: 0
type: Comment

http://stackoverflow.com/q/48140817
tagged with: python
has body: Can the user change a variable when the program is running and have it be that when the program is next used?
answer count: 0
score: 1
has title: Can variables be changed when the program is running and then saved?
type: Question
upvote count: 2
duplicate of: http://stackoverflow.com/q/5568904
downvote count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48099974
type: AnsweredQuestion
tagged with: python-3.x
has title: Error using number as argument to R function in RPy2
type: Question
has comment: http://stackoverflow.com/comment/83208490
has answer: http://stackoverflow.com/a/48130533
tagged with: rpy2
tagged with: numpy
has body: I am attempting to use the mutual information function from the R package tseriesChaos on a time series and find the first minimum in order to determine the optimum delay for a delay embedding of the time series. I have written the following function to accomplish this: def determine_lag(tseries, plot): numpser = numpy.asarray(tseries) n = numpser.size bins = 1 + math.log(n, 2) z = 500 emi = numpy.array(tseriesChaos.mutual(tseries, bins, z, plot)) x = emi[0] it = numpy.nditer(emi) while not it.finished: y = it[0] num = it.index if y &gt; x: lag = num break else: x = y it.iternext() else: showwarning(title='Error', message='No minimum found, delay set to 50') failed = True lag = 50 return lag, failed where tseries is the time series as extracted by soundfile.read elsewhere and plot is either TRUE or FALSE. When attempting to use the function, however, an error seems to occur in the translation of the arguments for the R function. The output is as follows: Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/Cellar/python3/3.6.4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1699, in __call__ return self.func(*args) File "/Users/BrandonPlay/Soundbed 0.3/master.py", line 177, in Start self.lag, failed = determine_lag(self.tseries, do_plot) File "/Users/BrandonPlay/Soundbed 0.3/master.py", line 49, in determine_lag emi = numpy.array(tseriesChaos.mutual(tseries, bins, z, plot)) File "/Users/BrandonPlay/Library/Python/3.6/lib/python/site-packages/rpy2/robjects/functions.py", line 178, in __call__ return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs) File "/Users/BrandonPlay/Library/Python/3.6/lib/python/site-packages/rpy2/robjects/functions.py", line 102, in __call__ new_args = [conversion.py2ri(a) for a in args] File "/Users/BrandonPlay/Library/Python/3.6/lib/python/site-packages/rpy2/robjects/functions.py", line 102, in &lt;listcomp&gt; new_args = [conversion.py2ri(a) for a in args] File…
has comment: http://stackoverflow.com/comment/83235569
answer count: 1
accepted answer: http://stackoverflow.com/a/48130533
tagged with: http://stackoverflow.com/tag/r
score: 0
tagged with: python

http://stackoverflow.com/q/48040118
has comment: http://stackoverflow.com/comment/83056349
score: 0
linked to: http://stackoverflow.com/q/18241029
has comment: http://stackoverflow.com/comment/83052357
has comment: http://stackoverflow.com/comment/83052250
answer count: 1
has answer: http://stackoverflow.com/a/48040575
accepted answer: http://stackoverflow.com/a/48040575
tagged with: lxml
has title: Python XPath keeps returning empty list
tagged with: python
tagged with: xpath
type: AnsweredQuestion
has body: XPath via lxml in Python has been making me run in circles. I can't get it to extract text from an HTML table despite having what I believe to be the correct XPath. I'm using Chrome to inspect and extract the XPath, then using it in my code. Here is the HTML table taken directly from the page: &lt;div id="vehicle-detail-model-specs-container"&gt; &lt;table id="vehicle-detail-model-specs" class="table table-striped vdp-feature-table"&gt; &lt;!-- Price --&gt; &lt;tr&gt; &lt;td&gt;&lt;strong&gt;Price:&lt;/strong&gt;&lt;/td&gt; &lt;td&gt; &lt;strong id="vehicle-detail-price" itemprop="price"&gt;$ 2,210.00&lt;/strong&gt; &lt;/td&gt; &lt;/tr&gt; &lt;!-- VIN --&gt; &lt;tr&gt;&lt;td&gt;&lt;strong&gt;VIN&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;&amp;nbsp;*0343&lt;/td&gt;&lt;/tr&gt; &lt;!-- MILEAGE --&gt; &lt;tr&gt;&lt;td&gt;&lt;strong&gt;Mileage&lt;/strong&gt;&lt;/td&gt;&lt;td&gt;0&amp;nbsp;mi&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; I'm trying to extract the Mileage. The XPath I'm using is: //*[@id="vehicle-detail-model-specs"]/tbody/tr[3]/td[2] And the Python code that I'm using is: page = requests.get(URL) tree = html.fromstring(page.content) mileage = tree.xpath('//*[@id="vehicle-detail-model-specs"]/tbody/tr[3]/td[2]') print mileage Note: I've tried adding /text() to the end and I still get nothing back, just an empty list []. What am I doing wrong and why am I not able to extract the table value from the above examples?
type: Question
has comment: http://stackoverflow.com/comment/83050721

http://stackoverflow.com/q/48052562
tagged with: pyaudio
score: 0
has title: installing pyalsaaudio on raspberry pi zero W (raspbian OS)
type: UnansweredQuestion
tagged with: python
has body: Hi everyone, I tried everything to install pyalsaaudio package on my Raspberry Pi Zero W can anyone please help me with a guide to install it on my device ? I see a lot of guides for Ubunto OS and i even tried them on my device but nothing worked for me. Thanks in advance.
has answer: http://stackoverflow.com/a/49837781
type: Question
tagged with: raspbian
has comment: http://stackoverflow.com/comment/83092676
tagged with: raspberry-pi
answer count: 1

http://stackoverflow.com/comment/83157527
type: Comment
has text: I only answer for the certain condition, not for the assumption. If it does not work, just put the condition and the non-work result.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48091535

http://stackoverflow.com/q/48047782
has comment: http://stackoverflow.com/comment/83067300
has title: pandas clever way of setting columns under conditions
has answer: http://stackoverflow.com/a/48050768
has comment: http://stackoverflow.com/comment/83067190
answer count: 2
has answer: http://stackoverflow.com/a/48047864
accepted answer: http://stackoverflow.com/a/48047864
score: 0
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/48050768
has body: Is there a clever way of setting columns under conditions?for example: import numpy as np import pandas as pd df = pd.DataFrame([[1,2,3],['a','b','c'],[4,5,6]]) df.columns = df.iloc[1,:] 1 a b c 0 1 2 3 1 a b c 2 4 5 6 then remove the row with values ['a','b','c']. 1 a b c 0 1 2 3 1 4 5 6 if there is a clever way such as set_index() function to do so, then what if the columns are multiindexed? many thanks!
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/83157617
type: QuestionComment
has text: umm.. Does profile model must have user_id column?
comment on: http://stackoverflow.com/q/48089545
score: 0
type: Comment

http://stackoverflow.com/comment/83210998
type: Comment
score: 2
comment on: http://stackoverflow.com/q/48117272
type: QuestionComment
has text: The problem in `while True`: on first iteration you got a result `15800.0`, but on second iteration your dictionary do not contains `key = 'price'`.

try-except
tags question: http://stackoverflow.com/q/48054241
type: Tag
tag name: try-except

http://stackoverflow.com/comment/83031345
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48030583
score: 0
has text: What is your expected output format

http://stackoverflow.com/comment/83070916
comment on: http://stackoverflow.com/q/48049601
has text: Well: 1. that's a *class attribute*, which you don't actually need to "initialise" to set an *instance attribute*; and 2. you seem to be mixing up assigning *values* to those attributes (e.g. `(float, float)` is a two-tuple literal with the built-in float class as both elements) with specifying *types*, so please clarify the expected behaviour. Is your teammate also using 3.4.x?
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/83217993
score: 0
type: Comment
has text: Why are you downgrading from Python 3 to Python 2? There are enough differences that you can't really expect compatibility.
type: QuestionComment
comment on: http://stackoverflow.com/q/48120553

tolist
type: Tag
tag name: tolist
tags question: http://stackoverflow.com/q/48078489

http://stackoverflow.com/q/48065805
has comment: http://stackoverflow.com/comment/83104921
type: AnsweredQuestion
score: 3
downvote count: 0
type: Question
has title: Index out of bounds for a 2D Array?
upvote count: 3
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83105550
has answer: http://stackoverflow.com/a/48066121
accepted answer: http://stackoverflow.com/a/48066121
has comment: http://stackoverflow.com/comment/83105468
has body: I am having a 2D List and i am trying to retrieve a column with the index spcified as a parameter (type : IntEnum). I get the index out of bounds error when trying to retrieve any column other then the one at index 0. Enum: class Column(IntEnum): ROAD = 0 SECTION = 1 FROM = 2 TO = 3 TIMESTAMP = 4 VFLOW=5 class TrafficData: data=[[]] Below are member methods of TrafficData Reading from file and storing the matrix: def __init__(self,file): self.data=[[word for word in line.split('\t')]for line in file.readlines()[1:]] Retrieve-ing the desired column: def getColumn(self,columnName): return [line[columnName] for line in self.data] Call: ) column1 = traficdata.getColumn(columnName=Column.ROAD) `column2 = traficdata.getColumn(columnName=Column.FROM)` //error `column3 = traficdata.getColumn(columnName=Column.TO)` //error I attached a picture with the data after __init__ processing: [
tagged with: python

http://stackoverflow.com/comment/83234323
has text: Could you create an [mcve]? Your code doesn't run as-is and one needs more than just minor modifications to make it work (I didn't succeed).
type: QuestionComment
comment on: http://stackoverflow.com/q/48128318
score: 1
type: Comment

http://stackoverflow.com/q/48122018
answer count: 1
has title: make scrapy requests from subfunction
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48122295
accepted answer: http://stackoverflow.com/a/48122295
upvote count: 1
tagged with: python
has body: If I make scrapy requests from a subfunction I get this error: ERROR: Spider must return Request, BaseItem, dict or None, got 'generator' Example code: def parse(self): yield self.subfunc(link) def subfunc(self): yield scrapy.Request(link) I assume it has to do with the way generators work but I am not really familiar with them. Any quick fix? I would like to use the subfunction to organise the code a little bit. I am writing to a csv myself so I do not need to yield items or dicts
tagged with: generator
type: AnsweredQuestion
score: 1
tagged with: scrapy
type: Question

http://stackoverflow.com/a/48097355
has body: I had that same problem, try change this: url: '/master/heights/' + seats_id, for this: url: '/master/heights/' + seats_id + '/', Ajax to django is so strict
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48095677

http://stackoverflow.com/q/48061496
score: 0
upvote count: 1
downvote count: 1
has body: I have following string string = """ Hello/nWorld 123 HelloWorld """ But when I print it I get Hello World 123 HelloWorld But I want to get Hello/nWorld 123 HelloWorld
tagged with: newline
has answer: http://stackoverflow.com/a/48061557
has answer: http://stackoverflow.com/a/48061532
possible better answer: http://stackoverflow.com/a/48061557
type: AnsweredQuestion
has title: Escape new line in triple quoted string - python
favorite count: 0
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48061532
tagged with: python

http://stackoverflow.com/a/48101577
accepted answer of: http://stackoverflow.com/q/48086835
upvote count: 2
has comment: http://stackoverflow.com/comment/83217292
answers question: http://stackoverflow.com/q/48086835
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
has body: When api_key_required is true, you have to provide an API key in the request in addition to any JWTs.

http://stackoverflow.com/comment/83151890
type: Comment
comment on: http://stackoverflow.com/a/48073937
score: 0
type: AnswerComment
has text: If you are currently inside the Anaconda environment, you will have to use `$ python` instead of `$ python3`, because that's what the name of the executable (most likely) is.

http://stackoverflow.com/comment/83079902
comment on: http://stackoverflow.com/q/48053794
has text: Do you have access to the source code?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48078632
upvote count: 5
answers question: http://stackoverflow.com/q/48078445
type: Answer
accepted answer of: http://stackoverflow.com/q/48078445
downvote count: 0
score: 5
has body: It looks as if you have not installed django-nose in your virtual environment. You can install it with: pip install django-nose
has comment: http://stackoverflow.com/comment/83131228
type: AcceptedAnswer

http://stackoverflow.com/q/48079130
has comment: http://stackoverflow.com/comment/83144164
has answer: http://stackoverflow.com/a/48079436
has comment: http://stackoverflow.com/comment/83137325
has comment: http://stackoverflow.com/comment/83133380
favorite count: 0
has title: How to print long string in python
type: UnansweredQuestion
downvote count: 2
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/83132698
has comment: http://stackoverflow.com/comment/83132682
has body: I'm running python 3.6. I'm running a sql query to pull the data. I'm using following query sql="SELECT DISTINCT A.Employee_No " sql=sql+"FROM Employee A " sql=sql+"INNER JOIN Dept B1 " sql=sql+"ON (B1.Dept_ID = A.Dept_ID" sql=sql+"OR B1.Manager_ID = A.Manager_ID " sql=sql+"OR B1.Joining_Date = A.Joining_Date " sql=sql+"OR B1.Group = A.Group) " sql=sql+"And B1.ACCT_YEAR = '"+str(acct_year)+"'" sql=sql+" AND B1.surname in ('"+surname+"') " sql=sql+"AND B1.address IN ('"+address+"')" sql=sql.replace(u'\xa0', ' ') But I'm getting some error in my code. So I put a print statement to check my sql. I used print(sql) &amp; got partial text as output then I tried following code My sql was showing as a series so I changed it to string by using this code &amp; print using textwrap str=sql.to_string() import textwrap print(textwrap.fill(str, 20)) But still I'm getting partial output like this SELECT DISTINCT A.Employee_No FROM Employee... instead of 20 I also tried 40 but still same output. Can you please suggest me how to see the full long string? Can you
type: Question
has comment: http://stackoverflow.com/comment/83132500
has comment: http://stackoverflow.com/comment/83132398
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83133549
has comment: http://stackoverflow.com/comment/83144144
tagged with: spyder

http://stackoverflow.com/comment/83122660
type: AnswerComment
type: Comment
has text: Give the data in the form of text, there might be cleaning required. I can't copy data from a image.
comment on: http://stackoverflow.com/a/48071485
score: 0

http://stackoverflow.com/q/48036233
type: Question
tagged with: curve-fitting
tagged with: python
tagged with: data-fitting
has comment: http://stackoverflow.com/comment/83042617
score: 0
has body: I am having trouble in creating my own fitting function in python. In particular my problem is the following. I have the following set of data: vel = [-337, -108, 79, 309, 518, 528, 494, 432, 203, 15, -236, -401, -496] phase = [-0.1405, -0.0583, 0.0325, 0.0998, 0.174, 0.231, 0.3079, 0.3699, 0.4388, 0.5008, 0.5698, 0.6371, 0.7276] err = [45.342891308377489, 73.067581785521284, 41.676025292022672, 68.304971952287929, 92.089464137519201, 45.111554097374324, 38.922906106705625, 35.431519418447465, 42.787787783231522, 19.305857846218228, 59.22902735428562, 49.416599841251582, 63.027937055619532] Where the first array is the y value, the second is the x and the third one contains the error of the y value. I should now create a function of the form V(\phi) = \gamma + K1*sin(2*pi*\phi) +K2*cos(2*pi*\phi) to fit the data. The values of the parameters have to be obtained from the best fit. Any idea on how to do that?
linked to: http://stackoverflow.com/q/16716302
has title: Create a non-shell fitting function in python
answer count: 0
has comment: http://stackoverflow.com/comment/83196500
type: UnansweredQuestion

http://stackoverflow.com/q/48111037
has body: I'm trying to create a dictionary that is concurrently added to by different threads. To do this I created a singleton class which contains the dictionary instance. To access this dictionary I want a semaphore object (since the incoming key-value pairs are different for different threads) that allows multiple threads to add to the dictionary at once. My attempt in python is below: class recipeDict : initializationLock = threading.lock() semaphore = threading.Semaphore(10) dictInstance = None def _instance(cls): if not cls.dictInstance: with cls.initalizationLock: if not cls.dictInstance: dictInstance = dict() semaphore.acquire() try: return dictInstance finally: semaphore.release() If my goal is to have each thread (25 threads) call recipeDict and access the dictionary contained inside for a bit (to add to it), and then release the semaphore, is this an appropriate implementation?
answer count: 1
has answer: http://stackoverflow.com/a/48111334
has comment: http://stackoverflow.com/comment/83198555
has title: Concurrent Singleton Class Python
type: Question
type: AnsweredQuestion
tagged with: singleton
accepted answer: http://stackoverflow.com/a/48111334
tagged with: python
score: 0
tagged with: multithreading

http://stackoverflow.com/comment/83064232
type: Comment
has text: Is that actually faster than the OP's (after fixing their `.keys()` mistake, of course). Can you share your benchmark results?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48046385

http://stackoverflow.com/comment/83122732
has text: List of days not required, that was just for understanding the total no.s
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48074610
type: Comment

http://stackoverflow.com/comment/83128187
has text: Sure. Here it is. https://pastebin.com/2qFgPVaq.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48077027
score: 0

http://stackoverflow.com/q/48134584
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83246611
has title: How can I change windows security settings using python? i.e. Password Requirements / Require Ctrl - Alt - Delete to log in
favorite count: 0
has comment: http://stackoverflow.com/comment/83259954
has comment: http://stackoverflow.com/comment/84641057
tagged with: python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/83247079
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83247176
has comment: http://stackoverflow.com/comment/83247383
has comment: http://stackoverflow.com/comment/83246404
has comment: http://stackoverflow.com/comment/84631810
has body: I am writing code in Python 2 or 3 to script Cybersecurity functions. Functions such as Lockout Duration, Password Length, and other things that involve a lot of clicking that could easily be automated. import subprocess subproccess.call(x, shell = True) I plan on using that format to run (or enter ((so I don't have to type only press the answer button))) commands in command prompt (with Administrator privileges). However, I have no idea how I should do this, especially the "Require Ctrl - Alt - Delete on Startup." Help would be greatly appreciated.
type: Question

http://stackoverflow.com/comment/83296989
type: Comment
type: QuestionComment
has text: Also http://www.soapboxlabs.com
comment on: http://stackoverflow.com/q/48157624
score: 0

http://stackoverflow.com/q/48101161
has answer: http://stackoverflow.com/a/48101339
type: Question
has title: How to handle Python function def with many parameters that can be called from command line or imported?
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/16878315
has answer: http://stackoverflow.com/a/48101357
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48101369
tagged with: parameters
has body: What's a good way to handle lots of parameters using standard python modules &amp; techniques when creating a function in a module that can be called from the command line or imported and called programmatically? For example: # my_thing.py import argparse def my_thing( param1=None, param2=None, param3=None, param4=None, param5=None, param6=None, param7=None, param8=None): # Do something with all those parameters pass def main(): parser = argparse.ArgumentParser() # add arguments args = parser.parse_args() my_thing( param1=args.param1, param2=args.param2, param3=args.param3, param4=args.param4, param5=args.param5, param6=args.param6, param7=args.param7, param8=args.param8): if __name__ == "__main__": main() or maybe this... # my_thing.py import argparse def my_thing(params): # Do something with all those parameters pass def main(): parser = argparse.ArgumentParser() # add arguments args = parser.parse_args() params = { "param1":args.param1, "param2":args.param2, "param3":args.param3, "param4":args.param4, "param5":args.param5, "param6":args.param6, "param7":args.param7, "param8":args.param8} my_thing(params) if __name__ == "__main__": main()

http://stackoverflow.com/comment/83038737
has text: `df['Full_Entry']=np.where(pd.isnull(df.2), np.NaN, df.1)`
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48034373

http://stackoverflow.com/comment/83009069
comment on: http://stackoverflow.com/a/48019750
score: 0
has text: Can you print the exact **ResultSet** on which you are trying to replace the line breaks?
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48136528
has answer: http://stackoverflow.com/a/48136781
downvote count: 0
accepted answer: http://stackoverflow.com/a/48136781
type: Question
type: AnsweredQuestion
answer count: 1
score: 1
favorite count: 0
has title: Web Scrape Failing - Beautiful Soup
has body: I'm trying to scrape a web page using Beautiful Soup to get a list of 2017 Biggest Tunes. I've tried a number of references in the html source from div to ul to span to li but I cant seem to get anything out of the page. I cant work it out as I've written similar code to parse other sites that has worked. Here's my code: from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = 'http://www.bbc.co.uk/programmes/b09jvtff' # Opening up URL and grabbing info uClient = uReq(my_url) page_html = uClient.read() uClient.close() #html parsing page_soup = soup(page_html, "html.parser") container_a = page_soup.findAll("span",{"class": "artist"}) print(container_a)
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48139562
answers question: http://stackoverflow.com/q/48139453
has body: There is almost no LP solver that does not return arrays/vectors containing the basis status of each variable and each row (or slack). Unfortunately scipy.optimize.linprog is the exception. I am sure if you look at the source you can locate basis status arrays. Pulp is not a solver but a modeling tool. I am not sure what solution info Pulp provides. But you can always generate an MPS file with PULP and feed that in any LP solver. If the solution is non-degenerate you can do something like x(j)&gt;0 =&gt; basic x(j)=0 =&gt; non-basic s(i)&gt;0 =&gt; slack is basic s(i)=0 =&gt; slack is non-basic However if the solution is degenerate we have some basic variables/slacks with value zero.
downvote count: 0
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/83022122
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48026242
score: 4
has text: *"for some reason"* - because you literally call it twice?

http://stackoverflow.com/q/48130844
has title: reading gpio pins of raspberry pi
score: 2
downvote count: 0
favorite count: 0
has body: I am using 8 channel relay, with raspberry pi 3 and programming in python. i want to read or sense the pins if they or low every 5 seconds and to print the output in .txt or .csv file. for single pin I have attached the code and it working fine but how i can expand to all 8 channels (relays). Python code: import time from time import sleep # Allows us to call the sleep function to slow down our loop import RPi.GPIO as GPIO # Allows us to call our GPIO pins and names it just GPIO GPIO.setmode(GPIO.BCM) # Set's GPIO pins to BCM GPIO numbering INPUT_PIN = 26 # Write GPIO pin number. GPIO.setup(INPUT_PIN, GPIO.IN) # Set our input pin to be an input # Start a loop that never ends while True: if (GPIO.input(INPUT_PIN) == True): # load is turned off. print (time.strftime ("%Y/%m/%d , %H:%M:%S"),"0") else: #now 20 watt load is turned ON!. print(time.strftime ("%Y/%m/%d , %H:%M:%S"),"20") sleep(10); # Sleep for 10 seconds. and i want to save all the data in a .csv or .txt file with time stamp at the start and other 8 columns for pins status that are connected with relay. My output should look like: 06/01/2018,18:54:00,1,0,1,1,1,0,0,0 06/01/2018,18:54:05,1,0,1,1,1,0,0,0 06/01/2018,18:54:10,1,0,1,1,1,0,0,0 06/01/2018,18:54:15,1,0,1,1,1,0,0,0 06/01/2018,18:54:20,0,0,0,0,0,0,0,0
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/48131021
upvote count: 2
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/48111296
tagged with: iteration
has comment: http://stackoverflow.com/comment/83198851
has comment: http://stackoverflow.com/comment/83199014
has body: I am writing a program that takes in a list of start and end times for farmers milking cows and determines both the longest time where >=1 cow is being milked and the longest time where no cows are being milk. In it, I've tried using this function. It's an exercise on complete search, but this isn't fast enough when there's a lot of data (I think because there are n^2 iterations). timesIS is simply a list of the times in increasing start order, and timesDE is a list of the same times by decreasing end. timeIndex is the position from which to start. For the longest interval of milking, my program later does this for every index and returns the longest interval. While still keeping to a complete search, how can I make this more efficient (switch to something closer to n passes, perhaps)? def nextCease(TimesIS, timesDE, timeIndex): latestTime = TimesIS[timeIndex][1] for j in range (0, len(timesDE)): for i in range (0, len(timesDE)): if timesDE[i][0]&lt;=latestTime and timesDE[i][1]&gt;=latestTime: latestTime = timesDE[i][1] if latestTime == timesDE[0][1]: return latestTime break return latestTime Here's a small piece of data input (first line is just the number of farmers): 6 100 200 200 400 400 800 800 1600 50 100 1700 3200 I think this is a minimal, complete, and verifiable example: from operator import itemgetter times = [[100,200], [200,400], [400,800], [800,1600], [50,100], [1700,3200] def nextCease(TimesIS, timesDE, timeIndex): latestTime = TimesIS[timeIndex][1] for j in range (0, len(timesDE)): for i in range (0, len(timesDE)): if timesDE[i][0]&lt;=latestTime and timesDE[i][1]&gt;=latestTime: latestTime = timesDE[i][1] if latestTime == timesDE[0][1]: return latestTime break return latestTime timesIS = sorted(times[:], key=itemgetter(0)) #increasing starttimes timesDE = sorted(times[:], key=itemgetter(1), reverse=True) #decreasing endtimes longestIntervalMilk = 0 for i in range (0, len(times)): interval = nextCease(timesIS, timesDE, i) - timesIS[i][0] if interval…
has comment: http://stackoverflow.com/comment/83198448
tagged with: python
accepted answer: http://stackoverflow.com/a/48112301
has comment: http://stackoverflow.com/comment/83199158
has comment: http://stackoverflow.com/comment/83198837
has title: Python complete search in one pass function
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83198998
type: Question
tagged with: search
has comment: http://stackoverflow.com/comment/83198301
score: 0
has answer: http://stackoverflow.com/a/48112301
answer count: 1

http://stackoverflow.com/comment/83148846
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48086586
has text: Yeah I want to target track objects as this pointcloud evolves using connected components analysis, and the first big challenge to this is creating a dilation mask that operates on pointclouds instead of an image

http://stackoverflow.com/comment/83210796
comment on: http://stackoverflow.com/q/48116843
score: 0
type: QuestionComment
has text: @leeum Updated question my bad logic was wrong.
type: Comment

http://stackoverflow.com/a/48024361
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48022796
has comment: http://stackoverflow.com/comment/83018761
upvote count: 2
has body: Create a generator of lists made from the elements from index 2 onwards for each item in the world[int(room)] list: if not object[2:] in (i[2:] for i in world[int(room)]): world[int(room)].append(object) N.b. you should also not use object as it is an identifier that refers to a built-in type, so by using it as a variable name, you are overriding it.
answers question: http://stackoverflow.com/q/48022796
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83018759
type: Answer
score: 2

http://stackoverflow.com/a/52193795
has comment: http://stackoverflow.com/comment/98072487
type: Answer
answers question: http://stackoverflow.com/q/48079973
upvote count: 33
score: 33
has comment: http://stackoverflow.com/comment/98114594
has body: The sample_weight parameter allows you to specify a different weight for each training example. The scale_pos_weight parameter lets you provide a weight for an entire class of examples ("positive" class). These correspond to two different approaches to cost-sensitive learning. If you believe that the cost of misclassifying positive examples (missing a cancer patient) is the same for all positive examples (but more than misclassifying negative ones, e.g. telling someone they have cancer when they actually don't) then you can specify one single weight for all positive examples via scale_pos_weight. XGBoost treats labels = 1 as the "positive" class. This is evident from the following piece of code: if (info.labels[i] == 1.0f) w *= param_.scale_pos_weight See this question. The other scenario is where you have example-dependent costs. One example is detecting fraudulent transactions. Not only a false negative (missing a fraudulent transaction) is more costly than a false positive (blocking a legal transaction), but the cost of missing a false negative is proportional to the amount of money being stolen. So you want to give larger weights to positive (fraudulent) examples with higher amounts. In this case, you can use the sample_weight parameter to specify example-specific weights.
has comment: http://stackoverflow.com/comment/98051602
has comment: http://stackoverflow.com/comment/133597856
downvote count: 0
has comment: http://stackoverflow.com/comment/98094051

http://stackoverflow.com/comment/83233319
has text: The `tol` argument for `corpcor` must be multiplied by `10` to get the same results as `ginv` in `MASS`. With the (standard) `tol` (as given in the answer and used in `ginv`) `fast.svd` accepts 4 singular values but `ginv` accepts only 3 singular values as satisfying the tolerance restriction.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48117726
type: Comment

http://stackoverflow.com/a/48164616
score: 1
answers question: http://stackoverflow.com/q/48164479
has comment: http://stackoverflow.com/comment/83309267
downvote count: 0
has body: What do you expect assert to return and why would you want to print that value? Your usage is just not very idiomatic. Take out the print and add a description of the thing you are testing to the assert as its second argument. assert is_valid_date(2014,4,4), "2014,4,4 is a valid date tuple" assert is_valid_date(2012,1,3), "2012,1,3 is a valid date tuple" Tangentially, maybe you want to refactor your function to avoid the arrow antipattern def is_valid_date(year, month, day): """ Inputs: year - an integer representing the year month - an integer representing the month day - an integer representing the day Returns: True if year-month-day is a valid date and False otherwise """ if year &lt;= datetime.MINYEAR: return False if year &gt;= datetime.MAXYEAR: return False if month &lt; 1: return False if month &gt; 12: return False if day &lt; 1: return False if day &gt; days_in_month(year, month): return False return True This is perhaps overdoing it, but you'll notice how adding new conditions is now easy, and adding debug prints to see exactly where the code is rejecting an input is now very straightforward.
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83309242

http://stackoverflow.com/comment/83343404
type: Comment
score: 1
has text: If you're looking for how to handle that NULL produced by the left join, then use the COALESCE function in SQL: `func.coalesce(func.avg(ReviewModel.star), 0.0)`.
type: QuestionComment
comment on: http://stackoverflow.com/q/48166292

http://stackoverflow.com/q/48104713
has comment: http://stackoverflow.com/comment/83185128
has comment: http://stackoverflow.com/comment/83185421
has answer: http://stackoverflow.com/a/48104800
accepted answer: http://stackoverflow.com/a/48104800
tagged with: python
has body: I have an array that looks like this: a = [['3','4','5','gg','5','6','7'], ['3','ww','6','7','4','2','3']] Is there a smart way to convert only the non digit elements to be 0?
type: AnsweredQuestion
has title: using masking to change string in an array
possible better answer: http://stackoverflow.com/a/48105115
has comment: http://stackoverflow.com/comment/83185649
type: Question
has answer: http://stackoverflow.com/a/48105115
has comment: http://stackoverflow.com/comment/83185172
tagged with: numpy
score: 0
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/83185635
downvote count: 1
has comment: http://stackoverflow.com/comment/83185729
favorite count: 0
has comment: http://stackoverflow.com/comment/83185319

http://stackoverflow.com/comment/83224457
has text: yes, but now I think about it, it'd be more interesting to also have a condition where it doesn't have to be, as long as the pair appears in different years. I'll edit the question. Thanks for asking!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48123740

http://stackoverflow.com/a/48031438
has comment: http://stackoverflow.com/comment/83033071
has comment: http://stackoverflow.com/comment/83033424
type: Answer
has comment: http://stackoverflow.com/comment/83081999
accepted answer of: http://stackoverflow.com/q/48031274
answers question: http://stackoverflow.com/q/48031274
upvote count: 1
has body: There are multiple ways of doing it, some of them documented on this question. Although there is an accepted answer, I would recommend trying the one that uses the library schedule (pip install schedule). The code looks like this: import schedule import time def job(t): print "I'm working...", t return schedule.every().day.at("01:00").do(job,'It is 01:00') while True: schedule.run_pending() time.sleep(60) # wait one minute
score: 1
has comment: http://stackoverflow.com/comment/83033106
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48085979
has answer: http://stackoverflow.com/a/48086031
favorite count: 0
linked to: http://stackoverflow.com/q/15037175
tagged with: python
score: -2
answer count: 4
possible better answer: http://stackoverflow.com/a/48086036
has comment: http://stackoverflow.com/comment/83146901
has answer: http://stackoverflow.com/a/48086261
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48086036
has title: Nested loops where inner loop variable depends on outer loop variable, Python
accepted answer: http://stackoverflow.com/a/48086031
downvote count: 2
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/83147546
has answer: http://stackoverflow.com/a/48086049
linked to: http://stackoverflow.com/q/47347945
has body: In Java, if I want to create nested loops where the inner loop variable depends on the outer loop variable (e.g. in typical bubble sort implementations), I can do something like this: for(int i=0; i &lt; n; i++){ for(int j=i; j &lt; n; j++){ // Do something, e.g compare elements at index i and j } } What's the most "Pythonic" way to accomplish this in Python? I'm having trouble when I try to set the inner loop variable to the outer loop variable. For example, this doesn't work: for i in range(n): for j=i in range(n): # Do something, e.g compare elements at index i and j
upvote count: 0

http://stackoverflow.com/comment/83282618
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48152069
has text: This doesnt make sense. `dir1/file1 -D python dir2/file2 > script.py` Will run `dir1/file1` as an executable, passing `-D python dir2/file2` as arguments. The stdout of that process is then redirected into a file called `script.py`.
type: Comment

http://stackoverflow.com/a/48052389
downvote count: 0
has body: Perhaps a less concise but easier to read method would be: b = [] for i in range(0, 3): c = "a" + str(i) b.append(c) Here we take an empty list and add a string with the desired letter and the value of range() add them together and use the append() method to add them to the list.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48052336
upvote count: 2

http://stackoverflow.com/comment/83209460
type: Comment
score: 1
has text: That really depends on your requirements. I'd assume that as far as setup goes, setting multiple values at once would be more efficient, but extracting them back might not be. Maybe the best way would be to use `set_many` which is basically a more efficient way of doing method one with one command
type: QuestionComment
comment on: http://stackoverflow.com/q/48116218

http://stackoverflow.com/a/48062547
has comment: http://stackoverflow.com/comment/94104554
score: 18
has body: As far as I can tell, the first dimension of the values is meant to be the batch_size. So when input_fn returns the data, it should return data as a batch. It works once you return the data as a batch, e.g.: dataset = tf.data.TextLineDataset(data_file) dataset = dataset.map(parse_csv) dataset = dataset.batch(10) # or any other batch size
answers question: http://stackoverflow.com/q/48046504
upvote count: 18
type: Answer
downvote count: 0

http://stackoverflow.com/q/48129163
has body: str1 = ['106.51.107.185', '122.169.20.139', '123.201.53.226'] str2 = ['106.51.107.185', '122.169.20.138', '123.201.53.226'] I need to match the above string based on their respective Index. str1[0] match str2[0] str1[1] match str2[1] str1[2] match str2[2] based on the match i need the output. I tried from my end, between the 2 strings, str[0] is checking the match with str2[:], it need to match only with the respective indexes alone. Please assist. Thanks !!!
has answer: http://stackoverflow.com/a/48130588
has answer: http://stackoverflow.com/a/48129189
favorite count: 0
has comment: http://stackoverflow.com/comment/83234983
possible better answer: http://stackoverflow.com/a/48129190
upvote count: 2
has answer: http://stackoverflow.com/a/48129224
has answer: http://stackoverflow.com/a/48129190
tagged with: python
accepted answer: http://stackoverflow.com/a/48130588
answer count: 4
type: AnsweredQuestion
has title: Python String Match with respective index
score: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83244424

http://stackoverflow.com/comment/83335756
comment on: http://stackoverflow.com/a/48161909
score: 0
type: Comment
type: AnswerComment
has text: I tried: 'code' with gzip.open(service_file, 'rb') as infile, with open(input_file, 'wb') as outfile: writer = csv.writer(outfile) writer.writerows(infile) But it does not work?

http://stackoverflow.com/q/48021882
favorite count: 0
type: Question
tagged with: python
tagged with: kivy
tagged with: kivy-language
has title: get value of dynamic add textbox
upvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/48057239
has body: I have two file test.py and test.kv In test.kv text: "+Add More" which add row dynamic vertical position.I am creating dynamic id in .py self.add_widget(Row(button_text=str(self.row_count),id=str("test"+str(self.row_count)))) and in .kv file i am assigning id id : root.id Can anyone tell me how to get all dynamic value value1,value2,value3 in .py file Any advise or guidance would be greatly appreciated..!! [![enter image description here][1]][1] test.py from kivy.uix.screenmanager import Screen from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.uix.boxlayout import BoxLayout from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty Window.size = (450, 525) class display(Screen): def add_more(self): self.ids.rows.add_row() def insert_value(self): print(Row().id) #print(self.ids.) class Row(BoxLayout): button_text = StringProperty("") id = ObjectProperty(None) class Rows(BoxLayout): orientation = "vertical" row_count = 0 def __init__(self, **kwargs): super(Rows, self).__init__(**kwargs) self.add_row() def add_row(self): self.row_count += 1 self.add_widget(Row(button_text=str(self.row_count),id=str("test"+str(self.row_count)))) class test(App): def build(self): self.root = Builder.load_file('test.kv') return self.root if __name__ == '__main__': test().run() test.kv &lt;Row&gt;: #state1 : state1 orientation: "horizontal" spacing: 0, 5 Button: text: root.button_text size_hint_x: .2 TextInput: #text : root.id size_hint_x: .8 id : root.id display: BoxLayout: orientation: "vertical" padding : 20, 20 BoxLayout: orientation: "horizontal" Button: size_hint_x: .2 text: "+Add More" valign: 'bottom' on_press: root.add_more() BoxLayout: orientation: "horizontal" Label: size_hint_x: .2 text: "SN" valign: 'bottom' Label: size_hint_x: .8 text: "Value" valign: 'bottom' Rows: id: rows BoxLayout: orientation: "horizontal" padding : 10, 0 spacing: 10, 10 size_hint: .5, .7 pos_hint: {'x': .2…
type: AnsweredQuestion
score: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/48057239

http://stackoverflow.com/a/54739204
has body: Another possibility, is the machine has an older version of xlrd installed separately, and it's not in the "..:\Python27\Scripts.." folder. In another word, there are 2 different versions of xlrd in the machine. when you check the version below, it reads the one not in the "..:\Python27\Scripts.." folder, no matter how updated you done with pip. print xlrd.__version__ Delete the whole redundant sub-folder, and it works. (in addition to xlrd, I had another library encountered the same)
score: 0
answers question: http://stackoverflow.com/q/48066517
type: Answer

http://stackoverflow.com/comment/83111532
score: 0
has text: Even Python 2.x handles Unicode fairly well (for *x* >= 6 or so at least) but the JSON decoder might be picky about what Unicode it accepts. Try doubling the backslash in `\u` maybe? And please [edit] your question to document the Python version requirement; 2.6 didn't have `json` out of the box so I'm guessing add the tag [tag:python-2.7] ...?
type: Comment
comment on: http://stackoverflow.com/a/48067935
type: AnswerComment

http://stackoverflow.com/comment/83313780
has text: What is the exact reason you believe the 2 results should be the same?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48158760

http://stackoverflow.com/comment/83272467
comment on: http://stackoverflow.com/q/48112044
score: 0
type: Comment
type: QuestionComment
has text: ok, thanks...https://gis.stackexchange.com/questions/267232/working-with-shapefiles-in-python

http://stackoverflow.com/comment/83021469
comment on: http://stackoverflow.com/q/48025821
score: 0
type: Comment
has text: @PatrickHaugh I wanted to restrict to insert only given size.
type: QuestionComment

http://stackoverflow.com/comment/83175566
comment on: http://stackoverflow.com/q/48100159
has text: I'd say "Welcome to Stack Overflow", but I see you've been here long enough to get 6 medals. You should probably already know that most people won't do the program for you, but are willing to help you with the work you've done. Here's some hints. You'll want to look into [csv](https://docs.python.org/3/library/csv.html) for reading and writing, and [sorting with a special key](https://docs.python.org/3/howto/sorting.html#key-functions) to handle sorting the way you want.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83216317
score: 0
type: Comment
type: QuestionComment
has text: and to find the correct tools to do so, your sounds like file-io, dictionary and some itertools should be able to solve it: https://docs.python.org/3.6/library/filesys.html & https://docs.python.org/3.6/library/itertools.html & https://docs.python.org/3.6/library/stdtypes.html#mapping-types-dict . Or you could whip out the big guns and go wiht panda or numpy. Have fun.
comment on: http://stackoverflow.com/q/48119814

http://stackoverflow.com/comment/83105743
score: 0
comment on: http://stackoverflow.com/a/48065926
type: AnswerComment
type: Comment
has text: @toyo10 Yes, I understand. But this code uses glob too. Try it.

http://stackoverflow.com/comment/83210583
has text: That is not how you install a module. You can `pip install pyperclip` from the command line, you should not try to just run `setup.py`
score: 1
comment on: http://stackoverflow.com/q/48117158
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/131210598
type: AnswerComment
comment on: http://stackoverflow.com/a/73434775
type: Comment
has text: is it possible that this interpolation function is way way slower than vanilla python implementations? I might have done something wrong but its like 20x slower for a test run that I have. I was hoping to make it 20x faster lol
score: 0

http://stackoverflow.com/comment/83219281
type: Comment
comment on: http://stackoverflow.com/q/48121303
score: 2
has text: Compiling the regexes in advance helps because it can cache the state machines it generates. Backreferences can be slow as well.
type: QuestionComment

http://stackoverflow.com/comment/83024886
type: Comment
type: QuestionComment
has text: @BorrajaX You are correct but in pandas this might actually be a bit of a shock for the OP since a _lot_ of operations require `inplace=True` to actually take effect in such a way, so I can see where their confusion comes from :)
comment on: http://stackoverflow.com/q/48027375
score: 0

http://stackoverflow.com/q/48120003
tagged with: python
tagged with: request
score: 1
has answer: http://stackoverflow.com/a/48120173
upvote count: 1
type: Question
has title: requests.get() and / or BeautifulSoup() behaviour inconsistent
answer count: 1
downvote count: 0
has body: I have the following code: __PARENT_TAG = "article" def _navigate_to_xxx(self): """acquire html from xxx and beautify the raw html""" html = requests.get(xxx.__BASE_URL + xxx.__EXTENDED_URL) self.beautified_html = BeautifulSoup(html.content, "html.parser") def _extract(self): """helper function that extracts elements from beautified_html and returns it""" element_list = None element_list = self.beautified_html.findAll(self.__PARENT_TAG) logging.debug("The number of __PARENT_TAG is: {0}".format(len(element_list))) return element_list The problem is for the same web page, the result I got from the debugging line is sometimes 18 and sometimes 20 (I expected 20). Anyone know why this happens?
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion

http://stackoverflow.com/comment/83201767
type: QuestionComment
type: Comment
has text: You could convert it to [base64](https://stackoverflow.com/questions/3715493/encoding-an-image-file-with-base64).
comment on: http://stackoverflow.com/q/48112886
score: 0

http://stackoverflow.com/comment/83164319
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48094443
type: AnswerComment
has text: I've update the example a bit based on what you've said you're trying to achieve.

http://stackoverflow.com/q/48144326
type: UnansweredQuestion
tagged with: python-multithreading
tagged with: multithreading
tagged with: python
has comment: http://stackoverflow.com/comment/83266904
answer count: 0
has body: In my current Python project I have such structure: file A has a Meta class which stores some global resources, such as a global DB access (Meta.db) file B has many classes, each class calls the global DB access Meta.db to access the database Here comes the problem: in file C, there is a function spawns around 20 threads (no lock, as no global resource are shared directly by threads), each thread calls different classes in file B, to manipulate database for different purposes, like this: file C spawns 20 threads ----> each thread call classes in file B ----> each class call Meta.db, the global single DB access The program runs with no errors, but very high in context switching (99% of runtime), therefore I would like to know whether this way of implementation is practical? or thread-safe?
tagged with: thread-safety
type: Question
tagged with: locking
has title: Is this way of shared resource thread-safe?
has comment: http://stackoverflow.com/comment/83267217
score: 0

http://stackoverflow.com/comment/83218495
comment on: http://stackoverflow.com/q/48106077
type: QuestionComment
has text: Yes, the minimum is inclusive
score: 0
type: Comment

http://stackoverflow.com/comment/83119562
type: Comment
has text: well you were providing 8000 characters for CharField which is not justfied, it can hold 255 characters, thus i changed it to TextField which can contain a large number of charaters, and you missed on_delete key before the models.DO_NOTHING
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48072039

http://stackoverflow.com/a/48031685
accepted answer of: http://stackoverflow.com/q/48030419
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 1
has body: It's important understanding that in Python everything is an object (including functions, and a class declaration itself) When you do this: class Classy(): inty = 3 stringy = "whatevs" You're assigning inty and stringy to the Class, not to the instances. Check this: class Classy(): inty = 3 stringy = "whatevs" print(Classy.__dict__) Wait... A class with a __dict__? Yeah, because Classy is also an instance (of type classobj, since you're using old style classes, which you shouldn't really do, by the way... You should inherit from object, which gives you access to more goodies) &gt;&gt;&gt; print(type(Classy)) &lt;type 'classobj'&gt; Now, if you created an instance of classy, and put an inty value to it, you would have: class Classy(): inty = 3 stringy = "whatevs" def __init__(self): self.inty = 5 classy = Classy() print("__dict__ of instance: %s" % classy.__dict__) print("__dict__ of Class: %s" % classy.__class__.__dict__) Which outputs __dict__ of instance: {'inty': 5} __dict__ of Class: {'__module__': '__main__', 'inty': 3, '__doc__': None, '__init__': &lt;function __init__ at 0x1080de410&gt;, 'stringy': 'whatevs'} See the inty being 5 in the __dict__ of the instance but still being 3 in the __dict__ of the class? It's because now you have two inty: One attached to classy, an instance of the class Classy and another one attached to the class Classy itself (which is, in turn, an instance of classobj) If you did classy = Classy() print(classy.inty) print(classy.stringy) You'd see: 5 whatevs Why? Because when you try to get inty on the instance, Python will look for it in the __dict__ of the instance first. If it doesn't find it, it will go to the __dict__ of the class. That is what's happening on classy.stringy. Is it in the classy instance? Nopes. Is it in the Classy class? Yep! Aight, return that one... And that's the one you see. Also, I mentioned that the Classy class is an object, right? And as such, you can assign it to something else like this: What = Classy #…
downvote count: 1
answers question: http://stackoverflow.com/q/48030419
has comment: http://stackoverflow.com/comment/83049491

http://stackoverflow.com/a/48091658
downvote count: 0
score: 1
has body: Try: ulist = [] # unique-list outdict = {} # dict for output for i in names.items(): # i will be as: (1, ('c1', 1)) if i[1][0] not in ulist: ulist.append(i[1][0]) # add unique item to unique-list outdict[i[0]] = i[1] # add entry to output dict print(outdict) Output: {1: ('c1', 1), 2: ('c2', 2)}
answers question: http://stackoverflow.com/q/48091123
upvote count: 1
type: Answer

http://stackoverflow.com/comment/83951016
comment on: http://stackoverflow.com/a/48113762
has text: Yes, I remember these days, I was astonished too;)
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48073918
possible better answer: http://stackoverflow.com/a/50052489
has answer: http://stackoverflow.com/a/50052489
answer count: 2
tagged with: scollector
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51054632
tagged with: python
type: AnsweredQuestion
tagged with: opentsdb
score: 1
has body: I am trying to run external sample.py script in /path-to-scollector/collectors/0 folder from scollector. scollector.toml: Host = "localhost:0" ColDir="//path-to-scollector//collectors//" BatchSize=500 DisableSelf=true command to run scollector: scollector-windows-amd64.exe -conf scollector.toml -p But I am not getting the sample.py metrics in the output. It is expected to run continuosly and print output to cnosole. Also when I am running: scollector-windows-amd64.exe -conf scollector.toml -l my external collector is not listed.
upvote count: 1
type: Question
has title: How to run External collector from Scollector?
has answer: http://stackoverflow.com/a/51054632

rendering
tags question: http://stackoverflow.com/q/48150506
tag name: rendering
type: Tag

http://stackoverflow.com/a/48130952
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Job for enumerate: for (idx, st) in enumerate(example_list, 1): print('This is file number {} for {}'.format(idx, st.split('/')[-1])) enumerate(example_list, 1) enumerates the list with setting starting index as 1 print('This is file number {} for {}'.format(idx, st.split('/')[-1])) prints in desired format, with st.split('/')[-1]) getting the last member of the / split-ted list. As / is the directory separator in POSIX systems, no filename can contain /, so split('/')[-1] should works the same as os.path.basename. But, it's better to use os.path.basename BTW. Example: In [46]: example_list = ['./Data/File_1.csv', './Data/File_2.csv', './Data/File_3.csv'] In [47]: for (idx, st) in enumerate(example_list, 1): print('This is file number {} for {}'.format(idx, st.split('/')[-1])) ....: This is file number 1 for File_1.csv This is file number 2 for File_2.csv This is file number 3 for File_3.csv
answers question: http://stackoverflow.com/q/48130932
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48130932

http://stackoverflow.com/a/48168095
upvote count: 5
score: 5
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84327531
has body: If I understood you correctly and you want to calculate mean and std values for all images: Demo: 2 images of (2,2,3) shape each (for the sake of simplicity): In [189]: a Out[189]: array([[[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]], [[[13, 14, 15], [16, 17, 18]], [[19, 20, 21], [22, 23, 24]]]]) In [190]: a.shape Out[190]: (2, 2, 2, 3) In [191]: np.mean(a, axis=(0,1,2)) Out[191]: array([ 11.5, 12.5, 13.5]) In [192]: np.einsum('ijkl-&gt;l', a)/float(np.prod(a.shape[:3])) Out[192]: array([ 11.5, 12.5, 13.5]) Speed measurements: In [202]: a = np.random.randint(255, size=(128,32,32,3)) In [203]: %timeit np.mean(a, axis=(0,1,2)) 9.48 ms ± 822 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [204]: %timeit np.einsum('ijkl-&gt;l', a)/float(np.prod(a.shape[:3])) 1.82 ms ± 22.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
answers question: http://stackoverflow.com/q/48159562

http://stackoverflow.com/comment/83156972
has text: Hi, it turned out that because of the structure of the original python code, it would be not ideal to use Jython. It will even be simpler to rewrite in Java, so we switched to another approach. Thanks anyway
comment on: http://stackoverflow.com/q/48017496
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83246971
comment on: http://stackoverflow.com/q/48065893
has text: I was told to wait for 6 days before asking any other question. As it was urgent so I post it here.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48109297
type: Question
score: 3
has answer: http://stackoverflow.com/a/48110578
has title: Get the names of all virtual machines in an azure scale set via the Python SDK
tagged with: azure-vm-scale-set
answer count: 1
downvote count: 0
favorite count: 0
tagged with: azure
accepted answer: http://stackoverflow.com/a/48110578
has body: How do I get a list of all the names of VMs in a scale set via the Python SDK? I think this might have the answer, but I cant create an instance of the class.
tagged with: python
type: AnsweredQuestion
upvote count: 3
tagged with: azure-virtual-machine

http://stackoverflow.com/comment/83202979
type: AnswerComment
comment on: http://stackoverflow.com/a/48113674
type: Comment
has text: Looks like this is it :) will approve in a bit.
score: 0

http://stackoverflow.com/q/48031700
downvote count: 0
has answer: http://stackoverflow.com/a/48590757
has answer: http://stackoverflow.com/a/48498143
has comment: http://stackoverflow.com/comment/83989514
has title: Loop through url with Selenium Webdriver
has comment: http://stackoverflow.com/comment/84033002
has answer: http://stackoverflow.com/a/48031765
has comment: http://stackoverflow.com/comment/83033675
has answer: http://stackoverflow.com/a/48538048
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84056465
tagged with: selenium-webdriver
score: 2
upvote count: 2
answer count: 5
has answer: http://stackoverflow.com/a/48519514
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48538048
has comment: http://stackoverflow.com/comment/84021712
has body: The below request finds the contest id's for the day. I am trying to pass that str into the driver.get url so it will go to each individual contest url and download each contests CSV. I would imagine you have to write a loop but I'm not sure what that would look like with a webdriver. import time from selenium import webdriver import requests import datetime req = requests.get('https://www.draftkings.com/lobby/getlivecontests?sport=NBA') data = req.json() for ids in data: contest = ids['id'] driver = webdriver.Chrome() # Optional argument, if not specified will search path. driver.get('https://www.draftkings.com/account/sitelogin/false?returnurl=%2Flobby'); time.sleep(2) # Let DK Load! search_box = driver.find_element_by_name('username') search_box.send_keys('username') search_box2 = driver.find_element_by_name('password') search_box2.send_keys('password') submit_button = driver.find_element_by_xpath('//*[@id="react-mobile-home"]/section/section[2]/div[3]/button/span') submit_button.click() time.sleep(2) # Let Page Load, If not it will go to Account! driver.get('https://www.draftkings.com/contest/exportfullstandingscsv/' + str(contest) + '')
type: Question
possible better answer: http://stackoverflow.com/a/48590757

http://stackoverflow.com/q/48086214
upvote count: 2
has comment: http://stackoverflow.com/comment/83147587
has answer: http://stackoverflow.com/a/48086348
has comment: http://stackoverflow.com/comment/83147631
has answer: http://stackoverflow.com/a/48086346
has comment: http://stackoverflow.com/comment/83147387
favorite count: 0
tagged with: python
answer count: 4
possible better answer: http://stackoverflow.com/a/48086260
score: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48086263
has body: How can I read the inputted value "transform" from the instance of this subclass? class Str(str): def __repr__(self): return "mesh" def __str__(self): return "mesh" string = Str("transform") print(string) # mesh print(repr(string)) # mesh
has comment: http://stackoverflow.com/comment/83147618
has comment: http://stackoverflow.com/comment/83147498
has comment: http://stackoverflow.com/comment/83147503
type: Question
has comment: http://stackoverflow.com/comment/83147464
has answer: http://stackoverflow.com/a/48086263
has title: Actual value of a subclassed str
has comment: http://stackoverflow.com/comment/83147458
has answer: http://stackoverflow.com/a/48086260

google-app-engine-python
type: Tag
tag name: google-app-engine-python
tags question: http://stackoverflow.com/q/48110614

http://stackoverflow.com/comment/83285466
type: AnswerComment
type: Comment
has text: two blocks that are parsed should have `block values` as main index to parse information between blocks. like `{'7': defaultdict(<class 'list'>, {'chr': ['7', '7', '7', '7', '7'], 'pos': ['05', '11', '15', '21', '31'], 'A_val': ['ATC', 'TCG', .... ]}), '9': defaultdict(<class 'list'>, {'chr': ['2', '2', .... ], 'pos': ['42', '55', '61'], 'A_val': ['T,C,G', 'C,G,GC', .... ]}))}`. Also, we read only when until we have two unique keys.
comment on: http://stackoverflow.com/a/48153004
score: 0

http://stackoverflow.com/q/48160009
type: Question
tagged with: sockets
has title: Send File From Python Server to Java Client
linked to: http://stackoverflow.com/q/5562370
tagged with: python
upvote count: 1
has comment: http://stackoverflow.com/comment/83299751
answer count: 1
has body: I am trying to send files from a Python server to Java client over a TCP socket. Here is what I have so far: Java Client (Note that all of the file transfer code is in the getFile() method): public class Client1 { private Socket socket = null; private FileOutputStream fos = null; private DataInputStream din = null; private PrintStream pout = null; private Scanner scan = null; public Client1(InetAddress address, int port) throws IOException { System.out.println("Initializing Client"); socket = new Socket(address, port); scan = new Scanner(System.in); din = new DataInputStream(socket.getInputStream()); pout = new PrintStream(socket.getOutputStream()); } public void send(String msg) throws IOException { pout.print(msg); pout.flush(); } public void closeConnections() throws IOException { // Clean up when a connection is ended socket.close(); din.close(); pout.close(); scan.close(); } // Request a specific file from the server public void getFile(String filename) { System.out.println("Requested File: "+filename); try { File file = new File(filename); // Create new file if it does not exist // Then request the file from server if(!file.exists()){ file.createNewFile(); System.out.println("Created New File: "+filename); } fos = new FileOutputStream(file); send(filename); // Get content in bytes and write to a file int counter; byte[] buffer = new byte[8192]; while((counter = din.read(buffer, 0, buffer.length)) != -1) { fos.write(buffer, 0, counter); } } fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } } And the Python Server: import socket host = '127.0.0.1' port = 5555 # Create a socket with port and host bindings def setupServer(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Socket created") try: s.bind((host, port)) except socket.error as msg: print(msg) return s # Establish connection with a client def setupConnection(): s.listen(1) # Allows one connection at a time print("Waiting for client") conn, addr = s.accept() return c…
has comment: http://stackoverflow.com/comment/83299645
has answer: http://stackoverflow.com/a/48693181
has comment: http://stackoverflow.com/comment/83299624
tagged with: java
has comment: http://stackoverflow.com/comment/83299731
has comment: http://stackoverflow.com/comment/83299667
tagged with: client-server
tagged with: file-transfer
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48693181

http://stackoverflow.com/comment/83295630
type: QuestionComment
comment on: http://stackoverflow.com/q/48121424
has text: Without trying to bore you with the details, I tried to help him download Python3.6 over the phone but all these issues kept popping up, and my limited windows touble-shooting tactics didn't work, so I decided I'd just zip it up with pyinstall which is what I do when I write little scrips for my co-workers.
score: 0
type: Comment

http://stackoverflow.com/q/48154573
score: 1
has answer: http://stackoverflow.com/a/48156548
accepted answer: http://stackoverflow.com/a/48156548
has title: Append pyodbc.Rows into a data frame using a loop
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48155989
downvote count: 0
has comment: http://stackoverflow.com/comment/83288226
has comment: http://stackoverflow.com/comment/83288247
tagged with: pandas
tagged with: sql
upvote count: 1
has answer: http://stackoverflow.com/a/48155989
has comment: http://stackoverflow.com/comment/83288332
has comment: http://stackoverflow.com/comment/83288414
favorite count: 0
tagged with: python
tagged with: pyodbc
has body: I am trying to import some data from a sql server to python. I would like to import the data row by row and append it to a data frame iteratively. My code so far is: data_NS = pd.DataFrame(columns=Fields_NS) i=0 while(i &lt; 10): row = cursor.fetchone() rowAsList = list(row) data_NS.append(rowAsList) i = i+1 conn.close() The result for data_NS is and empty data frame. I am not receiving any error messages so any information will be greatly appreciated.
type: AnsweredQuestion

http://stackoverflow.com/q/48035105
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83040182
has comment: http://stackoverflow.com/comment/83040276
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48035280
has body: I am using pandas to automatically clean a number of CSV files. The data looks like this date value 1 13 Sep 9 2 5 Oct 8 3 10 Oct 99 I use the following code to convert the string to datetime pd.to_datetime(new_df[0].str.replace(' ', ''), format='%d%b') (The replace is done to remove the extra spaces that sometimes occur) This works fine - except for the fact that no year is supplied in the date and pandas gives it the year 1900 by default date value 1 1900-09-13 9 2 1900-10-05 8 3 1900-10-10 99 Luckily, I can fetch the year from the filename and have it standing by as the variable 'fileyear'. But I am unsure how to use it to set the correct date. I tried something like: pd.to_datetime(new_df[0].str.replace(' ', ''), format='%d%b' + '2016') But that does not work. Does anyone know how to supply a (partially) known date to a datetimeformat?
score: 0
possible better answer: http://stackoverflow.com/a/48035240
tagged with: pandas
tagged with: datetime
has answer: http://stackoverflow.com/a/48035240
accepted answer: http://stackoverflow.com/a/48035280
has title: Pandas / Datetime, year form variable
tagged with: python

http://stackoverflow.com/comment/83133103
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48073732
has text: I tried with 3ms bouncetime, but when my sensor got triggered to TRUE, the counter count non-stop white the sensor is in TRUE state.
score: 0

http://stackoverflow.com/a/48150331
upvote count: 1
has body: The open function in Python 2.7 has a different signature and especially no keyword argument called encoding, as you can read from the error message. Eel seems to no support Python 2.7 (you should go with Python 3 anyways ;) open in Python 2.7: https://docs.python.org/2/library/functions.html#open open in Python 3.6: https://docs.python.org/3/library/functions.html#open
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48150143
type: Answer

http://stackoverflow.com/q/48133102
score: -2
has answer: http://stackoverflow.com/a/48133188
tagged with: import
has comment: http://stackoverflow.com/comment/83255472
has comment: http://stackoverflow.com/comment/83243769
has comment: http://stackoverflow.com/comment/83243441
answer count: 2
has comment: http://stackoverflow.com/comment/83243796
has comment: http://stackoverflow.com/comment/83243592
has comment: http://stackoverflow.com/comment/83243563
has comment: http://stackoverflow.com/comment/83243476
upvote count: 0
has comment: http://stackoverflow.com/comment/83243417
has title: import a function twice in Python, Flask
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83243621
has body: I would like to import a function twice in views.py of a flask project. I have a class defined in models.py and I want to use the function get_item() in that class as a class method import get_functions class Shopping_list(): ... def get(): return get_functions.get_item() but I also want to use the function get_item() outside the class as an independent function so that my views.py has the following imports import models import get_functions this does not seem to be allowed since I get an error. ImportError: cannot import name models I could define the function twice, but I would like to avoid that. Is there a way to use the functions in get_functions() twice? I notice that this seems to be a flask specific issue.
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/83243432
has comment: http://stackoverflow.com/comment/83243607
type: Question
has answer: http://stackoverflow.com/a/48133126

http://stackoverflow.com/comment/83209616
type: QuestionComment
type: Comment
has text: See the solution in this QA - https://stackoverflow.com/questions/48075864/how-to-avoid-a-socket-timeout-for-selenium-webdriver/48077973#48077973
comment on: http://stackoverflow.com/q/48115462
score: 0

http://stackoverflow.com/comment/83089208
comment on: http://stackoverflow.com/a/48031421
has text: Hi Blckknght,Thanks for clearing the doubts. Actually I got confuse when I used super functionality in the above example. And thread which you referred was correct, " the answer I think you were referring to"
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83044216
has text: my apologies for not explaining too well. For now, they are 19 which seems a nice chunk of data to be fed into NN. But I`m trying to find a good mechanism assuming those 19 would be a bigger number (eg: thousands). In that case, the chunk functionality would come handy.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48036861

http://stackoverflow.com/q/48062996
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83098782
score: 1
linked to: http://stackoverflow.com/q/29919306
favorite count: 0
has title: Assign values to columns based on conditions in a pandas dataframe
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/83098880
tagged with: python
has answer: http://stackoverflow.com/a/48063302
has comment: http://stackoverflow.com/comment/83098869
accepted answer: http://stackoverflow.com/a/48063302
answer count: 3
has comment: http://stackoverflow.com/comment/83098925
upvote count: 1
has answer: http://stackoverflow.com/a/48063056
tagged with: conditional-statements
has body: I have the below dataset: device_id A B C Current Class 1 70 35 40 C 2 45 90 34 B Now each device has a score within each class( A,B,C) and it is currently a part of a certain class. Based on the class for which it has the highest score , a class change will either be recommended or not. For example, device 1 is in class C but it's highest score is in class A and hence it's recommended class will be A. Expected output: device_id A B C Current Class Class Change Recommended 1 70 35 40 C Yes A 2 45 90 34 B No B Can someone please help me with this??
possible better answer: http://stackoverflow.com/a/48063056
has answer: http://stackoverflow.com/a/48063098

http://stackoverflow.com/comment/83109383
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48067514
type: QuestionComment
has text: A side-note: You should be passing `newline=''` to `open` when working with CSV-like stuff. And the `excel_tab` dialect is wrong here; it assumes line endings are `\r\n`, when the file is `\n` endings. Defining your own dialect based off `excel_tab` would be an easy solution, just subclass it and set the class level variable `lineterminator = '\n'`

http://stackoverflow.com/q/48058653
has comment: http://stackoverflow.com/comment/83108541
type: Question
score: 0
tagged with: python-import
has comment: http://stackoverflow.com/comment/83102073
tagged with: pypy
type: UnansweredQuestion
has body: Execute the following commands: touch sys.py touch parser.py python3 -c 'import sys; print(sys)' pypy3 -c 'import sys; print(sys)' python3 -c 'import parser; print(parser)' pypy3 -c 'import parser; print(parser)' When CPython or PyPy try to import sys, they cannot and it defaults to the builtin module sys. But some modules are different. In CPython, if you execute in another folder python3 -c 'import parser; print(parser)' you'll see the path of the module instead of (built-in), and is there is a parser.py file in the $PYTHONPATH (sys.path), it will be imported. In PyPy3, it seems that parser has the same status as sys. Is there a reference somewhere about those imports? (I know they are bad practice but I wonder why I have not seen this anywhere yet)
has comment: http://stackoverflow.com/comment/83108638
tagged with: python
has comment: http://stackoverflow.com/comment/83098801
answer count: 0
has title: How do CPython 3 and PyPy3 resolve builtin modules path?

http://stackoverflow.com/q/48063176
type: AnsweredQuestion
has body: Objective I need a reliable way to check in Python if a domain of any TLD has been registered or is available. The bold phrases are the key points that I'm struggling with. What I tried? WHOIS is the obvious way to do the check and an existing Python library like the popular python-whois was my first try. The problem is that it doesn't seem to be able to retrieve information for some of the TLDs, e.g. .run, while it works mostly fine for older ones, e.g. .com. So if python-whois is not reliable, maybe just a wrapper for the Linux's whois would be better. I tried whois library and unfortunately it supports only a limited set of TLDs, apparently to make sure it can always parse the results. As I don't really need to parse the results, I ripped the code out of the whois library and tried to do the query by calling Linux's whois myself: p = subprocess.Popen(['whois', 'example.com'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) r = p.communicate()[0] print(r.decode()) That works much better. Except it's not that reliable either. I tried one particular domain and got "Your connection limit exceeded. Please slow down and try again later." Well, it's not me who is exceeding the limit. Being behind a single IP in a huge office means that somebody else might hit the limit before I make a query. Another thought was not to use WHOIS and instead do a DNS lookup. However, I need to deal with domains that are registered or in the protected phase after expiry and don't have DNS records so this is apparently not possible. Last idea was to do the queries via an API of some 3rd party service. The problem is trust in those services as they might snatch an available domain that I check. Similar questions There are already similar questions: a stable way to check domain availability with pywhois Testing domain-name availability with pythonwhois ...but they either deal only with a limited set of TLDs or are not that bothered by reliability.
has title: How to reliably check if a domain has been registered or is available?
type: Question
answer count: 1
upvote count: 13
has answer: http://stackoverflow.com/a/48063380
accepted answer: http://stackoverflow.com/a/48063380
favorite count: 0
has comment: http://stackoverflow.com/comment/83099102
has comment: http://stackoverflow.com/comment/117651140
has comment: http://stackoverflow.com/comment/133829261
tagged with: python
has comment: http://stackoverflow.com/comment/83099220
tagged with: whois
linked to: http://stackoverflow.com/q/47418061
linked to: http://stackoverflow.com/q/11584942
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/117647917
downvote count: 0
score: 13
has comment: http://stackoverflow.com/comment/83099388

http://stackoverflow.com/comment/83283533
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48152069
has text: Running any command with `> script.py` at the end will result in any existing contents of `script.py` being overwritten/replaced. What you're showing only makes sense if `dir1/file1` is an executable that actually writes out python code to its stdout (which is redirected by the `>` into `script.py`).

http://stackoverflow.com/comment/83037555
type: QuestionComment
has text: Is 'lodgement_year' needed? Based on the sample output, it seems that cumulative sum is just based on 'words'?
score: 1
comment on: http://stackoverflow.com/q/48033351
type: Comment

http://stackoverflow.com/q/48158277
type: Question
tagged with: python
tagged with: nosql
has title: bson.errors.InvalidDocument: Cannot encode object: ec2.Image()
score: 0
tagged with: pymongo
answer count: 1
has answer: http://stackoverflow.com/a/48176162
tagged with: mongodb
accepted answer: http://stackoverflow.com/a/48176162
type: AnsweredQuestion
tagged with: mongoose
has body: When I try to insert the following document: aws_data = {u'ami_launch_index': 0, u'image': ec2.Image(id='xxx') } I get the following error: bson.errors.InvalidDocument: Cannot encode object: ec2.Image(id='xxx') MongoDB is not able to encode ec2.Image(id='ami-xxx') How do I fix it?

http://stackoverflow.com/comment/83006879
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48017454
has text: Possible duplicate of [selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH error with chrome](https://stackoverflow.com/questions/46085270/chrome-headless-browswer-selenium-python/46089751#46089751)

http://stackoverflow.com/a/48160128
answers question: http://stackoverflow.com/q/48141933
score: 0
has body: When you upload the file. It's not saved in the current folder. uploaded = files.upload() It's stored as the value in the uploaded dictionary, with the filename as key.
type: Answer

http://stackoverflow.com/comment/83236730
score: 0
type: Comment
type: QuestionComment
has text: my idea is to break period (that new user wants) to exact dates and for every date keep q-ty for every order, and later just summarize everything per date and take maximum value for one date that is between dates new user wants it
comment on: http://stackoverflow.com/q/48129540

http://stackoverflow.com/q/48125788
score: 0
tagged with: python
tagged with: dictionary
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83228524
has body: I got stuck while printing the dictionary, any help will be appreciated.. cells = pdf.extract( [('cells', 'LTTextLineHorizontal:in_bbox("%s,%s,%s,%s")' % (x,y,x1,y1))]) Above dictionary, which fetching some data using co-ordinates, result is - {'cells': [&lt;LTTextLineHorizontal&gt;]} {'cells': [&lt;LTTextLineHorizontal&gt;]} {'cells': [&lt;LTTextLineHorizontal&gt;]} The problem is while I am parsing this data and try to print then all values are not getting printed. I am doing like as follow- cells = pdf.extract( [('cells', 'LTTextLineHorizontal:in_bbox("%s,%s,%s,%s")' % (x,y,x1,y1))]) return [cell.text.encode('utf-8').strip() for cell in cells['cells']] Calling the function and printing the value here, but all value inside the list is not getting printed- it is printing only - [b'SRN : U16571275'] [b''] [b''] print(SRN) print(PMI)
has comment: http://stackoverflow.com/comment/83228595
has title: how to print all items inside dictionary if containing list
type: Question

http://stackoverflow.com/a/48142564
score: 0
has comment: http://stackoverflow.com/comment/83263365
type: Answer
has body: You can use "in", like this: data = ['Chicago', 'NYC', 'Boston', 'SD'] dictionary = {'NYC': 'New York', 'SD': 'San Diego'} new_list = [] for x in data: if x in dictionary: new_list.append(dictionary[x]) else: new_list.append(x) print(new_list) #output ['Chicago', 'New York', 'Boston', 'San Diego'] Using List comprehension data = ['Chicago', 'NYC', 'Boston', 'SD'] dictionary = {'NYC': 'New York', 'SD': 'San Diego'} new_list=[dictionary[x] if x in dictionary else x for x in data] print(new_list) ['Chicago', 'New York', 'Boston', 'San Diego']
has comment: http://stackoverflow.com/comment/83264017
has comment: http://stackoverflow.com/comment/83263447
has comment: http://stackoverflow.com/comment/83263311
upvote count: 3
has comment: http://stackoverflow.com/comment/83263992
downvote count: 3
answers question: http://stackoverflow.com/q/48142516
has comment: http://stackoverflow.com/comment/83263330
has comment: http://stackoverflow.com/comment/83263411

http://stackoverflow.com/q/48162712
tagged with: fuzzy
has answer: http://stackoverflow.com/a/63666584
score: 4
has answer: http://stackoverflow.com/a/54651501
has comment: http://stackoverflow.com/comment/83495819
tagged with: fuzzy-logic
has body: I made a traffic light prototype from raspi. My source code has given an error. The erorr said Traceback (most recent call last): File "/home/pi/testing.py", line 2, in &lt;module&gt; import skfuzzy as fuzz ImportError: No module named 'skfuzzy' I already checked that scikit-fuzzy has been installed on my raspi, but whenever i run, the source can not recognize that scikit-fuzzy tools. here is my some of source code: import numpy as np import skfuzzy as fuzz import RPi.GPIO as GPIO import time Curr_GtGB=40 Curr_GtSU=46 Curr_GtSS=26 Curr_GtK=12 GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) redGB=16 yelGB=18 grenGB=22 redSU=40 yelSU=38 grenSU=36 redSS=33 yelSS=35 grenSS=37 redK=11 yelK=13 grenK=15 GPIO.setup(redGB, GPIO.OUT) GPIO.setup(yelGB, GPIO.OUT) GPIO.setup(grenGB, GPIO.OUT) GPIO.setup(redSU, GPIO.OUT) GPIO.setup(yelSU, GPIO.OUT) GPIO.setup(grenSU, GPIO.OUT) GPIO.setup(redSS, GPIO.OUT) GPIO.setup(yelSS, GPIO.OUT) GPIO.setup(grenSS, GPIO.OUT) GPIO.setup(redK, GPIO.OUT) GPIO.setup(yelK, GPIO.OUT) GPIO.setup(grenK, GPIO.OUT)
answer count: 3
tagged with: raspberry-pi
favorite count: 0
has comment: http://stackoverflow.com/comment/83421804
tagged with: python
upvote count: 4
downvote count: 0
type: UnansweredQuestion
has title: skfuzzy can not be recognized
has answer: http://stackoverflow.com/a/50371602
type: Question

http://stackoverflow.com/q/48113927
has body: My structure (massively simplified) is depicted below: import multiprocessing def creator(): # creates files return def relocator(): # moves created files return create = multiprocessing.Process(target=creator) relocate = multiprocessing.Process(target=relocator) create.start() relocate.start() What I am trying to do is have a bunch of files created by creator and as soon as they get created have them moved to another directory by relocator. The reason I want to use multiprocessing here is: I do not want creator to wait for the moving to be finished first because moving takes time I dont want to waste. Creating all the files first before starting to copy is not an option either because there is not enough space in the drive for all of them. I want both the creator and relocator processes to be serial (one file at a time each) but run in parallel. A "log" of the actions should lool like this: # creating file 1 # creating file 2 and relocating file 1 # creating file 3 and relocating file 2 # ... # relocating last file Based on what I have read, Queue is the way to go here. Strategy: (maybe not the best one?!) After an file gets created it will be entering the queue and after it has finished being relocated, it will be removed from the queue. I am however having issues coding it; multiple files being created at the same time (multiple instances of creator running in parallel) and others... I would be very grateful for any ideas, hints, explanations, etc
answer count: 1
has answer: http://stackoverflow.com/a/48114263
has comment: http://stackoverflow.com/comment/83204107
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83203838
has comment: http://stackoverflow.com/comment/83203868
tagged with: python
tagged with: parallel-processing
has comment: http://stackoverflow.com/comment/83204284
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Struggling with multiprocessing Queue
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/83203962
accepted answer: http://stackoverflow.com/a/48114263
has comment: http://stackoverflow.com/comment/83203781
upvote count: 2

http://stackoverflow.com/q/48100159
type: AnsweredQuestion
downvote count: 2
upvote count: 1
type: Question
has body: Suppose I have a tab-delineated .txt file like this: And I want to collapse columns 1-5 so that for a given unique combination (i.e.: a-b-c-d-e), all of the values associated with that unique combination (column 6; in this case for the combination a-b-c-d-e, the associated values are f,g,h) are displayed while that unique combination is only displayed once. Here's what I'm trying to accomplish : What would the python script look like to accomplish this (if possible)?
has comment: http://stackoverflow.com/comment/83175532
score: -1
has answer: http://stackoverflow.com/a/48100353
has title: How to collapse similar values in tab-delineated .txt file?
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/48100353
has comment: http://stackoverflow.com/comment/83175631
answer count: 1
tagged with: grouping
has comment: http://stackoverflow.com/comment/83175395
favorite count: 0
has comment: http://stackoverflow.com/comment/83175566
tagged with: python

http://stackoverflow.com/a/48052579
upvote count: 17
type: Answer
has comment: http://stackoverflow.com/comment/83078802
downvote count: 0
has body: Consider using read_csv() args, index_col and parse_dates, to create indices during import and format as datetime. Then run your needed horizontal merge. Below assumes date is in first column of csv. And at the end use sort_index() on final dataframe to sort the datetimes. df1 = pd.read_csv(r"E:\Business\Economic Indicators\Consumer Price Index - Core (YoY) - European Monetary Union.csv", index_col=[0], parse_dates=[0]) df2 = pd.read_csv(r"E:\Business\Economic Indicators\Private loans (YoY) - European Monetary Union.csv", index_col=[0], parse_dates=[0]) df3 = pd.read_csv(r"E:\Business\Economic Indicators\Current Account s.a - European Monetary Union.csv", index_col=[0], parse_dates=[0]) finaldf = pd.concat([df1, df2, df3], axis=1, join='inner').sort_index() And for DRY-er approach especially across the hundreds of csv files, use a list comprehension import os ... os.chdir('E:\\Business\\Economic Indicators') dfs = [pd.read_csv(f, index_col=[0], parse_dates=[0]) for f in os.listdir(os.getcwd()) if f.endswith('csv')] finaldf = pd.concat(dfs, axis=1, join='inner').sort_index()
accepted answer of: http://stackoverflow.com/q/48051100
answers question: http://stackoverflow.com/q/48051100
has comment: http://stackoverflow.com/comment/83081866
score: 17
type: AcceptedAnswer

parallel.for
tag name: parallel.for
tags question: http://stackoverflow.com/q/48068584
type: Tag

ruamel.yaml
tags question: http://stackoverflow.com/q/48029461
type: Tag
tag name: ruamel.yaml
tags question: http://stackoverflow.com/q/48017317

http://stackoverflow.com/comment/83228303
score: 0
type: AnswerComment
has text: Do you mean I should use instead of "I click on 'search_button' on homepage and I click on 'search_button' on property" instead of "I click on 'search_button'?(it is other step) But is it not hardcode?
comment on: http://stackoverflow.com/a/48119458
type: Comment

http://stackoverflow.com/a/48156276
has body: It's protected by CloudFlare which is denying a pure GET request to that URL. You need a non-headless browser in order to access the page, otherwise it will reject it. Use a library such as Selenium that provides a GUI and you should be fine. from selenium import webdriver browser = webdriver.Firefox() # or whichever browser you prefer browser.get('https://hacked.com/wp-login.php') Note that there is no way to fetch a status code with Selenium. However, you have many more ways to interact with the page, and confirm that you have reached the page.
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48155877
upvote count: 2
has comment: http://stackoverflow.com/comment/83291664
has comment: http://stackoverflow.com/comment/83291634

http://stackoverflow.com/comment/83105264
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48064934
has text: BTW: there is rule/suggestion to use `CamelCaseNames` for classes - ie. `Button` instead `button` - it helps to recognize classes in code. Even Stackoverflow knows this rule and use light blue color for classes. More: [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/)
score: 0

http://stackoverflow.com/q/48145150
has answer: http://stackoverflow.com/a/48147592
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python
tagged with: conv-neural-network
has body: I want to predict 8-characters license plates, so I wrote the below model in Keras: x = Input(shape=(HEIGHT, WIDTH, CHANNELS)) base_model = InceptionV3(include_top=False, weights='imagenet', input_shape=(HEIGHT, WIDTH, CHANNELS)) base_model.trainable = False y = base_model(x) y = Reshape((8, 9 * 256))(y) y = LSTM(units=20, return_sequences='true')(y) y = Dropout(0.5)(y) y = TimeDistributed(Dense(TOTAL_CHARS, activation="softmax", activity_regularizer=regularizers.l2(REGUL_PARAM)))(y) y = Dropout(0.25)(y) model = Model(input=x, output=y) model.compile(loss="categorical_crossentropy", optimizer='rmsprop', metrics=['accuracy']) I have about 6000 data for training which I augment them with ImageGenerator. My problem is that the loss and accuracy are approximately constant during time: ************************************************************ Epoch: 1 ************************************************************ Train on 6869 samples, validate on 1718 samples Epoch 1/1 6856/6869 [============================&gt;.] - ETA: 0s - loss: 5.4525 - acc: 0.1924Epoch 00001: val_loss improved from 2.17175 to 2.15020, saving model to ./trained_model_V10.hdf5 6869/6869 [==============================] - 25s 4ms/step - loss: 5.4535 - acc: 0.1924 - val_loss: 2.1502 - val_acc: 0.2232 ************************************************************ Epoch: 2 ************************************************************ Train on 6869 samples, validate on 1718 samples Epoch 1/1 6848/6869 [============================&gt;.] - ETA: 0s - loss: 5.4543 - acc: 0.1959Epoch 00001: val_loss improved from 2.15020 to 2.11809, saving model to ./trained_model_V10.hdf5 6869/6869 [==============================] - 26s 4ms/step - loss: 5.4537 - acc: 0.1958 - val_loss: 2.1181 - val_acc: 0.2281 ************************************************************ Epoch: 3 ************************************************************ Train on 6869 samples, validate on 1718 samples Epoch 1/1 6856/6869 [====================…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83280139
upvote count: 1
type: Question
score: 1
has title: Issue with Combining LSTM and CNN? (Python, Keras)
tagged with: lstm
has comment: http://stackoverflow.com/comment/83302870

http://stackoverflow.com/comment/83241286
type: QuestionComment
comment on: http://stackoverflow.com/q/48131876
has text: You indicated you know about this similar question but it didn't help https://stackoverflow.com/questions/11491268/install-pycairo-in-virtualenv
score: 0
type: Comment

http://stackoverflow.com/q/48040762
possible better answer: http://stackoverflow.com/a/48040812
has answer: http://stackoverflow.com/a/48040812
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48040799
score: 1
has answer: http://stackoverflow.com/a/48040792
linked to: http://stackoverflow.com/q/19389490
type: Question
has comment: http://stackoverflow.com/comment/83051893
tagged with: for-loop
has comment: http://stackoverflow.com/comment/83059932
has body: def checker(a_list): for item in a_list: if str(item).isdigit(): return True else: return False The variable I have for checker is a list of four string containing variables. I planned to use it as a 'checker' to see if all input values of another function contained only digits. Problem: If the first item in a_list is not a number, checker returns False as it should. However, if the first item is a number while any others in the list aren't, checker returns True anyways. This causes the next function to proceed with the non-number variables and results in an error. How do I make it so my function checks the entire list before returning True? Or if need be, how do I make a new function that does what I'm looking for? Thanks
downvote count: 0
has answer: http://stackoverflow.com/a/48040848
accepted answer: http://stackoverflow.com/a/48040799
answer count: 4
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83051873
has comment: http://stackoverflow.com/comment/83051891
has title: Python for loop returns True after first item
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/83213393
has text: I did try set.union before but wasnt getting the answer. Apparently i was missing the * in it. Thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48118386
score: 0

http://stackoverflow.com/q/48079982
has comment: http://stackoverflow.com/comment/83134599
favorite count: 0
has comment: http://stackoverflow.com/comment/83134045
has comment: http://stackoverflow.com/comment/83134166
has comment: http://stackoverflow.com/comment/83133958
tagged with: python
has comment: http://stackoverflow.com/comment/83134436
has comment: http://stackoverflow.com/comment/83154865
tagged with: tkinter
type: UnansweredQuestion
downvote count: 3
upvote count: 1
has title: Passing value of Entry in button function
has comment: http://stackoverflow.com/comment/83133980
has answer: http://stackoverflow.com/a/48085985
has body: How to pass value of Entry in button function ? I want to pass value to a function onConfirm() from tkinter import Tk, ttk, Frame, Button, Label, Entry, Text, Checkbutton, \ Scale, Listbox, Menu, BOTH, RIGHT, RAISED, N, E, S, W, \ HORIZONTAL, END, FALSE, IntVar, StringVar, messagebox as box class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="skyblue") self.parent = parent self.parent.title("Simple Window") self.style = ttk.Style() self.style.theme_use("default") self.centreWindow() self.pack(fill=BOTH, expand=1) firstNameLabel = Label(self, text="First Name") firstNameLabel.grid(row=0, column=0, padx=(100,10), pady=(100,10)) firstNameText = Entry(self, width=20) firstNameText.grid(row=0, column=1, pady=(100,10)) okBtn = Button(self, text="OK", width=10, command= lambda: self.onConfirm(firstNameText.get())) okBtn.grid(row=0, column=2,padx = 5, pady=(100,10)) # closeBtn = Button(self, text="Close", width=10, command=self.onExit) #closeBtn.grid(row=4, column=3, padx=5, pady=3, sticky=W+E) def centreWindow(self): w = 500 h = 300 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w)/2 y = (sh - h)/2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y)) def onConfirm(self,s): box.showinfo("Information", s) def main(): root = Tk() #root.geometry("250x150+300+300") # width x height + x + y # we will use centreWindow instead root.resizable(width=FALSE, height=FALSE) # .. not resizable app = Example(root) root.mainloop() if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/83140010
has comment: http://stackoverflow.com/comment/83141388
type: Question
has comment: http://stackoverflow.com/comment/83141509
score: -2
answer count: 1

http://stackoverflow.com/q/48030230
has comment: http://stackoverflow.com/comment/83042482
tagged with: python
tagged with: kivy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83030652
tagged with: python-imaging-library
tagged with: fonts
has body: I am building a kivy app and need to include a font chooser. Since I cannot find one for kivy, I am building my own. But I cannot find a way to tell if a font is usable for me (i.e., can I use it to make a sentence as opposed to a string of symbols). I am using the Pillow ImageFont. Is there any way to descriminate between symbol and text fonts in python?
type: Question
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/48035728
has answer: http://stackoverflow.com/a/48045349
downvote count: 0
has comment: http://stackoverflow.com/comment/83030670
score: 4
possible better answer: http://stackoverflow.com/a/48035728
has comment: http://stackoverflow.com/comment/83064343
has comment: http://stackoverflow.com/comment/83030662
has title: How to Determine if a Font is a symbol font or a text font
favorite count: 0
accepted answer: http://stackoverflow.com/a/48045349

http://stackoverflow.com/a/48029895
type: Answer
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/48020122
has comment: http://stackoverflow.com/comment/83331714
has body: The code below steps continuously through my array of points with a given step size and window of 200 instead of discretely binning every 200. stepsize=10 NewArray=np.ravel(Array) NewArray.reshape(2000*200,3) plt.ion() fig, ax = plt.subplots() norm = plt.normalize(NewArray[:,2].min(), NewArray[:,2].max()) sc = ax.scatter(NewArray[0:200,0], NewArray[0:200,1], c=NewArray[0:200,2], cmap=cm.jet, s=5) plt.xlim(-40,40) plt.ylim(0,200) plt.draw() for i in range(len(NewArray//stepsize)-200): sc.set_offsets(np.c_[NewArray[(i*stepsize):(i*stepsize)+200,0],\ NewArray[(i*stepsize):(i*stepsize)+200,1]]) sc.set_array(NewArray[(i*stepsize):(i*stepsize)+200,2]) plt.pause(0.1) plt.ioff() plt.show()
answers question: http://stackoverflow.com/q/48020122

http://stackoverflow.com/comment/104957443
has text: Okay, so which one is recommended?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48171935
type: Comment

http://stackoverflow.com/comment/83107751
type: QuestionComment
has text: I dont see a question nor an error description ...
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48067200

http://stackoverflow.com/a/60219265
answers question: http://stackoverflow.com/q/48145992
upvote count: 3
type: Answer
has body: Here's a case valid for when the JSONField is set for readonly # set 'url' editable=False in model defintion class BodyHeightAdmin(admin.ModelAdmin): search_fields = ('name', ) list_display = ('id', 'name', 'key', 'get_pprint_url', ) list_display_links = ('id', 'name', 'key', ) readonly_fields = ('get_pprint_url', ) def url(self, instance): data = json.loads(instance.data) return data["url"] actions = [ 'process_webhook_events', 'reset_webhook_events' ] def get_pprint_url(self, obj=None): result = '' if obj and obj.url: result = json.dumps(obj.url, indent=4, sort_keys=True) # keep spaces result_str = f'&lt;pre&gt;{result}&lt;/pre&gt;' result = mark_safe(result_str) return result get_pprint_url.short_description = 'url'
score: 3
downvote count: 0

http://stackoverflow.com/comment/83300259
has text: @GarbageCollector: `I` in `str(I + key)` could be almost anything; they `eval`-ed the result of `input`, and didn't give us example inputs, expected outputs, and observed outputs (the minimum for a [MCVE]). By the time they hit `str(I - key)`, `I` is definitely a single character from a `str`, so it's a `str` itself.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48160319

http://stackoverflow.com/a/48033301
accepted answer of: http://stackoverflow.com/q/48017705
score: 0
answers question: http://stackoverflow.com/q/48017705
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83158432
type: Answer
has body: Regarding your code partner = { 'name': name, 'cv': cv, } calling remote ORM create method to create a record partner_id = sock.execute(dbname, uid, pwd, 'res.partner', 'create', partner) If 'cv' field is text and it had data, than sure it will works. Make sure your assignemnt variable had right data first. Try: partner = { 'name': 'SnippetBucket.com', 'cv': 'ERP Business Solution...', } partner_id = sock.execute(dbname, uid, pwd, 'res.partner', 'create', partner) As this workes,sure your cv data once filled, all works.

http://stackoverflow.com/comment/83519617
comment on: http://stackoverflow.com/a/48107035
score: 0
type: AnswerComment
has text: No. x.name in this case is referring to the usedate we are building in the dataframe. So when you apply with axis=1. Each row is passed in as a series, the series index are the column headers from the dataframe and the name of the series is the row index of that dataframe.
type: Comment

http://stackoverflow.com/comment/83324008
has text: what would be a more flexible way of doing this?
comment on: http://stackoverflow.com/a/48158961
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83166622
has text: it made it too complicated - you sould use only one `for event in pygame.event.get():` and one `if event.type == pygame.MOUSEBUTTONDOWN:` and this can be main mistake. because you click is checked only with first rectangle.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48095037

http://stackoverflow.com/q/48141933
has comment: http://stackoverflow.com/comment/83262990
answer count: 1
tagged with: google-colaboratory
has comment: http://stackoverflow.com/comment/83262377
has answer: http://stackoverflow.com/a/48160128
score: 0
has comment: http://stackoverflow.com/comment/83262984
has title: How to access csv file in the root folder of the Google Colaboratory?
linked to: http://stackoverflow.com/q/47744131
tagged with: pandas
tagged with: python
has body: I am trying to access a CSV file uploaded right in the same folder that my python notebook is from the colaboratory. when I simply do : pd.read_csv("train.csv") It throws me : "File b'train.csv' does not exist" error. Any idea is highly appreciated.
type: UnansweredQuestion
type: Question

http://stackoverflow.com/comment/83292307
score: 0
has text: That's interesting @jasonharper, I assumed that since it was a different thread, the result wouldn't write over each other.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48156384

http://stackoverflow.com/q/48068739
has body: I have a Python 2.7 program which must create a symbolic link with a modification date in the past. I can create the link with os.symlink(), and os.utime() claims to set the access time and modification time of files, but when I use os.utime() on my newly-created symlink, it changes the atime and mtime of the file to which the symlink points, rather than the atime and mtime of the symbolic link. What is the best way to set the access time and modification time of a symbolic link from Python code? Here is a test program which demonstrates what I am doing: #!/usr/bin/env python2.7 import os, datetime, time if __name__ == '__main__': path1, path2 = 'source', 'link' if os.path.exists(path1): os.rmdir(path1) os.mkdir(path1) if os.path.lexists(path2): os.remove(path2) os.symlink(path1, 'link') lstat1, lstat2 = os.lstat(path1), os.lstat(path2) print("Before: {path1} atime {sa}, mtime {sm}, {path2} atime {la}, mtime {lm}".format( path1=path1, path2=path2, sa=lstat1.st_atime, sm=lstat1.st_mtime, la=lstat2.st_atime, lm=lstat2.st_mtime)) long_ago = datetime.datetime(datetime.date.today().year - 1,1,1,00,00,00) long_ago_posix = time.mktime(long_ago.timetuple()) print("Desired: {path1} unchanged, {path2} atime {m}, mtime {m}".format( path1=path1, path2=path2, m=long_ago_posix)) os.utime(path2, (long_ago_posix, long_ago_posix)) lstat1, lstat2 = os.lstat(path1), os.lstat(path2) print("After: {path1} atime {sa}, mtime {sm}, {path2} atime {la}, mtime {lm}".format( path1=path1, path2=path2, sa=lstat1.st_atime, sm=lstat1.st_mtime, la=lstat2.st_atime, lm=lstat2.st_mtime)) This is the misbehaviour I see. The "After:" times change for "source" and not for "link", but the reverse should happen: % ../src/utime_symlink_test.py Before: source atime 1514931280.0, mtime 1514931280.0, link atime 1514931280.0, mtime 1514931280.0 Desired: source unchanged, link atime 1483257600.0, mtime 1483257600.0 After: source atime 1483257600.0, mtime 1483257600.0, link atime 1514931280.0, mtime 1514931280.0 …
tagged with: python
upvote count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48068849
downvote count: 0
possible better answer: http://stackoverflow.com/a/48068849
type: Question
has answer: http://stackoverflow.com/a/48072560
accepted answer: http://stackoverflow.com/a/48072560
tagged with: filesystems
answer count: 2
score: 4
tagged with: python-2.7
tagged with: symlink
favorite count: 0
has comment: http://stackoverflow.com/comment/83111117
has title: How can I change atime and mtime of a symbolic link from Python?

http://stackoverflow.com/q/48164206
has answer: http://stackoverflow.com/a/55994475
has title: PySpark - Adding a Column from a list of values
tagged with: python
score: 18
linked to: http://stackoverflow.com/q/48209667
type: AnsweredQuestion
upvote count: 19
tagged with: list
has answer: http://stackoverflow.com/a/71746420
downvote count: 1
has body: I have to add column to a PySpark dataframe based on a list of values. a= spark.createDataFrame([("Dog", "Cat"), ("Cat", "Dog"), ("Mouse", "Cat")],["Animal", "Enemy"]) I have a list called rating, which is a rating of each pet. rating = [5,4,1] I need to append the dataframe with a column called Rating, such that +------+-----+------+ |Animal|Enemy|Rating| +------+-----+------+ | Dog| Cat| 5| | Cat| Dog| 4| | Mouse| Cat| 1| +------+-----+------+ I have done the following however it is returning only the first value in the list in the Rating Column def add_labels(): return rating.pop(0) labels_udf = udf(add_labels, IntegerType()) new_df = a.withColumn('Rating', labels_udf()).cache() out: +------+-----+------+ |Animal|Enemy|Rating| +------+-----+------+ | Dog| Cat| 5| | Cat| Dog| 5| | Mouse| Cat| 5| +------+-----+------+
type: Question
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/69739650
tagged with: pyspark
has answer: http://stackoverflow.com/a/48165635
has answer: http://stackoverflow.com/a/48174607
tagged with: apache-spark
has answer: http://stackoverflow.com/a/48164615
has answer: http://stackoverflow.com/a/48173561
answer count: 7
possible better answer: http://stackoverflow.com/a/48165635
accepted answer: http://stackoverflow.com/a/48174607
favorite count: 0

http://stackoverflow.com/comment/83171783
has text: ı try run the code because your code dont work. TRACEBACK predicted_img1 = predict_face(test_img1) draw_text(img, label, x, y - 5) # draw the predicted label on top of the box cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 0, 255), 2) TypeError: bad argument type for built-in operation Why ?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48093667
type: Comment

http://stackoverflow.com/comment/83095640
has text: Try adding `SET NOCOUNT ON; ` to the beginning of your SQL string.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48061304
score: 6

http://stackoverflow.com/comment/83105658
has text: I upvoted his answer too. I'll keep yours as the accepted answer as you've been following through with me since yesterday. :)
type: Comment
comment on: http://stackoverflow.com/a/48055805
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83404977
type: QuestionComment
comment on: http://stackoverflow.com/q/48060738
score: 0
has text: @ChiefVOLDEMORT The linked answer has an algorithm — expressed as a Java class. IMHO that code should be fairly ”readable” for someone with JavaScript and Python knowledge.
type: Comment

http://stackoverflow.com/a/48102330
type: Answer
has body: This is generally speaking not how functions work at all (there are certain exceptions, but nothing remotely resembling your case). What would achieve your wish would be one function which prints result based on argument passed to it. Like this: def keyword(a): if a == 0: print("what is the boss") elif a == 1: print("who is the boss") elif a == 2: print("where is the boss") The rest of the code can be the same, except you don't need the setting of a, b, c variables at all.
answers question: http://stackoverflow.com/q/48102109
score: 0

http://stackoverflow.com/comment/83198768
comment on: http://stackoverflow.com/a/48111334
type: AnswerComment
score: 0
type: Comment
has text: Can you explain what a meta class is? Im just getting back into python after being in Java for a bit.

http://stackoverflow.com/q/48038126
has comment: http://stackoverflow.com/comment/83047437
has comment: http://stackoverflow.com/comment/83046636
has comment: http://stackoverflow.com/comment/83046698
tagged with: django-templates
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83046580
tagged with: django
has answer: http://stackoverflow.com/a/68839258
upvote count: 1
has comment: http://stackoverflow.com/comment/83046572
has title: Variables and attributes may not begin with underscores in django template
has comment: http://stackoverflow.com/comment/85808369
tagged with: django-template-filters
type: Question
has body: Creating a private filter works fine for this case: but for this case it doesn't work: {% url 'value.show' value|private='_id' %} Is there any way around this problem? Filter example: Django Templates and MongoDB _id I am using couchdb with mongo query. TemplateSyntaxError Variables and attributes may not begin with underscores: 'value._id' Request Method: GET Exception Type: TemplateSyntaxError Exception Value: Variables and attributes may not begin with underscores: 'value._id' Python Version: 3.6.4
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83046542
favorite count: 0
has comment: http://stackoverflow.com/comment/85517457
linked to: http://stackoverflow.com/q/24936601
tagged with: python
has comment: http://stackoverflow.com/comment/83046685
score: 1

http://stackoverflow.com/q/48112817
linked to: http://stackoverflow.com/q/4186062
tagged with: sqlite
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48113097
favorite count: 0
accepted answer: http://stackoverflow.com/a/48113097
upvote count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83201130
has title: How to sort results by descending order in SQLAlchemy?
score: -1
duplicate of: http://stackoverflow.com/q/4186062
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/83201656
type: Question
has comment: http://stackoverflow.com/comment/83201466
has body: I have a table called recentOrders and I want to return the row which has the highest value (basically the latest order number) from the column OrderID. I can return a single seemingly random row with: s = recentOrders.select() rs = s.execute() row = rs.fetchone() print(row) and I've tried various things along the lines of: s = recentOrders.select().order_by(OrderID.desc()) rs = s.execute() row = rs.fetchone() print(row) But I get an error of NameError: name 'OrderID' is not defined What's the correct syntax for a query?

http://stackoverflow.com/q/48055971
upvote count: 6
accepted answer: http://stackoverflow.com/a/48095892
has answer: http://stackoverflow.com/a/48070911
tagged with: python
tagged with: vectorization
downvote count: 1
has comment: http://stackoverflow.com/comment/83084205
type: AnsweredQuestion
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83087650
has title: Vectorization to achieve performance
score: 5
has comment: http://stackoverflow.com/comment/83084717
has answer: http://stackoverflow.com/a/48095892
tagged with: arrays
has answer: http://stackoverflow.com/a/48070666
favorite count: 0
has comment: http://stackoverflow.com/comment/83084240
answer count: 3
has body: I want to avoid using for loop in the following code to achieve performance. Is vectorization suitable for this kind of problem? a = np.array([[0,1,2,3,4], [5,6,7,8,9], [0,1,2,3,4], [5,6,7,8,9], [0,1,2,3,4]],dtype= np.float32) temp_a = np.copy(a) for i in range(1,a.shape[0]-1): for j in range(1,a.shape[1]-1): if a[i,j] &gt; 3: temp_a[i+1,j] += a[i,j] / 5. temp_a[i-1,j] += a[i,j] / 5. temp_a[i,j+1] += a[i,j] / 5. temp_a[i,j-1] += a[i,j] / 5. temp_a[i,j] -= a[i,j] * 4. / 5. a = np.copy(temp_a)
possible better answer: http://stackoverflow.com/a/48070666
has comment: http://stackoverflow.com/comment/83084258

http://stackoverflow.com/comment/83043202
type: Comment
has text: Since you have only one na_value, let's try without the square brackets making it a list.
type: AnswerComment
comment on: http://stackoverflow.com/a/48036388
score: 0

http://stackoverflow.com/comment/83119053
type: Comment
has text: You may want to check this out: https://wiki.python.org/moin/TupleSyntax . It is building a tuple on the right hand side, then assigning it to the left hand side.
comment on: http://stackoverflow.com/a/48072164
score: 0
type: AnswerComment

http://stackoverflow.com/q/48052806
favorite count: 0
has answer: http://stackoverflow.com/a/48053312
tagged with: python
has body: I have the following server: import os import asyncio import websockets class Server: def get_port(self): return os.getenv('WS_PORT', '8765') def get_host(self): return os.getenv('WS_HOST', 'localhost') def start(self): return websockets.serve(self.handler, self.get_host(), self.get_port()) async def handler(self, websocket, path): while True: async for message in websocket: await websocket.send(message) and the client: import asyncio import websockets async def msg(): async with websockets.connect('ws://localhost:8765') as websocket: await websocket.send('test message') asyncio.get_event_loop().run_until_complete(msg()) When I execute asyncio.get_event_loop().run_until_complete(msg()) I receive the following error: websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1000 (OK), no reason Also app.py code: #!/usr/bin/env python3.6 import asyncio from server import Server if __name__ == '__main__': ws = Server() asyncio.get_event_loop().run_until_complete(ws.start()) asyncio.get_event_loop().run_forever() P.S. Added while True to handler as suggested in the comment below. But I still receive that error
type: Question
type: AnsweredQuestion
upvote count: 9
score: 9
answer count: 1
tagged with: websocket
accepted answer: http://stackoverflow.com/a/48053312
downvote count: 0
has title: Why do I receive "WebSocket connection is closed: code = 1000 (OK), no reason"

http://stackoverflow.com/comment/83292770
comment on: http://stackoverflow.com/q/48156384
score: 0
has text: Do you get output from the other two print statements inside the `if __name__ == '__main__'` block?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83193725
score: 0
comment on: http://stackoverflow.com/q/48098432
type: Comment
type: QuestionComment
has text: Ok. So as far as I can see, these are juste work around, there is not way to support uuid in sqlalchemy (by default)

http://stackoverflow.com/comment/83044446
score: 0
type: QuestionComment
type: Comment
has text: I would suggest you look at some Python tutorials.
comment on: http://stackoverflow.com/q/48037051

http://stackoverflow.com/comment/83252899
score: 0
type: Comment
has text: Anyway, can you also please suggest how can I increase the column width, so that I can see 321000000 instead of 3.2100000e+08??
comment on: http://stackoverflow.com/a/48137743
type: AnswerComment

http://stackoverflow.com/a/61555952
downvote count: 0
answers question: http://stackoverflow.com/q/48016091
has body: Simply untar this file from here - github - lambda_packages/pyodbc. This has .so files in it. Now package your python code and the .so files together and upload to AWS lambda. The folder structure for your reference should look like this. lambda_function.py libodbc.so.2 pyodbc.so &lt;name_this_zip&gt;.zip No subfolders exist Edit: Created a lambda layer and saved it for reuse. Get it here - https://github.com/kuharan/Lambda-Layers
type: Answer
has comment: http://stackoverflow.com/comment/129320926
score: 5
upvote count: 5

http://stackoverflow.com/q/48161132
tagged with: combinations
type: AnsweredQuestion
tagged with: python-itertools
has body: I am using python and trying to filter a 2d array to only include arrays with a certain sum and that don't include the element 0. Other tutorials seem to show how to filter arrays to get certain elements that meet a condition using numpy.where for instance, but I am trying to only get certain arrays that meet a condition without using loops of course, but rather a numpy method. Like this operation, but with arrays and numpy: import itertools list_o_tuples = list(filter(lambda x: sum(x)==10 and 0 not in x, itertools.combinations(range(10),3))) #returns [(1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)]
accepted answer: http://stackoverflow.com/a/48161161
tagged with: numpy
answer count: 1
tagged with: arrays
downvote count: 0
favorite count: 0
has title: Filtering numpy using array operations
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/48161161
upvote count: 1
type: Question

http://stackoverflow.com/comment/83260264
type: QuestionComment
type: Comment
score: 0
has text: Hi, I thought about that. it would have been my ugly back up solution. I fixed this with an R wrapper which does not include any single quotes. This wrapper calls the final complicated script once in the R world. In the python world, I used a combination of triple quotes, single and double quotes to eliminate all conflicts. I wish there is a better way.
comment on: http://stackoverflow.com/q/48133683

http://stackoverflow.com/q/48015770
type: Question
linked to: http://stackoverflow.com/q/42622815
score: 1
has answer: http://stackoverflow.com/a/48015895
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/48016479
downvote count: 0
has answer: http://stackoverflow.com/a/48016479
favorite count: 0
accepted answer: http://stackoverflow.com/a/48015895
tagged with: python
has title: Indexing tensor in tensorflow using a tensor of integers
type: AnsweredQuestion
has body: My question is similar to the one here but not exactly the same. I have two tensors mu: (shape=(1000,1), dtype=np.float32) p : (shape=(100,30), dtype=np.int64) What I want is to create a new tensor x : (shape=(100,30), dtype=np.float32) such that x[i,j] = mu[p[i,j]] This can be done in numpy using advanced indexing x = mu[p] I have tried using the tf.gather_nd(mu, p) command but in my case I receive the following error *** ValueError: indices.shape[-1] must be &lt;= params.rank, but saw indices shape: [100,30] and params shape: [1000] for 'GatherNd_2' (op: 'GatherNd') with input shapes: [1000], [100,30]. It therefore seems in order to use this, I have to build a new tensor of coordinates. Is there a more simple way to accomplish what I want?
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/83066479
has text: @VivekKumar exactly
type: QuestionComment
comment on: http://stackoverflow.com/q/48034035
score: 0
type: Comment

http://stackoverflow.com/comment/83061689
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48042659
has text: For fun I replaced you optimization code/model with an equivalent in Keras. Using SDG optimization and a batch size of 50,000 as you are, it didn't optimize (at least not in a reasonable time). If I switched the batch size to 128 it optimized in a hundred epochs or so. If I switched the optimizer to RMSProp (128 batch) it was optimized reasonably well after the first epoch. You may not have a powerful enough optimization algorithm to deal with the data. If you have to do it this way I'd try a smaller batch size and a LOT of iterations.

http://stackoverflow.com/a/48136809
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48136266
type: Answer
answers question: http://stackoverflow.com/q/48136266
has body: Try this. The change of id number should not affect your result: from bs4 import BeautifulSoup import requests url = 'http://www.thehindu.com/opinion/op-ed/Does-Beijing-really-want-to-ldquobreak-uprdquo-India/article16875298.ece' page = requests.get(url) soup = BeautifulSoup(page.content, 'lxml') for content in soup.select("[id^='content-body-'] p"): print(content.text)
score: 0

http://stackoverflow.com/comment/83187503
has text: change the tick to 15
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48098403

http://stackoverflow.com/comment/83127210
comment on: http://stackoverflow.com/q/48076276
score: 0
type: Comment
type: QuestionComment
has text: At this point of my code I expect dataframes with datetime index. They should can contain one or many rowes and zero or many columns. And I guess it makes sense in probably most cases that one row is a series, but as a series has no orientation I don't know how to cast this to the right format. But what I found most unexpected, is this resulting in Key error: df.loc[["2015-10-01 02:00:00"],:]

http://stackoverflow.com/q/48151497
score: 0
answer count: 2
tagged with: pandas
tagged with: python
has title: Pandas Dataframe Faster Approach
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47152691
possible better answer: http://stackoverflow.com/a/48151724
type: Question
has answer: http://stackoverflow.com/a/48151724
has answer: http://stackoverflow.com/a/48151656
accepted answer: http://stackoverflow.com/a/48151656
tagged with: dataframe
has body: I have a section of my code which needs to take the values from one dataframe, and apply it to another. So for example lets say 1 data frame is the scores of students dataframe, and the 2nd is the combination of students dataframe. I want to go through each combination_DF, get the students scores and then sum them up for that row. print scores_DF Name Value Dennis 39.66 James 45.38 Leo 40.63 Joe 20.10 etc... print combination_DF name1 name2 name3 Dennis James Leo Leo Joe Dennis right now my program is looping through each combination_DF, finding the score for each name and adding it a column which will consist of the total score for each combination, which is really slowing down my program cause I work with thousands of entries. So it looks something like this.... for index,row in combination_df.iterrows(): value0 = scores_df[scores_df['Name'] == row[0]] value1 = scores_df[scores_df['Name'] == row[1]] value3 = scores_df[scores_df['Name'] == row[2]] total_score = value0['Value'].values + value1['Value'].values+ value2['Value'].values I'm new to Pandas and at the time it was the only way I knew how, but as my program has evolved this area of code needs to work faster if possible, Thanks.

http://stackoverflow.com/q/48039730
tagged with: closures
has comment: http://stackoverflow.com/comment/83151278
has comment: http://stackoverflow.com/comment/83300510
upvote count: 2
has body: Edit: Why are people downvoting this post? Are Python developers really this inept? It's a legitimate question, not one that's been answered in other places. I searched for a solution. I'm not an idiot. One parameter has a value and the other one is undefined, but if you actually read the post, you will see that both of them appear to be equally scoped. First of all, I assure you that this question is unlike other questions involving the error message: UnboundLocalError: local variable referenced before assignment closure method As I'm looking at this code, it appears that the parameter, uuidString, of the top-level method, getStockDataSaverFactory, should actually be in-scope when the method returns its inner method, saveData, as a first-class function object... because to my amazement, the parameter tickerName IS in-scope and does have the value 'GOOG' when the saveData() method is called (e.g. by the test method testDataProcessing_getSaverMethodFactory), so we can actually see that it has an actual value when the method, getDataMethodFactory(..) is called, unlike uuidString. To make the matter more obvious, I added the lines: localUuidString = uuidString and experimentUuidString = localUuidString to show that the parameter uuidString has an available value when the method is inspected by a breakpoint. def getStockDataSaverFactory(self, tickerName, uuidString, methodToGetData, columnList): # This method expects that methodToGetData returns a pandas dataframe, such as the method returned by: self.getDataFactory(..) localUuidString = uuidString def saveData(): (data, meta_data) = methodToGetData() experimentUuidString = localUuidString methodToNameFile = self.getDataMethodFactory(tickerName, uuidString) (full_filepathname, full_filename, uuidString) = methodToNameFile() methodToSaveData = self.getDataFrameSaverFactory(methodToGetData, columnList, full_filepathname) # We might want try/catch here: methodToSaveData() # A parameterless method that has immutable state (…
accepted answer: http://stackoverflow.com/a/48039833
has comment: http://stackoverflow.com/comment/83050011
answer count: 1
tagged with: first-class-functions
has title: Python 3 parameter closed upon by inner/nested method falls out of scope and triggers UnboundLocalError
favorite count: 0
has comment: http://stackoverflow.com/comment/83050035
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48039833
has comment: http://stackoverflow.com/comment/83166295
tagged with: python
tagged with: lambda
downvote count: 4
has comment: http://stackoverflow.com/comment/83227484
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83151075
has comment: http://stackoverflow.com/comment/83151181
linked to: http://stackoverflow.com/q/291978
type: Question
has comment: http://stackoverflow.com/comment/83050225
score: -2

http://stackoverflow.com/q/48170398
has body: I have a list containing lists containing arrays, something like this: A = [ [ array([[ 1., 4.3, 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]) ], [ array([[ 5., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]]) ] ] So I basically have two 4x4 matrices inside of this thing. Now, the goal is to take the average of these two which I managed to do with: np.mean([A[0][0],A[1][0]],axis=0) I also have another matrix B which consists of three 4x4 matrices, and the average would then be something like np.mean([B[0][0],B[1][0]],B[2][0],axis=0) I want to generalize this so that I dont have to rewrite the np.mean part each time. So I would probably use the length of A (2) or length of B (3) to construct that, but I'm not sure how to get something like np.mean(C[0][0],C[1][0],[...][0],[n-1][0],axis=0) where n is len(C). How can I implement this? Thanks!
has answer: http://stackoverflow.com/a/48171081
answer count: 1
downvote count: 0
favorite count: 0
has title: How do I change taking the mean based on the length of the list? (Python)
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83320497
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83320598
type: Question
tagged with: numpy

http://stackoverflow.com/comment/83028068
type: Comment
comment on: http://stackoverflow.com/a/48028977
has text: Thank you very much for the response. Unfortunately, it still only goes through the first page. Does not move to next page.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83232708
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48124763
has text: I tired both `./Data/` and using the full file path but neither would fixed the issue. Any suggestions for running a several python scripts in series and not using a bash script?
score: 0

http://stackoverflow.com/q/48020122
tagged with: animation
tagged with: python
has title: Currently Animating Scatter Plot With Static Frames. Is there a way to animate over a moving window instead?
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: plot
type: Question
accepted answer: http://stackoverflow.com/a/48029895
has comment: http://stackoverflow.com/comment/83014735
tagged with: matplotlib
has body: I have an array of arrays with format [2000][200,3] that I am creating an animated scatter plot of. 2000 is the number of frames and the interior arrays have format [length, [x,y,inten]] which are the points to scatter. So for an example a single frame will look like: Array[0]=np.array([x_1,y_1,I_1],[x_2,y_2,I_2],...,[x_200,y_200,I_200]) So we have 2000 frames of 200 points each. These points are arbitrarily truncated every 200 and are actually sequential. So I can feasibly reshape the array into: Array=np.array(np.array([x_1,y_1,I_1],[x_2,y_2,I_2],...,[x_400000,y_400000,I_400000]) Which is no problem for me. I know how to do this. My question is how can I animate a scatter plot that adaptively moves through the points instead of displaying 200 point bins? The code below allows me to plot an animated scatter plot with frames (1-200,201-400,401-600,etc) but the result is not very smooth to the eye. Ideally I would like something that updates at every point or at least every 10 points so for example frames (1-200,2-201,3-202,etc) or (1-200,11-210,21-200,etc) numframes=len(Array) plt.ion() fig, ax = plt.subplots() norm = plt.Normalize(Array[:][:,2].min(), Array[:][:,2].max()) sc = ax.scatter(Array[0][:,0], Array[0][:,1], c=Array[0][:,2], cmap=cm.hot, s=5) plt.xlim(-40,40) plt.ylim(0,200) plt.draw() for i in range(numframes): sc.set_offsets(np.c_[Array[i][:,0], Array[i][:,1]]) sc.set_array(Array[i][:,2]) print(i) plt.pause(0.1) plt.ioff() plt.show()
tagged with: numpy
has answer: http://stackoverflow.com/a/48029895
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/509211
favorite count: 0

http://stackoverflow.com/comment/83169349
type: AnswerComment
has text: Thanks. That's great.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48080621

http://stackoverflow.com/q/48019927
has title: How to fetch data in loop in python mysql
has comment: http://stackoverflow.com/comment/83010401
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83009262
tagged with: python
has comment: http://stackoverflow.com/comment/83010511
tagged with: mysql
linked to: http://stackoverflow.com/q/589284
duplicate of: http://stackoverflow.com/q/21740359
type: Question
has answer: http://stackoverflow.com/a/48020024
has comment: http://stackoverflow.com/comment/83008974
has body: I have a list and i want to pass all value of list to the where condition of Query.I am using This in Maya Python script Editor using maya cmds code list = [1,2,3] db = MySQLdb.connect("host","root","password","test" ) for num in list: cursor = db.cursor() cursor.execute('select Name from project WHERE projectID = %s '%(num)) name = cursor.fetchone() print(name) cursor.close() Error Error: ProgrammingError: file C:\Program Files\Autodesk\Maya2014\Python\lib\site-packages\MySQLdb\connections.py line 38: 1064 #
linked to: http://stackoverflow.com/q/23600286
has comment: http://stackoverflow.com/comment/83010819
score: 0
answer count: 1
tagged with: maya

http://stackoverflow.com/comment/83100808
score: 3
comment on: http://stackoverflow.com/q/48063908
has text: From the [documentation](http://docs.python.org/3.2/tutorial/inputoutput.html#methods-of-file-objects) for Python 3.2 and up: > In text files (those opened without a `b` in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with `seek(0, 2)`).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83139420
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48082090
has text: Apparently you're using a `numpy` array. Look at the [avaliable ways to slice arrays](https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html); your case could turn out trivial.

http://stackoverflow.com/comment/83020386
type: Comment
comment on: http://stackoverflow.com/a/48024992
has text: You solve your problem? I think you have to post your solution here, or edit your question. Thanks.
type: AnswerComment
score: 0

http://stackoverflow.com/a/50026086
type: Answer
answers question: http://stackoverflow.com/q/48054761
upvote count: 27
type: AcceptedAnswer
downvote count: 0
score: 27
has body: Maybe Q expression can help. Try this: Case( When( Q(registered_on__gt=date(2014, 1, 1)) &amp; Q(registered_on__lt=date(2015, 1, 1)), then='account_type' ), default='default' )
accepted answer of: http://stackoverflow.com/q/48054761

http://stackoverflow.com/q/48084565
answer count: 1
tagged with: python-3.x
has body: I have a QTableWidget with lots of items. I wanted to make it so that when i press the Return key (Same as Qt.Key_Return) while editing a cell, it will select and edit the next cell. However, if i call the nextrow function, it will not do anything, if i'm already editing a QTableWidgetItem already. It does work when nothing is being edited, and it will edit the selected row. self.table = QTablewidget() ... # Populate widget with QTableWidgetItems def nextrow(self, row) column = 1 self.table.editItem(self.table.item(row, column)) I see no way to actually disable that edit mode, and it completely ignores everything from setting the text to something, disabling the edit permission, because i'm already editing it. And as far as i looked, i couldn't find any method to do it either.
tagged with: python
has answer: http://stackoverflow.com/a/48087050
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48087050
tagged with: pyqt5
type: Question
has title: QTableWidget, Stop editing of QTableWidgetItem
score: 0
tagged with: pyqt

http://stackoverflow.com/comment/97995389
comment on: http://stackoverflow.com/a/48121996
type: Comment
has text: This is a nice technique because it works with any number of channels. I tried this with rgb data combined with a depth point cloud data and it preserved the relationship like I wanted.
type: AnswerComment
score: 5

http://stackoverflow.com/comment/83219789
has text: https://github.com/AvivC/genericfuncs
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48121458
score: 1

http://stackoverflow.com/a/48165401
type: Answer
accepted answer of: http://stackoverflow.com/q/48148825
answers question: http://stackoverflow.com/q/48148825
score: 0
has body: It is a memory problem I tried to reproduce the error today and realized that the example works fine if there is not a huge pandas dataframe (size (450016, 35)) uploaded.
type: AcceptedAnswer

http://stackoverflow.com/comment/83190362
score: 0
type: AnswerComment
type: Comment
has text: like i am getting response message as "hi, your order completed " i want it to print as "hi" in first line and remaining in second.
comment on: http://stackoverflow.com/a/48075023

http://stackoverflow.com/a/48146356
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48145173
has body: It's almost correct You are very close but you've forgotten a condition for when x is not printed and y and z are both even. Try the example of (4,2,6) for (x,y,z). Your exhaustive reasoning makes sense, but it is hard to program like this. I want to walk through your current logic then show how your code can be simplified, but your approach is clear using only if-else and indentation. Your logic In your logic you check all possibilities where you would ever print x which is if any following are true so long as x is odd: x is the largest of x, y, and z x is bigger than y when z is even x is bigger than z when y is even y and z are even Then in the first elif you test whether to print y and make the correct decision to no longer check x at all since the first if handled all the cases where you would want to print x. This is where your mistake is, however, since you should keep the same logical structure as your if statement for x: elif ((y&gt;z) or (y&lt;z and z%2==0)) and y%2!=0: You do the same for z in the last elif and then use else if all are even. Simplifying your logic We can simplify the first if statement where you check for x. One small note is that it is better to check that x is odd before doing all the or checks, since if x is even the computer doesn't have to look at all the or logic (short-circuiting): if x%2 != 0 and ((x&gt;y and x&gt;z) or (x&gt;y and x&lt;z and z%2==0) or (x&gt;z and x&lt;y and y%2==0) or (x&lt;z and x&lt;y and y%2==0 and z%2==0)): Next the or logic can be simplified to: if x%2 != 0 and ((x&gt;=y and x&gt;=z) or (x&gt;=y and z%2==0) or (x&gt;=z and y%2==0) or (y%2==0 and z%2==0)): All the simplifications came from the idea that if y or z is even we don't need to compare it to x since we'd want to print x regardless. I've also changed the &gt; to &gt;= or you would have had errors if some of the variables had the same values. With the same reasoning we can simplify the first elif to: elif ((y&gt;=z) or (z%2==0)) and y%2!=0: Bonus If …
type: Answer
answers question: http://stackoverflow.com/q/48145173

http://stackoverflow.com/a/48137397
type: Answer
has comment: http://stackoverflow.com/comment/83252416
score: 4
has body: Using negation to reverse operations You write it like: if (start_codon &lt;= coord &lt;= stop_codon) and strand==1: # do operation elif (start_codon &gt;= coord &gt;= stop_codon) and strand==-1: # do operation But this is equivalent to: if abs(strand) == 1 and strand * start_codon &lt;= strand * coord &lt;= strand * stop_codon: # do operation pass Or in case we can make the assumption that abs(strand) == 1 always holds: if strand * start_codon &lt;= strand * coord &lt;= strand * stop_codon: # do operation pass Theoretical proof This works since x &gt;= y, is equilvalent to -x &lt;= -y. So instead of "reversing" the condition, we multiply both operands with -1, and thus implicitly reverse the condition. Let us take the example: In case strand == 1, then we thus evaluate -start_codon &lt;= -coord &lt;= -stop_codon. This is equivalent to -start_codon &lt;= -coord and -coord &lt;= -stop_codon. Now we can normalize the two subexpressions with start_codon &gt;= coord and coord &gt;= stop_codon which is equivalent to start_codon &gt;= coord coord &gt;= stop_codon. So this means that -start_codon &lt;= -coord &lt;= -stop_codon is equivalent to start_codon &gt;= coord &gt;= stop_codon. We make a single assumption: that is that start_codon and stop_codon are numbers (such that we can multiply these). Empirical evidence We can generate empirical evidence for this relation emprically as well by the following setup: import numpy as np test_size = 1000 a = np.random.randn(test_size, 4) # generate 1000x4 matrix of random data a[:,3] = np.sign(a[:,3]) # make the last column -1 and 1 assert not (a[:,3] == 0).any() # check no zeros in the last column b = np.zeros(test_size) # results for our relation c = np.zeros(test_size) # results for the question implementation for i, (start_codon, coord, stop_codon, strand) in enumerate(a): b[i] = strand * start_codon &lt;= strand * coord &lt;= strand * stop_codon if (start_codon &lt;= coord &lt;= stop_codon) and strand==1: c[i] = 1 elif (start…
has comment: http://stackoverflow.com/comment/83252134
answers question: http://stackoverflow.com/q/48137332
has comment: http://stackoverflow.com/comment/83253330
has comment: http://stackoverflow.com/comment/83252324
has comment: http://stackoverflow.com/comment/83252200
has comment: http://stackoverflow.com/comment/83252684
has comment: http://stackoverflow.com/comment/83252274
upvote count: 4
has comment: http://stackoverflow.com/comment/83252099
has comment: http://stackoverflow.com/comment/83252283
has comment: http://stackoverflow.com/comment/83252250
has comment: http://stackoverflow.com/comment/83252080
downvote count: 0
has comment: http://stackoverflow.com/comment/83252349
has comment: http://stackoverflow.com/comment/83252185
has comment: http://stackoverflow.com/comment/83252093

http://stackoverflow.com/a/48126264
answers question: http://stackoverflow.com/q/48126253
upvote count: 6
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/134998784
has body: You could use isinstance: if isinstance(myvar, pandas.core.series.Series): # Do some processing
score: 6

http://stackoverflow.com/a/48173660
has body: You can only create categories with the rewrite version of discord.py (1.0.0a) Here is the documentation for it. This would be an example of how I would do it with the commands extension: @bot.command() async def create_category(ctx, *, name): await ctx.guild.create_category(name)
answers question: http://stackoverflow.com/q/48172961
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/83112282
comment on: http://stackoverflow.com/a/48069132
score: 0
type: AnswerComment
type: Comment
has text: How would i implement it ? Im tring for whole day and im getting more confused :S

http://stackoverflow.com/a/49163698
answers question: http://stackoverflow.com/q/48152457
downvote count: 0
score: 9
has comment: http://stackoverflow.com/comment/133577892
has body: I think it may have to do with your 'date_time_stamp', since it tries to download the files in the same second, and the system only keeps the last one. You could try using a UUID for that to ensure it is a unique string: import uuid file_uuid = str(uuid.uuid4()) ... attachments.SaveASFile(os.getcwd() + '\\' + 'my_attachment_name' + file_uuid + '.csv') To mark the message as Read, you could simply do: message.Unread = False message.Save()
upvote count: 9
type: Answer

http://stackoverflow.com/q/48053823
downvote count: 0
has comment: http://stackoverflow.com/comment/83081950
duplicate of: http://stackoverflow.com/q/47769818
has comment: http://stackoverflow.com/comment/83082097
has comment: http://stackoverflow.com/comment/83081966
has body: I have a large (~20 million) dataframe containing the posts made by users on various communities. The columns include 'community' and 'text'. Each row corresponds to a post; each community will typically have one thousand to several hundred thousand associated posts. I would like to output a dictionary containing community names as keys and associated Counters counting the number of occurrences of each token in that community. I thought the easiest way to do this would be to group the Pandas dataframe by community, concatenate the 'text' into a string, clean/tokenize, and apply the Counter, as follows: def run(data): counts = {} data_grouped = data.groupby('community') for community, group in data_grouped: community_doc = group['text'].str.cat(sep = '') community_doc = community_doc.lower() community_doc = community_doc.translate(None, string.punctuation) tokens = nltk.word_tokenize(community_doc) tokens = [token for token in tokens if not token in stopwords.words('english')] count = Counter(tokens).most_common() counts[community] = count return counts However, the code runs incredibly slowly -- often 20-30 minutes per community. Is there a more efficient way to do this?
tagged with: pandas
score: 3
has title: Tokenize and count tokens in grouped Pandas dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83080267
tagged with: nlp
favorite count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/83080245
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48049087
tagged with: tokenize
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/83082242
linked to: http://stackoverflow.com/q/47769818
has comment: http://stackoverflow.com/comment/83082222
tagged with: nltk

http://stackoverflow.com/q/48132971
accepted answer: http://stackoverflow.com/a/48133000
has answer: http://stackoverflow.com/a/48133142
has body: For a project to create a database, I wanted to convert .json files into .sqlite3 files using python (currently running Python 3.6.4 on Windows 10). Below is the code designed to read a json file ... with open('C:/Documents/{}/Posts.json'.format(forum), encoding="utf8") as f: row = json.load(f) parent_id = row['_Id'] body = format_data(row['_Body']) score = row['_Score'] comment_id = row['_Id'] comment_id_type = row['_PostTypeId'] parent_id_type = row['_PostTypeId'] accepted_answer_id = row['_AcceptedAnswerId'] accepted_parent_id = row['_ParentId'] ... While running this code I encounter this error. File "C:\Python\data base.py", line 85, in <module> parent_id = row['_Id'] KeyError: '_Id' I've read into this error finding that, according to the official python docs, the exception KeyError is Raised when a mapping (dictionary) key is not found in the set of existing keys. Now I've had trouble understanding this syntax because '_Id' exists in the json file(as seen below) { "posts": { "row": [ { "_Id": "1", "_PostTypeId": "1", "_AcceptedAnswerId": "3", "_CreationDate": "2016-08-02T15:39:14.947", "_Score": "5", "_ViewCount": "254", "_Body": " What does \"backprop\" mean? I've Googled it, but it's showing backpropagation. \n\n Is the \"backprop\" term basically the same as \"backpropagation\" or does it have a different meaning? \n", "_OwnerUserId": "8", "_LastEditorUserId": "7488", "_LastEditDate": "2017-05-28T13:48:02.003", "_LastActivityDate": "2017-05-28T13:48:02.003", "_Title": "What is \"backprop\"?", "_Tags": "<neural-networks><definitions><terminology>", "_AnswerCount": "3", "_CommentCount": "3" }, (This is a json from AI:stackexchange data) I request someone help give me a solution to my KeyError, for other sources I have searched yield me no help Please and thank you, in advance.
tagged with: python
has title: JSON reading with python: KeyError
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83243541
score: 0
possible better answer: http://stackoverflow.com/a/48133142
has answer: http://stackoverflow.com/a/48133000

http://stackoverflow.com/comment/83350830
type: QuestionComment
score: 0
has text: @stucash the whole point of `conda` is that it doesn't tamper with the system Python in any way, but installs everything only within its own environment(s). @JimmysCheeseSteak how are you starting Spyder?
type: Comment
comment on: http://stackoverflow.com/q/48171761

http://stackoverflow.com/comment/83187736
has text: Your code is fine. It's just not indented. Checkout my answer.
comment on: http://stackoverflow.com/q/48105436
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83323164
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48171749
has text: @pycoder you correctly catched it ..thnx
score: 0

http://stackoverflow.com/comment/83047431
type: Comment
comment on: http://stackoverflow.com/q/48035929
type: QuestionComment
has text: Yes, every time i make a change i restart the server
score: 0

http://stackoverflow.com/q/48158023
has comment: http://stackoverflow.com/comment/83295983
type: Question
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83295689
favorite count: 0
has comment: http://stackoverflow.com/comment/83304764
tagged with: python-2.7
tagged with: python
has comment: http://stackoverflow.com/comment/83295761
has body: I am programming in Python. The problem is that when I use a variable to input a string to the class, I get this error. Can you tell me what is the problem with it? I have already tried single quotation within the input. This is the code class Hero: def __init__(self,name): self.name = name self.health = 100 def eat(self,food): if food == 'ham': self.health -= 50 elif food == 'apple': self.health += 60 else: print "rowing answer" huseein = Hero("Husma") print huseein.name print huseein.health x = str(input("enter ham or apple")) huseein.eat(str(x)) print huseein.health
has comment: http://stackoverflow.com/comment/83300631
has comment: http://stackoverflow.com/comment/83295495
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83295519
has comment: http://stackoverflow.com/comment/83295573
has title: Arguments and input in classes issue
downvote count: 0
has answer: http://stackoverflow.com/a/48168650
score: 1

http://stackoverflow.com/a/48157738
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48157259
answers question: http://stackoverflow.com/q/48157259
has body: Seems like you forgot to close parenthesis: for item in targets_list: usernames.append(item.strip('\n'))
upvote count: 1
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/83093768
score: 0
comment on: http://stackoverflow.com/q/48060354
has text: Please specify what version of MongoDB you are using.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/112951844
score: 0
type: AnswerComment
has text: Hmmm, these are instruction for a 64-bit Windows... The question clearly states 32-bit windows...
comment on: http://stackoverflow.com/a/57566621
type: Comment

http://stackoverflow.com/comment/83287987
score: 0
comment on: http://stackoverflow.com/a/48154400
type: Comment
has text: Also we can do `set(df["0"].astype(str))` since OP has object columns, though it cant beat the `unique()`
type: AnswerComment

http://stackoverflow.com/comment/83327591
score: 1
type: QuestionComment
type: Comment
has text: There is no inbuilt "jitter" function. But of course you can calculate some new jittered coordinates yourself.
comment on: http://stackoverflow.com/q/48172881

http://stackoverflow.com/q/48053134
tagged with: pandas
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83105067
tagged with: data-science
favorite count: 0
has comment: http://stackoverflow.com/comment/83084455
tagged with: python
answer count: 0
type: UnansweredQuestion
tagged with: pandasql
upvote count: 1
has title: Accessing the columns of pivot table in Python Pandas
has comment: http://stackoverflow.com/comment/83092984
has body: I'm using a python pandas pivot. How can I get access the columns of pivot on new data frame? KM_pivot_first = pd.pivot_table(read_sql_KM, values=["IMPRESSIONS","ENGAGEMENTS"],index="PLACEMENT_ID",aggfunc=np.sum) KM_data_summary = KM_pivot_first"PLACEMENT_ID", "IMPRESSIONS", "ENGAGEMENTS" error: File "C:\Python27\lib\site-packages\pandas\core\indexing.py", line 1231, in _convert_to_indexer raise KeyError('%s not in index' % objarr[mask]) KeyError: "['PLACEMENT_ID'] not in index" though, 'PLACEMENT_ID' is present in the query.
type: Question
has comment: http://stackoverflow.com/comment/83078617

http://stackoverflow.com/q/48121303
tagged with: optimization
has comment: http://stackoverflow.com/comment/83219281
has comment: http://stackoverflow.com/comment/83219605
answer count: 2
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48122040
favorite count: 0
has comment: http://stackoverflow.com/comment/83219575
has answer: http://stackoverflow.com/a/48121589
has body: I have a python list with each string being one of the following 4 possible options like this (of course the names would be different): Mr: Smith\n Mr: Smith; John\n Smith\n Smith; John\n I want these to be corrected to: Mr,Smith,fname\n Mr,Smith,John\n title,Smith,fname\n title,Smith,John\n Easy enough to do with 4 re.sub(): with open ("path/to/file",'r') as fileset: dataset = fileset.readlines() for item in dataset: dataset = [item.strip() for item in dataset] #removes some misc. white noise item = re.sub((.*):\W(.*);\W,r'\g&lt;1&gt;'+','+r'\g&lt;2&gt;'+',',item) item = re.sub((.*);\W(.*),'title,'+r'\g&lt;1&gt;'+','+r'\g&lt;2&gt;',item) item = re.sub((.*):\W(.*),r'\g&lt;1&gt;'+','+r'\g&lt;2&gt;'+',fname',item) item = re.sub((*.),'title,'+r'\g&lt;1&gt;'+',fname',item) While this is fine for the dataset I'm using, I want to be more efficient. Is there a single operation that can simplify this process? Please pardon if I forgot a quote or some such; I'm not at my workstation now and I'm aware I've stripped the newline (\n). Thank you,
possible better answer: http://stackoverflow.com/a/48122040
has title: Python re.sub() optimization
tagged with: python
linked to: http://stackoverflow.com/q/5733419
tagged with: regex
accepted answer: http://stackoverflow.com/a/48121589
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6186938
has comment: http://stackoverflow.com/comment/83221224
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83219626

http://stackoverflow.com/q/48055736
has comment: http://stackoverflow.com/comment/83083955
answer count: 1
has title: Python method returning immediate then executing code during reload (gunicorn)
has answer: http://stackoverflow.com/a/48070192
type: UnansweredQuestion
has body: A totally bizarre issue. Very simple code. Gunicorn/Flask web app. External call comes in, executes everything just fine or so it seems. I'm calling method from another class. I am instantiating that class in my gunicorn method that's handling the request. The method I'm calling returns immediately (it's returning True/False, returns True even though the code hasn't been reached). I have gunicorn set to reload when code changes. When I make a change in my code to cause a reload of the app, all of the calls to this external class fire off in order.. like they were queued. The external class is using cx_Oracle and making database updates (once the reload occurs) The first line of this external method is a print(). In my application logs, that line is never printed until the reload occurs yet the return value in that class is somehow returned because if I return False or don't return anything, the app throws an exception (as it should) This code returns immediate. @app.route("/mytest") def test(): myclass = MyClass() myclass.update() return "OK" Calling it: $ curl http://localhost:8000/mytest [2018-01-01 23:05:30 -0600] [12160] [DEBUG] GET /mytest [2018-01-01 23:05:30 -0600] [12150] [DEBUG] Closing connection. OK update method: def update(self): returnVal = True print("=======================&gt; HERE") Reloading app with a file change: [2018-01-01 23:05:50 -0600] [12183] [INFO] Booting worker with pid: 12183 [2018-01-01 23:05:50 -0600] [12160] [INFO] Worker exiting (pid: 12160) ==&gt; nohup.out &lt;== =======================&gt; HERE
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/83083742
has comment: http://stackoverflow.com/comment/83083968
score: 0

http://stackoverflow.com/comment/83147357
comment on: http://stackoverflow.com/q/48084325
type: Comment
type: QuestionComment
score: 1
has text: Julia also have a `startswith`; `startswith(ln, '@')` is the same as: `ln[1] == '@'`

http://stackoverflow.com/a/48017926
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83013567
has comment: http://stackoverflow.com/comment/83004878
has comment: http://stackoverflow.com/comment/83011266
upvote count: 2
answers question: http://stackoverflow.com/q/48017890
type: Answer
has comment: http://stackoverflow.com/comment/83004896
has comment: http://stackoverflow.com/comment/83011822
accepted answer of: http://stackoverflow.com/q/48017890
has comment: http://stackoverflow.com/comment/83012402
has comment: http://stackoverflow.com/comment/83013533
has comment: http://stackoverflow.com/comment/83004892
has body: Use DataFrame.xs: print (jkm_df.xs(201406, level=1)) px_settlement contract_code assessment_date 2014-01-02 16.1 m14 Also if necessary both levels use parameter drop_level=False: print (jkm_df.xs(201406, level=1, drop_level=False)) px_settlement contract_code assessment_date contract_serial 2014-01-02 201406 16.1 m14 Solution with loc: print (jkm_df.loc(axis=0)[:, 201406]) px_settlement contract_code assessment_date contract_serial 2014-01-02 201406 16.1 m14 Another solution with slicers: print (jkm_df.loc[(slice(None), 201406), :]) px_settlement contract_code assessment_date contract_serial 2014-01-02 201406 16.1 m14
has comment: http://stackoverflow.com/comment/83012624

http://stackoverflow.com/a/48129248
accepted answer of: http://stackoverflow.com/q/48128935
answers question: http://stackoverflow.com/q/48128935
type: Answer
has body: Try and change your print statement to this: print(output.decode('utf-8')) The output is of type 'bytes' and needs to be decoded to convert to a string for proper formatting.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/83175004
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48099565
has text: You forgot `range`?

http://stackoverflow.com/comment/83254097
type: Comment
has text: Yeah, tried your command and it says 'destination path 'pyttrex' already exists and it's not empty'
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48137149

http://stackoverflow.com/comment/83314844
comment on: http://stackoverflow.com/q/48167239
has text: @khelwood Is this a bug? I tried it on my laptop as well and same issue
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83107652
type: Comment
has text: It`s a numeric field (Long Integer). I did try it without quotations, but it returned an error saying: cannot concatenate 'str' and 'int' objects. I also tried your first method, it did succeed, but I`m still having the same issue, nothing gets selected, the data on the map just blinks as if it were altered, but nothing get highlighted.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48058991

http://stackoverflow.com/q/48171974
tagged with: elementtree
has comment: http://stackoverflow.com/comment/83362354
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83323832
has answer: http://stackoverflow.com/a/48197432
has comment: http://stackoverflow.com/comment/83327649
has comment: http://stackoverflow.com/comment/83324472
type: Question
tagged with: xml-parsing
has comment: http://stackoverflow.com/comment/83334893
has body: I have some XML with the following structure: blah-1 text-value-A text-value-B text-value-C text-value-D blah-2 text-value-A text-value-B blah-3 text-value-C text-value-A blah-4 text-value-C text-value-A Currently, I am parsing the text-value-s and joining them with some string !, but for the text-value-X occurring last within a properties level, I need to assign some other string &, and output something like: text-value-A!text-value-B!text-value-C!text-value-D&text-value-A!text-value-B&text-value-C!text-value-A. Since the attributes in <property cannot be specific to tags/have random values, something like if(item.text == 'text-value-A') #get text-value-A of parent-3 won't work. ---------- I am not keeping duplicate text-value-s (in this case will not need parent-4 since text-value-s of parent-3 are identical) and I want to preserve order, so with enumerate I am doing the following: alist = [] for item in root.findall('parent/properties/property'): alist.append(item.text) self.alist = '!'.join([a for b,a in enumerate(alist) if a not in alist[:b]] Given the desired output above, I am wondering if I need a different approach to this problem or the concept of something like the following will somehow work: alist = [] for item in root.findall('parent/properties/property'): alist.append(item.text) for element in alist: if element in alist[-1]: self.alist = '&'.join([a for b,a in enumerate(alist) if a not in alist[:b]] if not element in alist[-1]: self.alist = '!'.join([a for b,a in enumerate(alist) if a not in alist[:b]] Thanks
has comment: http://stackoverflow.com/comment/83374391
accepted answer: http://stackoverflow.com/a/48197432
score: 0
tagged with: xml.etree
answer count: 1
has comment: http://stackoverflow.com/comment/83327673
has title: Getting the last tag in ElementTree and append text

http://stackoverflow.com/q/48113662
has comment: http://stackoverflow.com/comment/83204541
has comment: http://stackoverflow.com/comment/83209450
has body: Hello I'm looking for a way to implement a simple L-system into function in python which would take three arguments : axiom , rules and number of interations(if iterations = 0 output would be previously input axiom). I came up with some code it only works on 1 iteration and I dont know how to implement more. The code I came up with : # x = axiom # y = rules # z would be iterations which I dont know how to implement def lsystem(x,y): output = '' for i in x: if i in y: output += y[i] else: output += i print(output) rules = { "A" : "ABA" , "B" : "BBB"} # output lsystem("AB",rules) ---&gt; ABABBB
tagged with: function
downvote count: 0
has answer: http://stackoverflow.com/a/48114486
score: 2
type: AnsweredQuestion
has title: Simple L -system in python
tagged with: l-systems
tagged with: iteration
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48114486
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83203449
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/83205477

http://stackoverflow.com/q/48034044
has answer: http://stackoverflow.com/a/48043743
type: Question
upvote count: 4
tagged with: tile
has body: I'm using PyGame 1.9.2 on Python 3.4.3 (Win8.1). My game window consists of a tiled map using 48x48px tiles. The game's framework moves the tiles according to player input using the following method of the game's framwork class: def moveTiles(self): xmove = self.parent.dt * self.panning[0] * self.panning_speed ymove = self.parent.dt * self.panning[1] * self.panning_speed for tile in self.game_map: tile.x += xmove tile.y += ymove tile.rect.x = int(tile.x) tile.rect.y = int(tile.y) tile.pos = (tile.rect.x, tile.rect.y) While "self.panning_speed" is pretty self-explanatory, self.panning is a list containing two values for x and y panning (e.g. [0, 0] = no panning, [-1, 1] = panning down-left, etc.). The tile.x/tile.y values are then "int'ed" to be used as x-/y-values of the rect and the pos (the latter used for blitting). I add the exact same amount to every single tile's x/y value, then I use "int" on them which, to my knowledge, always floors the float down to the next lower int. So technically seen the relative change to every single tile's x/y value is the exactly same as to any other tile's x/y value. Yet: I still get gaps between rows or columns from time to time! Those gaps appear irregularly but are very visible and when you stop panning while a gap is visible that gap will stay until you pan again. See this image for an example: See this image for an example (black line in the red square is the gap; gold and pink are the tiles) Where in my code can these gaps occur?
score: 4
possible better answer: http://stackoverflow.com/a/48035464
answer count: 3
has comment: http://stackoverflow.com/comment/83039141
has title: PyGame: Panning tiled map causes gaps
accepted answer: http://stackoverflow.com/a/48036774
downvote count: 0
has comment: http://stackoverflow.com/comment/83042395
favorite count: 0
has answer: http://stackoverflow.com/a/48036774
tagged with: python
tagged with: pygame
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48035464
has comment: http://stackoverflow.com/comment/83039260

http://stackoverflow.com/q/48071949
has answer: http://stackoverflow.com/a/63774287
tagged with: alpha-vantage
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/50163776
possible better answer: http://stackoverflow.com/a/59161026
has comment: http://stackoverflow.com/comment/83124393
has comment: http://stackoverflow.com/comment/83124428
has answer: http://stackoverflow.com/a/59161026
has answer: http://stackoverflow.com/a/50430878
has comment: http://stackoverflow.com/comment/83127029
tagged with: python-requests
has answer: http://stackoverflow.com/a/56598142
type: Question
score: 5
has answer: http://stackoverflow.com/a/62371542
has comment: http://stackoverflow.com/comment/83124639
upvote count: 5
has body: I've been using Romel Torres' alpha_vantage package but would also like to use the Alpha Vantage API directly from python (gives greater functionality) with package requests as described here CALL with CURL an API through Python: import requests import alpha_vantage API_URL = "https://www.alphavantage.co/query" data = { "function": "TIME_SERIES_DAILY", "symbol": "NIFTY", "outputsize": "compact", "datatype": "csv" "apikey": "XXX", } response = requests.get(API_URL, data) print(response.json())[/code] But am getting the following error message in the dict returned: {'Error Message': 'Invalid API call. Please retry or visit the documentation (https://www.alphavantage.co/documentation/) for TIME_SERIES_DAILY.'} And with requests.post() the outcome is: response = requests.post(API_URL, data) {'detail': 'Method "POST" not allowed.'} I've re-checked the documentation and am following all the required API parameters. Appreciate some help re what I might be missing here and what the correct call would be and/or any other alternative approach. Thanks
accepted answer: http://stackoverflow.com/a/50163776
tagged with: api
downvote count: 0
answer count: 7
has title: How to use the Alpha Vantage API directly from Python
favorite count: 0
has answer: http://stackoverflow.com/a/51561823
linked to: http://stackoverflow.com/q/38289153
tagged with: python

http://stackoverflow.com/q/48089911
has body: Given a wav file (mono 16KHz sampling rate) of an audio recording of a human talking, is there a way to extract just the voice, thereby filtering out most mechanical and background noise? I'm trying to use librosa package in Python 3.6 for this, but can't figure out how piptrack works (or if there is a simpler way). When tried using an fft/ifft to restrict frequencies to 300-3400 range, the resulting sound was severely distorted. sr, y = scipy.io.wavfile.read(wav_file_path) x = np.fft.rfft(y)[0:3400] x[0:300] = 0 x = np.fft.irfft(x)
has comment: http://stackoverflow.com/comment/113345638
type: UnansweredQuestion
type: Question
tagged with: audio
upvote count: 6
has answer: http://stackoverflow.com/a/73486269
score: 5
downvote count: 1
answer count: 1
tagged with: voice
favorite count: 0
tagged with: fft
has title: Python | librosa: how to extract human voice from an audio wav file?
tagged with: python
tagged with: librosa

http://stackoverflow.com/q/48033318
type: AnsweredQuestion
tagged with: list
downvote count: 2
has comment: http://stackoverflow.com/comment/83036651
has title: Grouping same elements in the list efficiently
upvote count: 1
has comment: http://stackoverflow.com/comment/83036764
type: Question
has comment: http://stackoverflow.com/comment/83036645
has body: n,m=map(int,input().split()) arr=[i%m for i in (map(int,(input().split())))] suppose n=5 and m =3 and input array =[3, 2 ,1 ,4, 5] so arr=[0, 2, 1, 1, 2] in this case but now i want to store elements of equal value in a list efficiently i.e [1,1] and [2,2].What's the best way to group them together efficiently?Also i want their indices at the end so output : [[1,1],[2,2]] from index (2,3) and index(1,4) what i am looking for is the indices of the original array elements before taking mod that have the same value after performing mod operation.
has comment: http://stackoverflow.com/comment/83036834
has comment: http://stackoverflow.com/comment/83036904
has comment: http://stackoverflow.com/comment/83036808
has comment: http://stackoverflow.com/comment/83036720
answer count: 1
has answer: http://stackoverflow.com/a/48033454
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83036913
accepted answer: http://stackoverflow.com/a/48033454
tagged with: python
has comment: http://stackoverflow.com/comment/83036742
score: -1

http://stackoverflow.com/comment/83292384
score: 0
comment on: http://stackoverflow.com/q/48156691
has text: Pass a tuple of tuples?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48024985
has title: How to patch class with different class in python
has body: I'm trying to patch one class with another one in tests, doing: @patch('integrations.Client', 'tests.utils.MockClient') def test_client(self): check_client() method: check_client() is using __integrations.Client__ class, but unfortunately after doing @patch inside __check_client__ class is not replaced with __tests.utils.MockClient__
tagged with: unit-testing
type: Question
has answer: http://stackoverflow.com/a/48062022
score: 0
tagged with: mocking
answer count: 1
tagged with: patch
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83314444
has text: This is a very inefficient way to check for unique characters. `def check_pass(): password = input('Enter a password:') ; return len(password) == len(set(password))`
comment on: http://stackoverflow.com/q/48167621
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48067735
type: Question
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/83109135
tagged with: shell
has comment: http://stackoverflow.com/comment/83135305
favorite count: 0
has body: I have a shell on a directory bash-4.1$ pwd /x/dev/local_base but when i run a python script cur_dir = os.getcwd() print "cur dir %s" % cur_dir and it returns an empty string I've tried p = subprocess.Popen("/bin/pwd", stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) out, err = p.communicate() and it returns empty as well but pwd on the shell shows current directory (/x/dev/local_base) this only happens when i leave the shell for a long time (few hours). if i cd back to the directory, it works fine. I think the directory is getting snapshotted off and being recreated in the background. Any suggestions on how to get current working dir? PS these work fine p = subprocess.Popen("ls", stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) out, err = p.communicate() and os.listdir('.') when i tried os.path.abspath on one of the files returned from listdir, it only shows relative path i.e. if listdir returns a file name README, it returns README, not /x/dev/local_base/README
tagged with: python
has title: python os.getcwd() returns empty string
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/83109103
has comment: http://stackoverflow.com/comment/83109041
downvote count: 1

http://stackoverflow.com/q/48082783
favorite count: 0
has comment: http://stackoverflow.com/comment/133416850
tagged with: python-3.x
tagged with: turtle-graphics
type: UnansweredQuestion
tagged with: python
has body: We are attempting a tank game in my class. I'm able to load the tank image however the image doesnt rotate. I did a search but cannot find a solution (or a simple one if it exists). Here's what I have so far (very elementary). I'm hoping there's a simple solution to rotating the image to turn left/right. import turtle screen = turtle.Screen() tankImage = "tank.gif" screen.addshape(tankImage) tank = turtle.Turtle() tank.shape("turtle") def left(): tank.left(20) def right(): tank.right(20) screen.listen() screen.onkey(left, "Left") screen.onkey(right, "Right") turtle.mainloop()
has title: Python Turtle: rotate custom cursor image
linked to: http://stackoverflow.com/q/35834691
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/36107570
has answer: http://stackoverflow.com/a/69671451
has answer: http://stackoverflow.com/a/63385218
downvote count: 0
score: 4
tagged with: image
answer count: 3
tagged with: python-turtle
has answer: http://stackoverflow.com/a/48084894
linked to: http://stackoverflow.com/q/11277518

http://stackoverflow.com/comment/83226962
comment on: http://stackoverflow.com/a/48125038
type: AnswerComment
score: 0
type: Comment
has text: And? First, your code does not correspond to your data, as there is no `Time` column. Second, you don't show the code with the loop. Third, you reference `x` without indicating what it is (a variable in your loop, presumably, but referencing what exactly?) Fourth, you don't provide the error that you are getting.

http://stackoverflow.com/comment/83213029
has text: Yep, looks like that’s the key. What’s the implications when running on Windows or *nix? Will this fail?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48118320
score: 1

http://stackoverflow.com/comment/83049141
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48039309
has text: OK, you could show a code that can run to see what is the best option, yours is not currently.

http://stackoverflow.com/a/48103377
type: Answer
answers question: http://stackoverflow.com/q/48103119
score: 0
has body: Have a look at networkx, plot.ly, or graph-tool. I cannot recommend some text based ASCII art-like visualization. Using an elaborate package gives you way more freedom and can also work with more complex data where a visualization is not as easy to set up for.

http://stackoverflow.com/q/48090513
has title: How do I create a method with a dict of fuel types and corresponding default unit prices integer values and make them appear in a form in Odoo
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48098539
accepted answer: http://stackoverflow.com/a/48098539
tagged with: odoo
tagged with: odoo-8
tagged with: odoo-9
score: 0
tagged with: odoo-10
has body: How do I make it possible when the user selects the Fuel Type in the form , the Unit Price will automatically display the integer unit value for corresponding fuel type chosen. For example when user selects petroleum the value of 0.87(currency is in dollars) should appear automatically at unit price field. Here is the code for the class I created for the station registration # Fuel Station register Class class fleet_fuel_stn_reg(osv.Model): _name = 'fleet.fuel.station.reg' _description = 'Contains fuel station details to register' _columns = { 'station':fields.char('Station Name'), # 'partner':fields.many2one('fleet.partner','Partner', required=True), 'location':fields.char('Location', help='Location of the vehicle (garage, ...'), 'fuel_type': fields.selection([('petroleum', 'Petroleum'), ('diesel', 'Diesel'), ('kerosene', 'Kerosene')], 'Fuel Type', help='Fuel Used by the vehicle'), 'stocklevel':fields.float('Stock Level'), 'unit':fields.selection([('litres', 'Litres')], 'Odometer Unit', help='Unit of the odometer ',required=True), 'unit_price':fields.float('Unit Price'), 'init_stock':fields.float('Initial Stock'), 'init_stock_taken':fields.date('Initial Stock Taken In'), } Here is how the interface looks like:
answer count: 1

http://stackoverflow.com/comment/83065370
comment on: http://stackoverflow.com/q/48046729
type: Comment
type: QuestionComment
has text: I prefer `== 0` here. You're getting an `int` containing the file size, and you want to know if the size equals zero. I don't like `not` in this case, because I use multiple languages and have trouble keeping track of which ones regard `0` as "falsy" or "truthy". Python considers `0` to be falsy, so `not 0` is `True`, but Ruby considers _any_ number, `0` included, to be _truthy_, so `not 0` is `false`!
score: 1

http://stackoverflow.com/comment/83324245
score: 0
type: Comment
has text: Now it's working but not completly. I've posted an edit.
comment on: http://stackoverflow.com/a/48171747
type: AnswerComment

http://stackoverflow.com/comment/83058581
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48043754
has text: Yep the brackets are working thanks! I never knew you could put brackets around logic operators.
type: Comment

http://stackoverflow.com/a/48066892
accepted answer of: http://stackoverflow.com/q/48066093
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/83120966
downvote count: 0
score: 1
has body: Not sure of kind of OrderedDict you have, but I've made an attempt as per my understanding. You can add commas with custom function and replace innerdict values as needed. Hopefully this helps. Sample Code from collections import OrderedDict #Build your dict (sort of) x = ['Value1', '100000', 'Value2', '10000', 'Value3', '1000'] y = ['Value4', '2000', 'Value5', '20000', 'Value6', '200000'] z = {'X': OrderedDict([x[i:i+2] for i in range(0, len(x),2)]), 'Y': OrderedDict([y[i:i+2] for i in range(0, len(y),2)]), } #function to set commas, you can expand as needed def getNum(a): if len(a) == 5: return a[0:2] + ',' + a[2:] elif len(a) == 6: return a[0:3] + ',' + a[3:] else: return a #Add commas to inner dict for k,innerdict in z.iteritems(): for k2,v2 in innerdict.iteritems(): innerdict[k2] = getNum(v2) Result #`z` before changes &gt;&gt;&gt; {'Y': OrderedDict([('Value4', '2000'), ('Value5', '20000'), ('Value6', '200000')]), 'X': OrderedDict([('Value1', '100000'), ('Value2', '10000'), ('Value3', '1000')])} #`z` after changes {'Y': OrderedDict([('Value4', '2000'), ('Value5', '20,000'), ('Value6', '200,000')]), 'X': OrderedDict([('Value1', '100,000'), ('Value2', '10,000'), ('Value3', '1000')])} &gt;&gt;&gt;
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48066093

http://stackoverflow.com/comment/83216309
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48119844
has text: check this answer https://stackoverflow.com/a/8201281/8150371 , it is using urllib instead of requests

http://stackoverflow.com/a/48104498
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83185208
downvote count: 0
answers question: http://stackoverflow.com/q/48104460
has comment: http://stackoverflow.com/comment/83185223
type: Answer
upvote count: 2
score: 2
has body: You can avoid using selenium and use requests directly, but this would require two steps in this case - get the short URL value from the initial webpage first and then get the number of views from a separate endpoint: import re import requests pattern = re.compile(r'data-shorturl="https://r.rbc.ru/(.*?)"') with requests.Session() as session: session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'} response = session.get("https://www.rbc.ru/society/05/01/2018/5a4e9de19a7947e2bef693a1?from=main") short_url = pattern.search(response.text).group(1) response = session.get("https://www.rbc.ru/redir/stat/{short_url}".format(short_url=short_url)) data = response.json() print(data["show"]) Currently prints 7712. Note that using a regex to extract the short URL value in this case is perfectly okay, since we are not parsing HTML markup and structure with regular expressions but rather just extracting a specific part of a URL string somewhere in the document.
accepted answer of: http://stackoverflow.com/q/48104460

web-services
type: Tag
tag name: web-services
tags question: http://stackoverflow.com/q/48131837

http://stackoverflow.com/comment/82999566
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162131/discussion-between-schwobaseggl-and-stefan-pochmann).
comment on: http://stackoverflow.com/a/48015051
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83101821
comment on: http://stackoverflow.com/q/48063550
type: Comment
has text: Using python 3.6 f-string
score: 0
type: QuestionComment

http://stackoverflow.com/a/48117449
has comment: http://stackoverflow.com/comment/83214176
downvote count: 0
has comment: http://stackoverflow.com/comment/83212350
has comment: http://stackoverflow.com/comment/83214367
has comment: http://stackoverflow.com/comment/83215449
has comment: http://stackoverflow.com/comment/83211909
answers question: http://stackoverflow.com/q/48116700
has comment: http://stackoverflow.com/comment/83211756
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83215822
accepted answer of: http://stackoverflow.com/q/48116700
has comment: http://stackoverflow.com/comment/83211482
type: Answer
has body: You can do assignment in blocks, say, of 1000 rows. The additional array this creates will be 1/29 of the size of your array, and having a for loop running 29 times shouldn't be much of a speed problem. Typical memory/speed tradeoff. block = 1000 # the size of row blocks to use K = np.random.random((29000, 29000)) for i in range(int(np.ceil(K.shape[0] / block))): K[i*block:(i+1)*block, :] *= 1.5 - 0.5 * K[i*block:(i+1)*block, :]**2 Since there was some concern about the performance on smaller matrices, here is a test for those: block = 1000 K = np.arange(9).astype(np.float).reshape((3, 3)) print(1.5 * K - 0.5 * K**3) for i in range(int(np.ceil(K.shape[0] / block))): K[i*block:(i+1)*block_size, :] *= 1.5 - 0.5 * K[i*block:(i+1)*block_size, :]**2 print(K) This prints [[ 0. 1. -1.] [ -9. -26. -55.] [ -99. -161. -244.]] twice.
has comment: http://stackoverflow.com/comment/83212585
has comment: http://stackoverflow.com/comment/83211236
has comment: http://stackoverflow.com/comment/83211220
upvote count: 5
score: 5

http://stackoverflow.com/q/48150111
has comment: http://stackoverflow.com/comment/83279171
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83279204
has comment: http://stackoverflow.com/comment/83307979
has comment: http://stackoverflow.com/comment/83307869
has comment: http://stackoverflow.com/comment/83307799
type: UnansweredQuestion
tagged with: python
has body: I would like to draw a bar plot from a data frame using Matplotlib object-oriented interface. As far as I understand, Matplotlib axe.bar method only accept two arguments, x and height. Do I need to manually extract the data from the data frame, which seems to be very inefficient for a complex chart, or is there a more straightforward approach? For example, is there a way to use df.plot(kind='bar') method along with Matplotlib axe object?
answer count: 0
has comment: http://stackoverflow.com/comment/83278481
tagged with: matplotlib
type: Question
has title: Using Matplotlib object oriented interface to plot a bar chart from a data frame

http://stackoverflow.com/q/48045412
tagged with: webdriver
type: Question
has answer: http://stackoverflow.com/a/48056446
downvote count: 2
has comment: http://stackoverflow.com/comment/83062743
tagged with: firefox
has comment: http://stackoverflow.com/comment/83062079
upvote count: 3
has body: I am using this code in Python: from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary binary = FirefoxBinary(r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe') driver = webdriver.Firefox(firefox_binary=binary) driver.get("www.google.com") Unlucky, this open Firefox but not the URL (not return any error). Do you know why?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83062045
tagged with: surf
has comment: http://stackoverflow.com/comment/83061976
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83062137
score: 1
has title: Webdriver.get(url) open Firefox but not the URL
tagged with: selenium

http://stackoverflow.com/comment/83029275
score: 0
type: Comment
has text: Possible duplicate of [Trouble installing Django: Command "python setup.py egg\_info" failed with error code 1 in /tmp/pip-build-rcF9a5/Django/](https://stackoverflow.com/questions/47684498/trouble-installing-django-command-python-setup-py-egg-info-failed-with-error)
type: QuestionComment
comment on: http://stackoverflow.com/q/48028248

http://stackoverflow.com/q/48104763
tagged with: http://stackoverflow.com/tag/json
type: AnsweredQuestion
downvote count: 0
score: 1
has title: I am trying to use python's objectpath to pick specific values out of a multi-level json/dictionary, but can't get to my desired target format
favorite count: 0
tagged with: objectpath
type: Question
has answer: http://stackoverflow.com/a/48105010
tagged with: python
tagged with: dictionary
has body: Imagine I hit an API and it returns a multi-level json blob. I want to then pull specific values out of that blob and then upload it to a database, so I need to flatten it. Basically I want to move from something like this: d1 = {'results': [ {'a': 1, 'b': 10}, {'a': 2, 'b': 20}, {'a': 3, 'b': 30, 'c': {'d': 100, 'e': 1000}}, {'a': 4, 'c': {'d': 200, 'e': 2000}} ] } To something like this (ideally with the labels adjusted to represent the original hierarchy): d2 = [ {'a': 1, 'b': 10}, {'a': 2, 'b': 20}, {'a': 3, 'b': 30, 'c.d': 100}, {'a': 4, 'c.d': 200} ] I feel like jsonpath or objectpaths should be able to do this, but I haven't been able to get it to work. I could traverse this example fairly easy, but I have a bunch of these to do so something more "declarative" would be much preferable. I must be missing something on how these path things work. Here's my attempt: from objectpath import Tree # starting here... d1 = {'results': [ {'a': 1, 'b': 10}, {'a': 2, 'b': 20}, {'a': 3, 'b': 30, 'c': {'d': 100, 'e': 1000}}, {'a': 4, 'c': {'d': 200, 'e': 2000}} ] } # trying to get here... # d2 = [ # {'a': 1, 'b': 10}, # {'a': 2, 'b': 20}, # {'a': 3, 'b': 30, 'c.d': 100}, # {'a': 4, 'c.d': 200} # ] if __name__ == "__main__": t = Tree(d1) print([x for x in t.execute('$.results.a')]) # works to get value of a print([x for x in t.execute('$.results.(a,b)')]) # creates dictionary of a &amp; b -- cool print([x for x in t.execute('$.results.(a,b,c)')]) # adds all of c's sub document, makes sense print([x for x in t.execute('$.results.(a,b,c.d)')]) # nothing changed? print([x for x in t.execute('$.results.*')]) # selects everything, sure print([x for x in t.execute('$.results.*["a"]')]) # just "a" value again, makes sense print([x for x in t.execute('$.results.*["a" or "b"]')]) # apparently this means HAS "A" or "B" -- weird? print([x for x in t.execute('$.results..(a,b,d)')]) # almost works but puts d in it's own dictionary?! print([x for x in t.execute('{"a": $.results.a, "b": $.…
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/48105010

http://stackoverflow.com/q/48109228
tagged with: normalize
tagged with: python
has answer: http://stackoverflow.com/a/48109733
accepted answer: http://stackoverflow.com/a/48109361
type: AnsweredQuestion
upvote count: 10
type: Question
downvote count: 0
score: 10
has answer: http://stackoverflow.com/a/48109361
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/48109501
has title: Normalizing data to certain range of values
has body: I am a new in Python, is there any function that can do normalizing a data? For example, I have set of list in range 0 - 1 example : [0.92323, 0.7232322, 0,93832, 0.4344433] I want to normalize those all values to range 0.25 - 0.50 Thank you,
has answer: http://stackoverflow.com/a/72661104
possible better answer: http://stackoverflow.com/a/48109733

http://stackoverflow.com/comment/83093181
has text: Traceback (most recent call last): File "/Users/syam.mohan/PycharmProjects/untitled2/TEST/qqq.py", line 31, in <module> print ob.x File "/Users/syam.mohan/PycharmProjects/untitled2/TEST/qqq.py", line 15, in x return self.__x AttributeError: 'sample' object has no attribute '_sample__x'
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48060345

http://stackoverflow.com/q/48041000
tagged with: keras
favorite count: 0
tagged with: multidimensional-array
tagged with: python
has answer: http://stackoverflow.com/a/48044870
has comment: http://stackoverflow.com/comment/83067947
type: AnsweredQuestion
has title: Which shape should have input and output data for a LSTM NN?
has answer: http://stackoverflow.com/a/48044981
upvote count: 3
possible better answer: http://stackoverflow.com/a/48044870
type: Question
score: 3
has comment: http://stackoverflow.com/comment/83060833
tagged with: recurrent-neural-network
accepted answer: http://stackoverflow.com/a/48044981
answer count: 2
has body: I have a problem with the way of creating my data for a NN with a LSTM layer. I have many files containing hundreds of lines. Each file represents a song and each line represents a note with 4 values. I want the NN read the notes with a sequence of 10 notes so that it can predict the next note from them. If it is needed, we can fix the number of notes at 5000 per song. So I just want to know which shape my input and output data should have and how to define the first LSTM layer. model = Sequential() model.add(LSTM(32, input_shape=(5000, 4),return_sequences=True)) To sump up: One file has 5000 lines and 4 columns and represents 1 song. One line in a file represent one note with 4 values. Thank you for your help.
tagged with: neural-network
downvote count: 0

http://stackoverflow.com/q/48132195
type: AnsweredQuestion
has title: Can't regex over created list
type: Question
score: 4
has comment: http://stackoverflow.com/comment/83241500
has answer: http://stackoverflow.com/a/48132256
upvote count: 4
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83241539
has body: I want to: Pull number from parentheses "javascript:analysis(XXXXXXX)" for each game Create a list with direct hyperlinks like: http://www.nowgoal.cc/analysis/XXXXXXX.html Many many more... Code: import bs4 as bs import sys import re from PyQt5.QtWebEngineWidgets import QWebEnginePage from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QUrl class Page(QWebEnginePage): def __init__(self, url): self.app = QApplication(sys.argv) QWebEnginePage.__init__(self) self.html = '' self.loadFinished.connect(self._on_load_finished) self.load(QUrl(url)) self.app.exec_() def _on_load_finished(self): self.html = self.toHtml(self.Callable) print('READY!') def Callable(self, html_str): self.html = html_str self.app.quit() def main(): page = Page('http://www.nowgoal.cc/') soup = bs.BeautifulSoup(page.html, 'html.parser') lista = [] for x in soup.find_all("a", attrs={'title' : 'Match analyze'}): lista.append(x) for element in lista: z = re.search(r"\((.......\))",element) if z: print(z.groups()) if __name__ == '__main__': main() Python yields: TypeError: expected string or bytes-like object I struggle with this for a few days now, don't have more ideas to fix this. I digged and tried, searched and ended clueless. I really want to write more code and develop my idea. Please help, I'm dying here.
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48132256

http://stackoverflow.com/comment/83131709
comment on: http://stackoverflow.com/a/48078169
score: 0
type: AnswerComment
has text: @jezrael I have sent you the file.
type: Comment

http://stackoverflow.com/a/48134018
has comment: http://stackoverflow.com/comment/83249157
upvote count: 4
has body: Following may help you in same. subprocess.check_call('netsh advfirewall show allprofiles')
type: AcceptedAnswer
downvote count: 0
score: 4
accepted answer of: http://stackoverflow.com/q/48133905
type: Answer
answers question: http://stackoverflow.com/q/48133905
has comment: http://stackoverflow.com/comment/83248511
has comment: http://stackoverflow.com/comment/83245828
has comment: http://stackoverflow.com/comment/83248731
has comment: http://stackoverflow.com/comment/83245944

http://stackoverflow.com/comment/83172689
type: Comment
score: 4
comment on: http://stackoverflow.com/q/48098845
type: QuestionComment
has text: But this is `fetchone`...

http://stackoverflow.com/a/48115826
answers question: http://stackoverflow.com/q/48115573
type: Answer
has body: So considering there isn't too much information, I'll take a stab at the fact you have possibly used the name of Series and already given it the data type of Integer... Restart your interpreter or tell us the type of Series... Make sure you are not assigning an integer to Series.
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48115573
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83217973
type: Comment
comment on: http://stackoverflow.com/q/48120682
has text: doesn't seem like a python question. But if you use `$FILES` within simple quotes, that won't be evaluated. You could try `sed 's/\$/\$($FILES)/' test.txt > test5000.txt`
score: 0
type: QuestionComment

http://stackoverflow.com/q/48132807
has body: I can't really understand why this is not working, basically I'm trying to retrieve values for m and q just to print them but I always get [nan, nan] import tensorflow as tf import pandas as pd import matplotlib.pyplot as plt m = tf.Variable(tf.random_uniform(shape=()), dtype=tf.float32) q = tf.Variable(tf.random_uniform(shape=()), dtype=tf.float32) X = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) linear_model = m * X + q cost = tf.reduce_sum(tf.square(linear_model - y)) optimizer = tf.train.GradientDescentOptimizer(0.01) gdescent = optimizer.minimize(cost) train, test = [pd.read_csv(file) for file in ["train.csv", "test.csv"]] if False: # Scatter training points plt.scatter(train['x'], train['y'], s=1) plt.show() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) _, m, q = sess.run([gdescent, m, q], feed_dict={X: train['x'].values, y: train['y'].values}) print(m, q) train.csv and test.csv are both files with a header line and two columns of values, x and y First 10 lines of train.csv x,y 24,21.54945196 50,47.46446305 15,17.21865634 38,36.58639803 87,87.28898389 36,32.46387493 12,10.78089683 81,80.7633986 25,24.61215147
tagged with: deep-learning
has answer: http://stackoverflow.com/a/48133079
answer count: 1
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/83242966
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83242783
has comment: http://stackoverflow.com/comment/83242820
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/48133079
has comment: http://stackoverflow.com/comment/83242972
has comment: http://stackoverflow.com/comment/83242900
has title: Why does tensor flow return NaN when running variables after training?
score: 0

kivy
tags question: http://stackoverflow.com/q/48042935
tags question: http://stackoverflow.com/q/48035716
type: Tag
tags question: http://stackoverflow.com/q/48125698
tags question: http://stackoverflow.com/q/48065970
tags question: http://stackoverflow.com/q/48030469
tags question: http://stackoverflow.com/q/48030993
tags question: http://stackoverflow.com/q/48138348
tags question: http://stackoverflow.com/q/48046985
tags question: http://stackoverflow.com/q/48023605
tags question: http://stackoverflow.com/q/48108800
tags question: http://stackoverflow.com/q/48140520
tags question: http://stackoverflow.com/q/48035979
tags question: http://stackoverflow.com/q/48075585
tags question: http://stackoverflow.com/q/48132151
tags question: http://stackoverflow.com/q/48022075
tags question: http://stackoverflow.com/q/48062300
tags question: http://stackoverflow.com/q/48087638
tags question: http://stackoverflow.com/q/48083856
tags question: http://stackoverflow.com/q/48039997
tags question: http://stackoverflow.com/q/48121487
tags question: http://stackoverflow.com/q/48133520
tags question: http://stackoverflow.com/q/48141004
tags question: http://stackoverflow.com/q/48083420
tags question: http://stackoverflow.com/q/48043228
tag name: kivy
tags question: http://stackoverflow.com/q/48113748
tags question: http://stackoverflow.com/q/48030230
tags question: http://stackoverflow.com/q/48016090
tags question: http://stackoverflow.com/q/48076593
tags question: http://stackoverflow.com/q/48039728
tags question: http://stackoverflow.com/q/48021882
tags question: http://stackoverflow.com/q/48103771
tags question: http://stackoverflow.com/q/48148123
tags question: http://stackoverflow.com/q/48024654
tags question: http://stackoverflow.com/q/48098611
tags question: http://stackoverflow.com/q/48078820
tags question: http://stackoverflow.com/q/48090839
tags question: http://stackoverflow.com/q/48050833
tags question: http://stackoverflow.com/q/48072091

http://stackoverflow.com/comment/83241872
type: QuestionComment
has text: my workbook file size consists of 600 sheets that mean I am gonna split each file to 600 files then merge the 600 CSV files would it be possible ??!!
score: 0
comment on: http://stackoverflow.com/q/48132290
type: Comment

header
type: Tag
tags question: http://stackoverflow.com/q/48025088
tags question: http://stackoverflow.com/q/48053207
tag name: header

http://stackoverflow.com/comment/83077164
type: Comment
has text: Thanks! I tried that but it doesn't seem to solve the problem.
score: 0
comment on: http://stackoverflow.com/q/48052478
type: QuestionComment

http://stackoverflow.com/comment/83101063
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48032532
has text: @newpyguy No problem. Please consider selecting it as the correct answer. Thanks and Happy New Year!
score: 0

http://stackoverflow.com/comment/83233769
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48127116
has text: Does transaction.atomic roll back if the exception thrown isn't a `DatabaseError` or its subclass? With regard to validating first and saving second, I don't actually know how big the tree is in advance (just that it's one branch deep, in my case, but I don't know how many branches), so I'd have to record the tree structure while validating. Additionally, not all leaves are the same `model` type. I think recursive saving is more readable under those circumstances.
type: AnswerComment

http://stackoverflow.com/q/48088490
downvote count: 1
has answer: http://stackoverflow.com/a/48089360
type: Question
has comment: http://stackoverflow.com/comment/83151783
has comment: http://stackoverflow.com/comment/83151638
score: -1
linked to: http://stackoverflow.com/q/23946933
has comment: http://stackoverflow.com/comment/83151859
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83151627
linked to: http://stackoverflow.com/q/20090495
has comment: http://stackoverflow.com/comment/83151662
answer count: 2
has comment: http://stackoverflow.com/comment/83151686
linked to: http://stackoverflow.com/q/45621722
tagged with: indentation
upvote count: 0
has answer: http://stackoverflow.com/a/48088595
favorite count: 0
duplicate of: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/83151681
has comment: http://stackoverflow.com/comment/136936628
tagged with: python
tagged with: nano
linked to: http://stackoverflow.com/q/34559358
has comment: http://stackoverflow.com/comment/83151644
has body: Hello I am having an indentation error on python 2.7 My program looks like this: import sys, os import subprocess from threading import Thread from re import split def GetProcesses(Clean=True): # if Clean == True: # # x = subprocess.Popen(["sudo", "ps", "aux"], stdout=subprocess.PIPE, shell=True) (out, err) = x.communicate() print(out) print(out.split("\n")) print("--------------") Processes = out.split("\n") print(Processes) print("------") print(Processes[0]) print("----------") Header = Processes[0] Process_list = Processes.remove(Processes[0]) return((Header, Process_list)) # else: # # if Clean == True: #added problem so future SE users can see it x = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE, shell=True) (out, err) = x.communicate() return(out) I am not understanding the error, I have tried de-denting everyline 1 space, indenting back to the originals, and adding 1 space but it always says that it either expects an indent, or unexpected indent. P.S I am using only spaces. Actual Error: File "MemoryHandling.py", line 31 x = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE, shell=True) ^ IndentationError: expected an indented block I have check several online questions/sources (mainly SE) for this error (below) both during and before asking this question, i found that they were case specific, downvoted / not answered, or were not usefull: -- Python Indentation Error # i am using spaces -- Python 2.7 Indentation error # i have manually checked indentation multiple times, and tried using the tab key -- Unexpected indentation error, but indentation looks correct # once again not using tabs and spaces -- Code Indent Error, code is indented? # not answered (bug?) -- Python Indentation Error when there is no indent error # once more not using tabs and spaces
has title: Why did I get this indentation Error in python 2.7?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83151722
accepted answer: http://stackoverflow.com/a/48088595
has comment: http://stackoverflow.com/comment/83151743
linked to: http://stackoverflow.com/q/29416297
possible better answer: http://stackoverflow.com/a/48089360

http://stackoverflow.com/q/48100587
has comment: http://stackoverflow.com/comment/83176432
has comment: http://stackoverflow.com/comment/83176987
type: Question
tagged with: python-itertools
has answer: http://stackoverflow.com/a/48104495
accepted answer: http://stackoverflow.com/a/48104495
has title: Selected combinations between the values of two lists
upvote count: 2
has comment: http://stackoverflow.com/comment/83177131
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83176505
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83177017
tagged with: python
has comment: http://stackoverflow.com/comment/83177361
has body: I have two lists a and b. Then I try to find all three-element combinations between the values of the lists, and only those in which there are values from the list b. For now I do it in the following way: import itertools as it a = [1,2,3,4] b = [5,6] for i in range(len(b)): a.append(b[i]) c = [] for j in it.combinations(a, 3): if 5 in j or 6 in j: c.append(list(j)) # output: # [[1, 2, 5], [1, 2, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [1, 5, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6], [2, 5, 6], [3, 4, 5], [3, 4, 6], [3, 5, 6], [4, 5, 6]] Unfortunately, with large lists, this is an ineffective way, because the condition of existence of elements from the list b is located behind a loop with the functionit.combinations, which in such a system is executed entirely regardless of the condition. What in the case of large lists heavily overloads the calculation. Is it possible to obtain such a result differently?
tagged with: combinations
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83176529
score: 1

http://stackoverflow.com/comment/83200265
type: QuestionComment
score: 2
has text: Move `print(password)` out of that inner loop.
type: Comment
comment on: http://stackoverflow.com/q/48112343

http://stackoverflow.com/q/48060097
tagged with: python
tagged with: excel
score: 2
has comment: http://stackoverflow.com/comment/83099478
has body: Scenario: I am trying to run a python script from a vba code in excel. The code runs with no errors, but yields no results whatsoever. Code in VBA: Private Sub CommandButton1_Click() Dim Ret_Val Dim args As String args = "\\X\s\D\D\Data_manager.py" Ret_Val = Shell("C:\Users\D\AppData\Local\Continuum\anaconda2\python.exe" &amp; " " &amp; args, vbNormalFocus) 'also tried this, same result Ret_Val = Shell("C:\Users\D\AppData\Local\Continuum\anaconda2\python.exe \\X\s\D\D\Data_manager.py") End Sub Question: I ran this same code a couple of months ago and it worked just fine, but now, for some reason it is behaving weirdly. Any ideas on what might be happening? OBS1: I also read other posts in SO with similar problems, but for those, VBA seems to be throwing an error, which is something that does not happen in my code. OBS2: I know the code is not yielding any result, because my python script is pretty simple, it asks for a couple of inputs and outputs them to a csv file.
type: Question
has comment: http://stackoverflow.com/comment/83098747
has answer: http://stackoverflow.com/a/48078393
has comment: http://stackoverflow.com/comment/83096447
answer count: 1
downvote count: 0
tagged with: vba
has title: Running a python script from VBA
linked to: http://stackoverflow.com/q/18135551
has comment: http://stackoverflow.com/comment/83096910
favorite count: 0
has comment: http://stackoverflow.com/comment/83098800
upvote count: 2
has comment: http://stackoverflow.com/comment/83099003
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83129271

http://stackoverflow.com/a/48123813
has comment: http://stackoverflow.com/comment/83224678
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/83224698
has comment: http://stackoverflow.com/comment/83225231
has comment: http://stackoverflow.com/comment/83224742
has comment: http://stackoverflow.com/comment/83244395
has comment: http://stackoverflow.com/comment/83224830
upvote count: 3
has body: Something like df1=df.groupby('donorID').apply(lambda x : x.groupby(x.recipientID).year.nunique().gt(1).sum()) df1 Out[102]: donorID 101 2 102 0 103 1 dtype: int64 To get the dataframe df1.to_frame('num_donation_2_years').reset_index() Out[104]: donorID num_donation_2_years 0 101 2 1 102 0 2 103 1 As Dark mention do not using apply This is the update df1=df.groupby(['donorID','recipientID']).year.nunique().gt(1).sum(level=0) df1 Out[109]: donorID 101 2.0 102 0.0 103 1.0 Name: year, dtype: float64 df1.to_frame('num_donation_2_years').reset_index() Out[104]: donorID num_donation_2_years 0 101 2 1 102 0 2 103 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48123740
answers question: http://stackoverflow.com/q/48123740
has comment: http://stackoverflow.com/comment/83244221
has comment: http://stackoverflow.com/comment/83224728
type: Answer
has comment: http://stackoverflow.com/comment/83224688

http://stackoverflow.com/a/48160518
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48156089
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48156089
has body: The program is doing what you told it: Move only if the y-position is between 20 and 680. If it's less than 20, this condition won't be True and the circle won't be able move anymore. # You only move if this is True. if 20 &lt; CaptainY &lt; 680: Instead of stopping the movement, you should just move the position back, so that the circle ends up on the screen. Here's a complete example with a few more changes: import pygame # Avoid * imports, since they make code harder to read and cause bugs. pygame.init() screen = pygame.display.set_mode((1000, 700)) HEIGHT = screen.get_height() BLACK = (0,0,0) WHITE = (255,255,255) clock = pygame.time.Clock() # Use a clock to limit the frame rate. running = True captain_y = 350 captain_radius = 15 while running: # Handle events. for evnt in pygame.event.get(): if evnt.type == pygame.QUIT: running = False elif evnt.type == pygame.KEYDOWN: if evnt.key == pygame.K_ESCAPE: running = False # To see if a key is being held down, use `pygame.key.get_pressed()`. pressed_keys = pygame.key.get_pressed() # Move if up or down keys are pressed. if pressed_keys[pygame.K_UP]: captain_y -= 5 elif pressed_keys[pygame.K_DOWN]: captain_y += 5 # Update the game. # Reset the position if the circle is off screen. if captain_y - captain_radius &lt;= 0: captain_y = 0 + captain_radius elif captain_y + captain_radius &gt;= HEIGHT: captain_y = HEIGHT - captain_radius # Draw everything. screen.fill(BLACK) pygame.draw.circle(screen, WHITE, (950, captain_y), captain_radius) pygame.display.flip() clock.tick(60) # Cap the frame rate at 60 fps. pygame.quit()
type: AcceptedAnswer

matplotlib
tags question: http://stackoverflow.com/q/48060986
tags question: http://stackoverflow.com/q/48151629
tags question: http://stackoverflow.com/q/48120501
tags question: http://stackoverflow.com/q/48077655
tags question: http://stackoverflow.com/q/48065567
tags question: http://stackoverflow.com/q/48062499
tags question: http://stackoverflow.com/q/48125753
tags question: http://stackoverflow.com/q/48150111
tags question: http://stackoverflow.com/q/48015378
tags question: http://stackoverflow.com/q/48165378
tags question: http://stackoverflow.com/q/48162312
tags question: http://stackoverflow.com/q/48157735
tags question: http://stackoverflow.com/q/48105410
tags question: http://stackoverflow.com/q/48081854
tags question: http://stackoverflow.com/q/48137724
tags question: http://stackoverflow.com/q/48039312
tags question: http://stackoverflow.com/q/48053484
tags question: http://stackoverflow.com/q/48014789
tags question: http://stackoverflow.com/q/48108582
tags question: http://stackoverflow.com/q/48061554
tags question: http://stackoverflow.com/q/48106135
tags question: http://stackoverflow.com/q/48090691
tags question: http://stackoverflow.com/q/48130290
tags question: http://stackoverflow.com/q/48031442
tags question: http://stackoverflow.com/q/48064921
tags question: http://stackoverflow.com/q/48066337
tags question: http://stackoverflow.com/q/48027155
tags question: http://stackoverflow.com/q/48115159
tags question: http://stackoverflow.com/q/48093361
tags question: http://stackoverflow.com/q/48071624
tag name: matplotlib
tags question: http://stackoverflow.com/q/48172881
tags question: http://stackoverflow.com/q/48066848
tags question: http://stackoverflow.com/q/48123231
tags question: http://stackoverflow.com/q/48166461
tags question: http://stackoverflow.com/q/48048135
tags question: http://stackoverflow.com/q/48027833
tags question: http://stackoverflow.com/q/48141626
tags question: http://stackoverflow.com/q/48035152
tags question: http://stackoverflow.com/q/48152402
tags question: http://stackoverflow.com/q/48028404
tags question: http://stackoverflow.com/q/48081418
tags question: http://stackoverflow.com/q/48088669
tags question: http://stackoverflow.com/q/48030937
tags question: http://stackoverflow.com/q/48126330
tags question: http://stackoverflow.com/q/48152754
tags question: http://stackoverflow.com/q/48029530
tags question: http://stackoverflow.com/q/48128261
tags question: http://stackoverflow.com/q/48171887
tags question: http://stackoverflow.com/q/48125674
tags question: http://stackoverflow.com/q/48160616
tags question: http://stackoverflow.com/q/48065878
tags question: http://stackoverflow.com/q/48099776
tags question: http://stackoverflow.com/q/48051678
tags question: http://stackoverflow.com/q/48117149
tags question: http://stackoverflow.com/q/48022090
tags question: http://stackoverflow.com/q/48020122
tags question: http://stackoverflow.com/q/48162182
tags question: http://stackoverflow.com/q/48035641
tags question: http://stackoverflow.com/q/48083936
tags question: http://stackoverflow.com/q/48148874
tags question: http://stackoverflow.com/q/48140977
tags question: http://stackoverflow.com/q/48168880
tags question: http://stackoverflow.com/q/48026056
tags question: http://stackoverflow.com/q/48159441
tags question: http://stackoverflow.com/q/48172928
tags question: http://stackoverflow.com/q/48097995
tags question: http://stackoverflow.com/q/48132155
tags question: http://stackoverflow.com/q/48014713
tags question: http://stackoverflow.com/q/48135100
tags question: http://stackoverflow.com/q/48043008
tags question: http://stackoverflow.com/q/48145811
tags question: http://stackoverflow.com/q/48100608
tags question: http://stackoverflow.com/q/48045888
tags question: http://stackoverflow.com/q/48104082
tags question: http://stackoverflow.com/q/48050915
tags question: http://stackoverflow.com/q/48114473
tags question: http://stackoverflow.com/q/48076341
tags question: http://stackoverflow.com/q/48066779
tags question: http://stackoverflow.com/q/48044297

http://stackoverflow.com/comment/83000866
has text: Abs - do you mean indenting for the Python code? then ye this is how it looks. i'm very new to python so not sure how to use the resp.json call but i'll look into it. Barmar - value['dist'] doesn't give me anything it errors out - as mentioned anything under "StrikeData" i cant seem to call. SCB - i haven't added the condition in yet for the 40 distance but thats what i want to achieve once i can call the dist data
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48015536

http://stackoverflow.com/a/48036961
has comment: http://stackoverflow.com/comment/126757137
downvote count: 0
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/126763728
answers question: http://stackoverflow.com/q/48036946
upvote count: 5
has body: You are confusing expressions with assignment. Getting values (reading) is handled differently from setting values (writing). Assignment (setting) re-uses syntax to specify a target. In an assignment like a[:] = ..., a[:] is a target to which the assignment takes place. Using a[:] in an expression produces a new list. In other words: you have two different language statements, that are deliberately using the same syntax. They are still distinct however. See the Assignment statements reference documentation: assignment_stmt ::= (target_list "=")+ (starred_expression | yield_expression) target_list ::= target ("," target)* [","] target ::= identifier | "(" [target_list] ")" | "[" [target_list] "]" | attributeref | subscription | slicing | "*" target [...] If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it. (Bold emphasis mine). Compare this with the Slicings section in the expressions reference documentation; slicing in an expression produces a slice() object, which the list.__getitem__ method interprets as a request for a new list object with the matching indices copied over. Other object types can choose to interpret a slice object differently. Note that there is a third operation, the del statement to delete references, including…
type: Answer
accepted answer of: http://stackoverflow.com/q/48036946

http://stackoverflow.com/comment/83036000
has text: Hi @Simon , first info (I am using Python 3.6, Cx_Freeze 5.1.1, Win7 64bit). When I tested the script before freezing it I kept looking on the terminal and there was no error or traceback, it just works. After I freeze it, clicking on button 1 it reads the content of the file but if I write in the Entry field and click button 2 it seems to have no effect, the file is simply unchanged. I even tried to install to freeze it on a different pc and it doesn't work either. I'm running out of ideas...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48026079
score: 0

http://stackoverflow.com/comment/83101676
comment on: http://stackoverflow.com/q/48063550
type: Comment
type: QuestionComment
has text: How can you get those results? Shouldn't the last print line be something like `'generator num: {} lenght: {}'.format(index, len([i for i in lengh]))`?
score: 0

http://stackoverflow.com/comment/83261434
type: Comment
has text: How about having 2 accounts, or 2 shell shortcuts that have paths to the different pythons?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48141731

http://stackoverflow.com/comment/83219193
has text: have you tried to install igraph with homebrew and then `pip install python-igraph`? It described in [official guide for mac os](http://igraph.org/python/)
score: 2
comment on: http://stackoverflow.com/q/48120881
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48052426
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/83091999
score: 0
answer count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/48063385
has body: I am trying to use lmfit, but getting sporadic results for the parameters: import numpy as np import scipy.stats as sp from scipy.optimize import curve_fit from lmfit import minimize, Parameters, Parameter, report_fit x = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.99999999,] #some paramters to try to estimate sigma1 = 6 scale1 = np.exp(5) #generate values to use to fit y = sp.lognorm(sigma1,scale=scale1).ppf(x) #function set-up to use in lmfit def invlognorm(params,x,data): sigma = params['sigma'] mu = params['mu'] model = sp.lognorm(sigma,scale=mu).ppf(x) return model - data params = Parameters() params.add('sigma', value= 1,) params.add('mu', value= 1, ) # do fit, here with leastsq model result = minimize(invlognorm,params, method = 'least-squares',args=(x, y)) and finally checking the results result.params.pretty_print() Name Value Min Max Stderr Vary Expr Brute_Step mu 2.161 -inf inf None True None None sigma 6.754 -inf inf None True None None but these are nowhere near the original values. Any help on what's going on here and how I can fix this so it gives reasonable results?
tagged with: python
has title: Python - Using lmfit to fit a function
has answer: http://stackoverflow.com/a/48063385
type: AnsweredQuestion

http://stackoverflow.com/q/48076341
tagged with: scatter-plot
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/17925545
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/31684448
has title: How can I match the Z ticklabels' color to the scatterpoints color?
has answer: http://stackoverflow.com/a/48171576
type: Question
has body: EDIT: THe issue was solved by using a loop for i, x in enumerate(plt.cm.jet(np.linspace(0,1,N))): plt.gca().get_zticklabels()[i].set_color(x) where plt.cm.jet(np.linspace(0,1,N)) is used color palette How can I match the Z ticklabels' color to the scatterpoints color? I made a custom 3d Axis by merging these two answers together: How to color a specific gridline/tickline in 3D Matplotlib Scatter Plot figure?? for the grid line color and https://stackoverflow.com/a/17927118/8881965 for the override _axinfo attribute import numpy as np from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.axis3d import Axis import matplotlib.pyplot as plt import matplotlib.projections as proj from matplotlib.colors import colorConverter custom_AXINFO = { 'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2), #empty plane 'color': (0, 0, 0)}, 'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2), #date plane 'color': (0.756, 0.145, 0.184)}, 'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1), 'color': (0.835, 0.549, 0.164)},} #bottom plane class axis3d_custom(Axis): def __init__(self, adir, v_intervalx, d_intervalx, axes, *args, **kwargs): Axis.__init__(self, adir, v_intervalx, d_intervalx, axes, *args, **kwargs) self.gridline_colors = [] def set_gridline_color(self, *gridline_info): '''Gridline_info is a tuple containing the value of the gridline to change and the color to change it to. A list of tuples may be used with the * operator.''' self.gridline_colors.extend(gridline_info) def draw(self, renderer): # filter locations here so that no extra grid lines are drawn Axis.draw(self, renderer) which_gridlines = [] if self.gridline_colors: locmin, locmax = self.get_view_interval() if locmin &gt; locmax: locmin, locmax = locmax, locmin # Rudimentary clipping majorLocs = [loc for loc in self.major.locator() if locmin &lt;= loc &lt;= locmax] for i, val in enumerate(majorLocs): for colored_val, color in self.gridline_colors: if val == colored_val: which_gridlines.append((i, color)) colors = …
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/83126433

http://stackoverflow.com/q/48046518
has comment: http://stackoverflow.com/comment/83064443
downvote count: 0
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48046535
has title: How to get rid of the BeautifulSoup html parser error when I'm not using BeautifulSoup
has comment: http://stackoverflow.com/comment/83064439
upvote count: 1
type: Question
has body: I'm going to be making a dictionary program with a GUI but I fell at the first hurdle. I just installed a module (PyDictionary) but when I run the following code I get an error. from PyDictionary import PyDictionary dictionary = PyDictionary() print(dictionary.meaning("fish")) Which returns The code that caused this warning is on line 3 of the file Dictionary.py. To get rid of this warning, change code that looks like this: BeautifulSoup(YOUR_MARKUP}) to this: BeautifulSoup(YOUR_MARKUP, "lxml") markup_type=markup_type)) {'Noun': ['any of various mostly cold-blooded aquatic vertebrates usually having scales and breathing through gills', 'the flesh of fish used as food', '(astrology', 'the twelfth sign of the zodiac; the sun is in this sign from about February 19 to March 20'], 'Verb': ['seek indirectly', 'catch or try to catch fish or shellfish']}
score: 1
accepted answer: http://stackoverflow.com/a/48046535

http://stackoverflow.com/comment/83056272
has text: I'm just about to do that @Cleb
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48037509
score: 1

http://stackoverflow.com/comment/83134263
comment on: http://stackoverflow.com/q/48079327
score: 0
type: Comment
type: QuestionComment
has text: Might also be worth taking a look at the [cmd](https://docs.python.org/3/library/cmd.html) module, this makes it easy to write line-based interpreters (e.g. you would start your script, then just type commands to pass to it).

http://stackoverflow.com/a/48163465
answers question: http://stackoverflow.com/q/48161676
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83327153
downvote count: 0
has body: try this urls.py in mysite urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('anomaly.urls',namespace='anomaly')) To qualify a url name with a namespace use the syntax 'namespace:name' &lt;form action="{% url 'anomaly:upload_csv' %}" method="POST" enctype="multipart/form-data" class="form-horizontal"&gt;
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/83327131
upvote count: 5
has comment: http://stackoverflow.com/comment/83328318
accepted answer of: http://stackoverflow.com/q/48161676

http://stackoverflow.com/comment/83002122
type: Comment
comment on: http://stackoverflow.com/q/48016382
score: 0
has text: Possible duplicate of [How do I validate a date string format in python?](https://stackoverflow.com/questions/16870663/how-do-i-validate-a-date-string-format-in-python)
type: QuestionComment

snappy
type: Tag
tags question: http://stackoverflow.com/q/48016126
tag name: snappy

http://stackoverflow.com/q/48097015
tagged with: networkx
type: Question
tagged with: graph-theory
has comment: http://stackoverflow.com/comment/83184051
has comment: http://stackoverflow.com/comment/83184843
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/83194930
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Python Networkx Implementing Cyclic Directed Graph
answer count: 0
tagged with: cyclic-graph
has comment: http://stackoverflow.com/comment/83188483
has body: I’m trying to find all paths through the following cyclic directed graph. I would like to be able to include the paths which pass through the cycles once, but not include the possibility of infinitely cycling through one path. Start -&gt; [1]; 1 -&gt; [2]; 2 -&gt; [3, 4]; 3 -&gt; [6]; 4 -&gt; [7]; 5 -&gt; [3,8]; 6 -&gt; [5,8]; 7 -&gt; [10]; 8 -&gt; [9]; 9 -&gt; [End]; 10 -&gt; [8]. I have found all of the simple paths, however, there are three more paths which do not repeat the cycles, however, are able to travel through a cycle once. I would like to be able to find these, using Python?? I have included the code developed to date below. import networkx as nx #Build a dummy dictionary to represent a graph, nodes as keys, edges to the node as paired arrays #Page 1 Demo_Bussines_Process_Diagram = {"Start" : ["1"], "1":["2"], "2":["3","4"], "3":["6"], "4":["7"], "5":["3","8"], "6":["5","8"], "7":["10"],"8":["9"],"9":["End"],"10":["8","4"]} #Build an empty directed graph Business_Process = nx.MultiDiGraph() #place each node into the graph, unconnected for node in Demo_Bussines_Process_Diagram: Business_Process.add_node(node) #Build the edges between the nodes of the graph for source_node in Demo_Bussines_Process_Diagram: for edge_node in Demo_Bussines_Process_Diagram[source_node]: Business_Process.add_edge(source_node,edge_node,weight=1) #Freeze the diagram, locking down any possible modifications nx.freeze(Business_Process) #Calculate the order (total nodes) order = Business_Process.order() print("Total nodes in the graph =", order) #Find all of the edges in the proces total_edges = Business_Process.edges() print("Total conections in the graph =", len(total_edges)) #Find all decisions in the diagram Decisions = {} for node in Business_Process: if Business_Process.out_degree(node)&gt;1: Decisions[node] = [Business_Process.out_degree(node),Business_Process.out_edges(node)] print("Total decisions =",len(Decisions)) #Find all cycles cycles = nx.simple_cycles(Business_Proces…

http://stackoverflow.com/comment/83235816
has text: Thanks, I think the buffer reader should do, question though. In my case I am retrieving data from the stream to append to a listview, with that in mind woulld it be wiser to go with ths or the RxJava solution proposed in a comment on the question
type: Comment
comment on: http://stackoverflow.com/a/48122597
score: 0
type: AnswerComment

http://stackoverflow.com/q/48075406
type: Question
tagged with: robotframework
answer count: 1
linked to: http://stackoverflow.com/q/1517616
has title: Robot Framework urlopen option
score: 0
type: UnansweredQuestion
has body: I'm using robot framework as a testing framework. one of my usecases is to upload a zip file using POST request. I created the right command for uploading a local file, it works perfectly. However, I want to take it to a bit more flexible approach. Instead of download the file to my computer and uploading it, I want to give a URL with holds the file I'm about to upload. Meaning, giving it the url http://X.X.X.X/test.zip. My main problem is that I need to figure out a way to read the binary chunk and send it to the API. In python it's easy doing it with using urlopen (Stream large binary files with urllib2 to file), but I didn't found any way of doing it in robot. Do you have any idea?
tagged with: python
has answer: http://stackoverflow.com/a/48099815

http://stackoverflow.com/a/48094658
answers question: http://stackoverflow.com/q/48094617
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48094617
downvote count: 0
has body: if instance.physical_server == None: This won't work, because instance.physical_server will raise an exception if that instance does not have a related PhysicalServer You can fix the problem by changing your check to: if hasattr(instance, 'physical_server'): See the docs on one-to-one relationships for more info.
type: AcceptedAnswer
type: Answer
score: 6

http://stackoverflow.com/q/48169414
has comment: http://stackoverflow.com/comment/83318366
tagged with: python
favorite count: 0
has title: how to check if a positional element in a list of lists does not exist in another list of lists
tagged with: list
has body: I'm trying to find a reliable way to check if a positional list element in a list2 (all same length) does not exist in any i for i in list1? This looks like the opposite of what I need: How to check if one of the following items is in a list? &gt;&gt;&gt; list1 = [('1', '2', '3'), ('a', 'b', 'c'), ('4', '5', '6')] &gt;&gt;&gt; list2 = [('a', 'b', 'c'), ('m', 'n', 'b'), ('p', 'q', '6')] &gt;&gt;&gt; print(any(z in [i[2] for i in list1] for z in [z for x,y,z in list2])) True Ideally I want ('m','n,'b') of list2 because 'b' is not found in any 3rd element of list1, so how do I segregate it out? Instead of 'any' I am looking for this sort of pseudo code: print x,y,z from list2 if 'z' is not found in any 3rd position element in all the lists present in "list1"
has answer: http://stackoverflow.com/a/48169490
accepted answer: http://stackoverflow.com/a/48169490
upvote count: 1
downvote count: 1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/740287
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/83318423
score: 0
has comment: http://stackoverflow.com/comment/83318293

http://stackoverflow.com/q/48038883
type: Question
score: 3
has answer: http://stackoverflow.com/a/48038945
has answer: http://stackoverflow.com/a/48039081
has comment: http://stackoverflow.com/comment/83048203
answer count: 3
downvote count: 0
favorite count: 0
tagged with: tuples
has answer: http://stackoverflow.com/a/48038899
tagged with: python
accepted answer: http://stackoverflow.com/a/48038899
type: AnsweredQuestion
tagged with: list
upvote count: 3
has body: I have been studying the Tensorflow API written in Python. I have two questions. 1. Can we always use a list type as a function parameter when a tuple is expected? If we look at the official API definition about the tf.placeholder and its examples (https://www.tensorflow.org/api_docs/python/tf/placeholder), we see that the second parameter of this function is the "shape". In the example code, we can see that a tuple is used to provide the shape information as a parameter as shown below. x = tf.placeholder(tf.float32, shape=(1024, 1024)) However, in the official tutorial page (https://www.tensorflow.org/get_started/mnist/beginners), the example uses the list as the shape rather than using the tuple as shown below. y_ = tf.placeholder(tf.float32, [None, 10]) I know that there are some differences between list and tuple such as being immutable vs mutable. If the list supports all the functionality of a tuple, then could we always use the list instead of the tuple safely as a function parameter? And is it recommended? 2. What's the meaning of [None, 10] in the above example code? In the above example code, [None, 10] is used. Are such expressions normally used? If so, then is "None" also considered as a kind of number?
has title: Could we always use the list type as the function parameter when the tuple type parameter is expected?
tagged with: tensorflow
possible better answer: http://stackoverflow.com/a/48038945

http://stackoverflow.com/comment/83096500
has text: @bergi https://stackoverflow.com/a/35897601/8641677 No algorithm :(
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48060738
score: 0

python-module
tags question: http://stackoverflow.com/q/48038180
type: Tag
tag name: python-module
tags question: http://stackoverflow.com/q/48061206

http://stackoverflow.com/comment/83132883
comment on: http://stackoverflow.com/a/48079514
score: 0
has text: No unfortunately its not.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48167361
favorite count: 0
tagged with: python-3.x
upvote count: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/48167759
type: AnsweredQuestion
has title: Why do I get an overflow error multiplying Numpy product outputs?
has body: I've encountered an overflow warning as a result of multiplying the output of Numpy products that I'm looking to understand. A simplified version of their actual use within my larger project is detailed below: import numpy as np class MyClass(object): def __init__(self, array_1, array_2): # Assigning arrays to be used in later methods self.array_1 = array_1 self.array_2 = array_2 # Assigning some scaling factors to be used in later methods. self.value_1 = np.prod(self.array_1.shape) self.value_2 = np.prod(self.array_2.shape) print("Numpy Product Assignment: {0}, {1}".format(self.value_1, self.value_2)) # Alternative assignment of scaling factors self.alt_value_1 = self.array_1.shape[0] * self.array_1.shape[1] self.alt_value_2 = self.array_2.shape[0] * self.array_2.shape[1] print("Regular Product Assignment: {0}, {1}".format(self.alt_value_1, self.alt_value_2)) pass def mymethod(self): print("Direct Multiplication: {0}".format(80160 * 262144)) print("Numpy Product Multiplication: {0}".format(self.value_1 * self.value_2)) print("Regular Product Multiplcation {0}".format(self.alt_value_1 * self.alt_value_2)) if __name__ == '__main__': test_array_1 = np.zeros([512, 512], dtype=complex) test_array_2 = np.zeros([1002, 80], dtype=complex) test_class = MyClass(test_array_1, test_array_2) test_class.mymethod() Including the use with the class structure for completeness, though heavily edited down to the bare minimum. If I run this code (on Python 3.6.0) I get the following output: C:/somepath/scratch.py:247: RuntimeWarning: overflow encountered in long_scalars print("Numpy Product Multiplication: {0}".format(self.value_1 * self.value_2)) Numpy Product Assignment: 262144, 80160 Regular Product Assignment: 262144, 80160 Direct Multiplication: 21013463040 Numpy Product Multiplication: -461373440 Regular Product Multiplcation 21013463040 Process finished with exit code 0 Clearly I can get around the problem using the regular multiplication, but I would like to understand why the…
has answer: http://stackoverflow.com/a/48167759
linked to: http://stackoverflow.com/q/23189506
type: Question
tagged with: numpy
score: 5
answer count: 1
has comment: http://stackoverflow.com/comment/83315927
has comment: http://stackoverflow.com/comment/83314528
linked to: http://stackoverflow.com/q/7604966
has comment: http://stackoverflow.com/comment/83314448
tagged with: python
has comment: http://stackoverflow.com/comment/83315763

http://stackoverflow.com/a/48039742
type: AcceptedAnswer
type: Answer
has body: I managed to fix it by changing if testresint&lt;float(10.0) to if float(testresint)&lt;float(10.0).
accepted answer of: http://stackoverflow.com/q/48037121
answers question: http://stackoverflow.com/q/48037121
score: 0

http://stackoverflow.com/comment/83262101
type: QuestionComment
comment on: http://stackoverflow.com/q/48142010
score: 2
has text: Possible duplicate of [GUI Button hold down](https://stackoverflow.com/questions/34522095/gui-button-hold-down)
type: Comment

http://stackoverflow.com/q/48142119
score: 0
answer count: 1
tagged with: url
tagged with: django
tagged with: python
type: UnansweredQuestion
has title: What type of instance can django.conf.urls.url() be counted as?
type: Question
has answer: http://stackoverflow.com/a/48142225
has body: While reading the official Django documentation, specifically the chapter 'URL dispatcher' about how Django processes requests, I stumbled upon something which made me uncertain. The docs stated that the variable 'urlpatterns' is a list containing django.conf.urls.url() instances. This made me wonder, is django.conf.urls.url(), or url() as commonly written within the framework, a function or a class? I have understood that everything in Python can be considered a class, however is it syntactically speaking a function or a class? My first instinct was to research the django.conf.urls.url(), url(), within the Django documentation, but I was unable to find much to read. This same question has now become relevant for me regarding other functions/classes that Django provides. How can you be sure whether or not foo() is a function or a class? From my understanding, these are definitely functions, but I am having a hard time expressing why. Thank you in advance.

http://stackoverflow.com/q/48159608
tagged with: python
accepted answer: http://stackoverflow.com/a/48159647
duplicate of: http://stackoverflow.com/q/33678543
has body: Given an array of integers, I need to find the indexes of many of its elements stored in a different array. This is: import numpy as np a1 = np.array([ 4, 5, 6, 1, 2, 3, 7, 86, 9, 15]) a2 = np.array([ 2, 3, 5, 6, 9]) Where a1 is my initial array of elements, and a2 is the array that contains the elements for which I need their indexes in a1. In this case, the result should be: a3 = ([4, 5, 1, 2, 8]) This seems like a rather simple operation, but I haven't been able to figure out how to do it.
type: AnsweredQuestion
has title: Find index of multiple elements in numpy array
has comment: http://stackoverflow.com/comment/83301483
score: 4
type: Question
upvote count: 4
tagged with: numpy
answer count: 1
tagged with: arrays
has answer: http://stackoverflow.com/a/48159647
downvote count: 0
linked to: http://stackoverflow.com/q/33678543
favorite count: 0

http://stackoverflow.com/q/48139722
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has title: Two loops in HTML Table
has answer: http://stackoverflow.com/a/48139790
has answer: http://stackoverflow.com/a/48139810
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/48139791
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/48139933
accepted answer: http://stackoverflow.com/a/48139933
tagged with: python
has answer: http://stackoverflow.com/a/48139791
has body: Hello I have a bit of problem with my HTML, I have two loops from my python which generates every item with their respective. Here's the code: Nature of Collection Amount {%for nature in natures%} {{nature}} {% endfor %} {%for amount in amounts%} {{amount}} {% endfor %} How do I make it so that it gets formatted in a table properly? I already tried algning it, and fidgeting with it but I don't get the result I want. I just want it to be a simple Table for example Nature of Collection | Amount NOC1 1000 NOC2 1000 What should I do to achieve that?
answer count: 4

http://stackoverflow.com/comment/83115214
type: QuestionComment
comment on: http://stackoverflow.com/q/48070703
has text: I cannot fully understand this question. So what is "lets say 2 processors as each case is a parallel (MPI) simulation"?
score: 0
type: Comment

http://stackoverflow.com/q/48085420
tagged with: python
has comment: http://stackoverflow.com/comment/92751023
score: 3
has comment: http://stackoverflow.com/comment/83147807
has comment: http://stackoverflow.com/comment/83178318
upvote count: 3
has comment: http://stackoverflow.com/comment/89209284
has comment: http://stackoverflow.com/comment/83146740
has comment: http://stackoverflow.com/comment/83150008
type: Question
has comment: http://stackoverflow.com/comment/83146506
has comment: http://stackoverflow.com/comment/83145995
has comment: http://stackoverflow.com/comment/83147577
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83147026
tagged with: unicode
has comment: http://stackoverflow.com/comment/83146737
has comment: http://stackoverflow.com/comment/88370068
has comment: http://stackoverflow.com/comment/83148337
has answer: http://stackoverflow.com/a/52921092
tagged with: tkinter-canvas
has title: Python 3 unicode codec error binding mousewheel in tkinter
has body: Using Python 3.6/tkinter on MacOS, I created a frame within a canvas and bound a scrollbar to it. This all works fine. The problem is when I try to snag MouseWheel events when the cursor is in the scrollable frame. I set up a binding: main_window.bind("&lt;MouseWheel&gt;",on_mousewheel) and created a short dummy event handler: def on_mousewheel(event): print(event.delta) Every time I use the scroll wheel, Python responds with: Traceback (most recent call last): File "/Users/Gary/IPPS/opendb.py", line 160, in &lt;module&gt; main_window.mainloop() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1277, in mainloop self.tk.mainloop(n) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Here is the code: from tkinter import * def on_main_window_resize(event): canvas.configure(scrollregion=canvas.bbox('all')) def on_mousewheel(event): print(event.delta) main_window = Tk() main_window.bind("&lt;MouseWheel&gt;",on_mousewheel) canvas = Canvas(main_window, width=500, height=500) canvas.pack(side=LEFT, fill=BOTH, expand=YES) cust_scroll = Scrollbar(main_window, orient=VERTICAL, command=canvas.yview) cust_scroll.pack(side=RIGHT, fill=Y, expand=NO) cust_list = Frame(canvas) canvas['yscrollcommand'] = cust_scroll.set canvas.bind('&lt;Configure&gt;', on_main_window_resize) canvas.create_window((0,0), window=cust_list, anchor=NW) main_window.grid_columnconfigure(0, weight=1) main_window.grid_rowconfigure(0, weight=1) memberbuttons = list(); for member in range(1,20): memberbutton = Button(cust_list, text="BUTTON", justify=LEFT, pady=2) memberbutton.pack(side=TOP, fill=X) main_window.mainloop() Any ideas?
has comment: http://stackoverflow.com/comment/83147098
has comment: http://stackoverflow.com/comment/83147429
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/16995969

http://stackoverflow.com/comment/83206034
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48114614
type: Comment
has text: The regressor is doing regression task, so I'm afraid it won't help. I think one option is to use pure tensorflow, where you can define your own loss easily. See this example - https://github.com/aymericdamien/TensorFlow-Examples/blob/master/notebooks/2_BasicModels/logistic_regression.ipynb

http://stackoverflow.com/a/48125850
has comment: http://stackoverflow.com/comment/83228599
answers question: http://stackoverflow.com/q/48125803
has body: In your code info should be a dictionary, from a list of dictionaries. It's currently a string... Anyway, your dataset is more suited for a simple csv.writer I've changed names to a list of lists, containing all the rows, changed DictWriter to writer. Then dropped writeheader for writerow with the title. Also used writerows on the list of lists for better speed (avoids a loop): import csv names = [ ['kisha' ,'smith' , 'kishasmith@gmail.com', 40000 , '1-1-2029' ,'janitor' ], # more employees here ] with open('employees.csv' , 'w', newline="") as employee_file: fieldnames2 = ['first' , 'last' , 'email' , 'salary' , 'DOB' , 'occupation'] csvwriter = csv.writer(employee_file , delimiter = ',') csvwriter.writerow(fieldnames2) csvwriter.writerows(names) Also note that you need newline="" (python 3) or your csv file will have a blank line every other line on windows.
score: 3
has comment: http://stackoverflow.com/comment/83228628
downvote count: 0
upvote count: 3
type: Answer

http://stackoverflow.com/q/48147195
type: Question
score: -1
has title: python list element address decrease instantly
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83275231
has comment: http://stackoverflow.com/comment/83272592
has comment: http://stackoverflow.com/comment/83272651
tagged with: element
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83272648
has comment: http://stackoverflow.com/comment/83272680
tagged with: memory-address
has body: I just wrote the code like this: li = [1, 2, 3, 4, 5] for ele in li: print "value: ", id(ele) and I got the result: value: 21381944 1 value: 21381920 2 value: 21381896 3 value: 21381872 4 value: 21381848 5 24 bytes are allocated to each element, but I don't understand why the address of each element decrease rather than increase.
downvote count: 1
has answer: http://stackoverflow.com/a/48147327
has comment: http://stackoverflow.com/comment/83272559

http://stackoverflow.com/q/48116698
score: 1
has comment: http://stackoverflow.com/comment/113504109
has answer: http://stackoverflow.com/a/57334645
linked to: http://stackoverflow.com/q/35508711
has title: Zoom QImage on QPixmap in QLabel
upvote count: 1
type: Question
tagged with: qlabel
has comment: http://stackoverflow.com/comment/83216650
tagged with: qimage
has body: I am subclassing QLabel, on which I set QPixmap. I want to zoom into the image displayed in the pixmap (without losing quality). I don't want to see the entire image enlarged, just to zoom in. I have tried many ways to scale the pixmap, but was unable to get good results. The following code resizes the image, but with very bad quality. What is the right way? from PyQt5 import QtWidgets, QtCore, QtGui class ImageLabel(QtWidgets.QLabel): def __init__(self, img): self.set_image(img) def set_image(self, image): qimg = QtGui.QPixmap.fromImage(image) self._displayed_pixmap = QtGui.QPixmap(qimg) # scale image to fit label self._displayed_pixmap.scaled(self.width(), self.height(), QtCore.Qt.KeepAspectRatio) self.setScaledContents(True) self.setMinimumSize(512, 512) self.show() def zoom_image(self): image_size = self._displayed_pixmap.size() image_size.setWidth(image_size.width() * 0.9) image_size.setHeight(image_size.height() * 0.9) self._displayed_pixmap = self._displayed_pixmap.scaled(image_size, QtCore.Qt.KeepAspectRatio) self.update() # call paintEvent() def wheelEvent(self, event): modifiers = QtWidgets.QApplication.keyboardModifiers() if modifiers == QtCore.Qt.ControlModifier: self._zoom_image(event.angleDelta().y()) def paintEvent(self, paint_event): painter = QtGui.QPainter(self) painter.drawPixmap(self.rect(), self._displayed_pixmap)
tagged with: pyqt
downvote count: 0
answer count: 1
favorite count: 0
tagged with: qpixmap
has comment: http://stackoverflow.com/comment/83216694
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83141210
comment on: http://stackoverflow.com/q/48082826
has text: I recently read [this](http://pbpython.com/wine_visualization.html) with bokeh. Look for `desc.text` I don't know if it's possible to change font/size.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48029770
accepted answer of: http://stackoverflow.com/q/48027076
answers question: http://stackoverflow.com/q/48027076
score: 0
has body: I was able to get the code to function just how I wanted. All I had to do was move the global reduced_item() statement from the def reduced_item() function to def main(node, json_file_path, csv_file_path) function I created. If stating that its a global variable doesn't define, it then I'm not sure why this worked. Also why is defining something Global generally not a great idea? If you guys have a recommendations for how to do this better I'm open for guidance. Thank you for trying to help.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83047738
type: Answer

http://stackoverflow.com/q/48124200
score: 1
has title: How to get the text from an anchor tag?
type: Question
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83225490
favorite count: 0
has answer: http://stackoverflow.com/a/48124303
has body: I would like to get the text from all anchor tag which has class="ip_click" in the page. Here's an exactly example that I'm trying to get: 177.1.1.1 177.2.2.2 I want to get "177.1.1.1" and "177.2.2.2" and how much other Something here Exist in the page, so I tried: ip = browser.find_by_css("ip_click") for i in ip: print i But the Firefox closes and nothing is displayed in terminal. Furthermore, in terminal no error is shown.
tagged with: python
has comment: http://stackoverflow.com/comment/83225319
tagged with: splinter
upvote count: 1
accepted answer: http://stackoverflow.com/a/48124303
type: AnsweredQuestion

http://stackoverflow.com/q/48131600
score: -1
type: AnsweredQuestion
tagged with: floating-point
accepted answer: http://stackoverflow.com/a/48131917
downvote count: 1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/83240291
tagged with: sum
has comment: http://stackoverflow.com/comment/83240259
has title: python 3 float sum
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48131917
tagged with: python
has body: 0.15 0.98 0.92 I've got float numbers which comes from mongodb as above and try to sum of the numbers with code below and getting error. for document in cursor: Price = (document['Price']) item = (datetime.strptime(cortime(document['TimeStamp']), "%Y:%m:%d %H:%M:%S")) dif = str(li - item) if dif &lt;= '0:05:00': try: print(sum(Price)) except Exception as error: print(error) Error: unsupported operand type(s) for +: 'int' and 'str'

http://stackoverflow.com/comment/83003869
score: 0
type: Comment
has text: @Ravi You create the whole thing from scratch... for **efficiency**?
comment on: http://stackoverflow.com/a/48017321
type: AnswerComment

http://stackoverflow.com/comment/83277683
comment on: http://stackoverflow.com/a/48132734
type: AnswerComment
has text: hey man your welcome thanks so much for your help, I'm still very new and learning and its hard to know where to get good help.
score: 0
type: Comment

http://stackoverflow.com/comment/83229600
type: Comment
type: QuestionComment
score: 2
has text: Define "1 year". Is `ct + 60*60*24*365` accurate enough?
comment on: http://stackoverflow.com/q/48126471

http://stackoverflow.com/comment/83031927
type: Comment
has text: @Mr.Me No, but I've cleared up the problem, you were right I believe they were ratelimiting me, and the only other URL I tried was Google, which needs certain headers to not ratelimit. This is the correct answer.
type: AnswerComment
comment on: http://stackoverflow.com/a/48030775
score: 0

http://stackoverflow.com/a/48028959
accepted answer of: http://stackoverflow.com/q/48028887
answers question: http://stackoverflow.com/q/48028887
type: Answer
score: 3
downvote count: 0
has body: By looking at Django docs what you get when you do img = request.FILES['avatar'] is a file descriptor that points to an open file with your image. Then you should to dump the contents in your actual avatar path, right? #Here is where I create the name of the path to save as a VARCHAR field, THIS WORKS TOO avatar = &quot;../../static/profile/&quot; + str(request.session['user_id']) + &quot;/&quot; + str(img) # # # # # with open(avatar, 'wb') as actual_file: actual_file.write(img.read()) # # # # # return redirect(request, 'myapp/upload.html') Beware: the code is untested.
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/48048322
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/48048347
favorite count: 0
upvote count: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 1
has title: Summing up values across multiple columns into groups which are defined in a dictionary
type: Question
has comment: http://stackoverflow.com/comment/83122449
downvote count: 0
accepted answer: http://stackoverflow.com/a/48048347
has body: I have device data spread across various channels , the channels come in 3 separate groups and are defined by a dictionary.Now from the dataset I need to sum the columns into 3 separate groups as in the dictionary. Input : device_id class Channel A Channel B Channel C Channel D Channel E Channel F Channel G Channel H Channel I Channel J 28 S 2 4 23 45 6 6 8 9 0 0 54 P 0 0 0 0 0 0 0 0 0 0 97 S 0 0 0 0 0 0 0 0 0 0 14 V 0 0 0 0 0 0 0 0 0 0 21 P 0 0 0 0 0 0 0 0 0 0 23 V 0 0 0 0 0 0 0 0 0 0 22 P 0 0 32 76 89 0 0 0 0 0 29 P 0 0 0 0 0 0 0 0 0 0 25 S 0 0 0 0 0 0 0 0 0 0 27 P 0 0 0 0 0 0 0 0 0 0 So as per the description of the problem the expected output: Expected Output: device_id S P V 28 6 74 23 54 0 0 0 97 0 0 0 14 0 0 0 21 0 0 0 23 0 0 0 22 0 197 0 29 0 0 0 25 0 0 0 27 0 0 0 And the dictionary containing the mapping is: The dictionary: { 'S' : ['Channel A','Channel B'], 'P' : ['Channel C','Channel D','Channel E'], 'V' : ['Channel F','Channel G','Channel H','Channel I',' Channel J'] } Can someone please help me with this?

http://stackoverflow.com/q/48121711
score: 1
has body: I'm trying to implement a file directory using PyQt5. I'd like to incorporate drag and drop functionality within this tree to support both internal and external files (i.e. if I had some files on my desktop I'd like to be able to drop them into a folder in my PyQt view). This is what I have currently: from PyQt5.QtWidgets import QTreeView,QFileSystemModel,QApplication, QMenu, QAbstractItemView from PyQt5.QtCore import * from PyQt5.QtGui import * from src import config class Tree(QTreeView): def __init__(self): QTreeView.__init__(self) cfg = config.get() model = QFileSystemModel() model.setRootPath("/Users/") self.setModel(model) self.setRootIndex(model.index("/Users/")) self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.open_menu) self.setSelectionMode(self.SingleSelection) self.setDragDropMode(QAbstractItemView.InternalMove) self.setDragEnabled(True) self.setAcceptDrops(True) self.setDropIndicatorShown(True) def open_menu(self): menu = QMenu() menu.addAction("Create new folder") menu.exec_(QCursor.pos()) if __name__ == '__main__': import sys app = QApplication(sys.argv) w = Main() w.show() sys.exit(app.exec_()) With the above code I can show a directory and its contents. I can drag an item but dropping it does nothing and no drop indication is seen. It's unclear how to a. get drag and drop working within the view and b. get it working with items outside of that context (like from the desktop for example).
type: Question
accepted answer: http://stackoverflow.com/a/48122488
possible better answer: http://stackoverflow.com/a/48122565
answer count: 2
tagged with: pyqt
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48122488
tagged with: drag-and-drop
has title: Drag and drop within PyQt5 TreeView?
tagged with: python
tagged with: qtreeview
has answer: http://stackoverflow.com/a/48122565
downvote count: 0
tagged with: pyqt5
type: AnsweredQuestion

http://stackoverflow.com/a/48142649
accepted answer of: http://stackoverflow.com/q/48142637
answers question: http://stackoverflow.com/q/48142637
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83263820
type: Answer
has comment: http://stackoverflow.com/comment/83264038
has comment: http://stackoverflow.com/comment/83293800
has comment: http://stackoverflow.com/comment/98944481
downvote count: 0
has comment: http://stackoverflow.com/comment/98934929
has body: As per help messages from running mod_wsgi-express start-server --help: --limit-request-body NUMBER The maximum number of bytes which are allowed in a request body. Defaults to 10485760 (10MB). Change your app.sh to add the option and set it to a larger value.
score: 1

http://stackoverflow.com/comment/83079881
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48051977
has text: But if I were you, I would install my packages with pip, even in an anaconda environment. That's what I do and it works perfectly

http://stackoverflow.com/comment/83129390
type: QuestionComment
comment on: http://stackoverflow.com/q/48077808
type: Comment
score: 1
has text: And you'll be teaching the courses?

http://stackoverflow.com/comment/83142157
type: Comment
has text: better use only `14,5,19,5` and it will make life/code easier. You can always create function which will check walls and replace `19,5,14,5` with `14,5,19,5`
score: 0
comment on: http://stackoverflow.com/q/48082037
type: QuestionComment

http://stackoverflow.com/comment/83107529
comment on: http://stackoverflow.com/a/48064909
type: Comment
score: 1
has text: Thanks for taking your time to reply!
type: AnswerComment

http://stackoverflow.com/a/48095271
accepted answer of: http://stackoverflow.com/q/48091645
upvote count: 1
answers question: http://stackoverflow.com/q/48091645
has comment: http://stackoverflow.com/comment/83186743
type: AcceptedAnswer
downvote count: 0
has body: If you already have model profile - then add db_column=${USER ID DB COLUMN NAME} on user field, if no - set managed = True in Meta. Also, you can use related_name='profile' to get profile instance from user. Django tries to accept profile instance by user_id column, but can't identify it.
type: Answer
score: 1

http://stackoverflow.com/comment/83272294
has text: your error says: 'Content-Type header [] is not supported' . Have you try to index without [ ] ? maybe in this way body={"title":"this is title","desc":"this is description"}
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48139986

http://stackoverflow.com/comment/83153845
type: Comment
has text: Could you please formulate your question as a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)? There is definitely a solution to this, but it may depend slightly on how you generate the plot.
comment on: http://stackoverflow.com/q/48088128
score: 0
type: QuestionComment

http://stackoverflow.com/q/48154787
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48186537
has body: I have a deployed django webapp which has been working fine. It scrapes sites for newly published .csv files and then uses them for data analysis which is then returned to the user. The most recent .csv is not being recognised as a file on the deployed version, but is on the test version on my local machine. The structure is as follows: -indicator-analyser -Analyser -AnalysisScripts -uploads -data -2017 -Monthly_File_Jun_Final.csv -Monthly_File_Sep_Final.csv When a user attempts to run the script on the Monthly_File_Jun_Final.csv, the webapp performs as expected. When they run the same script on Monthly_File_Sep_Final.csv, django throws an error as there is no file found. I have taken the file path that is passed in and used that to open the file in explorer, and I have used the same file path to load the .csv as a dataframe in pandas within the console with no problems. The path that is passed to the loading script is: C:\\webapp\\indicator-analyser\\Analyser/uploads/data/2017/Monthly_File_Sep_Final.csv When this is evaluated using os.path.isfile(filepath), it is being returned as False. However, when the other file is selected, this is returned and recognised as a file: C:\\webapp\\indicator-analyser\\Analyser/uploads/data/2017/Monthly_File_Jun_Final.csv Just for reference, this is running on a IIS server. I have restarted the machine and the server to no avail. To conclude, I can access this file: through the console on my local instance through my file explorer But it is not recognised as a file in the live django instance.
tagged with: http://stackoverflow.com/tag/csv
tagged with: iis
has title: Deployed Django instance not recognising a file as a file
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83296266
has comment: http://stackoverflow.com/comment/83352559
accepted answer: http://stackoverflow.com/a/48186537
type: Question
has comment: http://stackoverflow.com/comment/83294226
has comment: http://stackoverflow.com/comment/83301527

http://stackoverflow.com/comment/83153062
score: 0
type: Comment
type: QuestionComment
has text: StackOverflowhas a sister Stack Exchange site for *code review*. This question is more appropriate for *that* community. Also, SO does not favor primarily opinion based questions/answers. Welcome.. Please read: [What kinds of questions can I ask](https://stackoverflow.com/help/on-topic), [How to ask](https://stackoverflow.com/help/how-to-ask).
comment on: http://stackoverflow.com/q/48089131

http://stackoverflow.com/comment/83043783
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48036586
score: 0
has text: Fair enough. I just want to check if anything on the screen has changed within x (seconds). If so, draw rectangle around the parts that changed. Imagine you're looking at document or page or app that has a bunch of dynamic text in it and say one or more words changes on the page you're on. I want to draw a box around the word(s) that changed. I chose python because I'm most comfortable with it is all. And chose images to compare because it might not always be text that changes etc.

http://stackoverflow.com/q/48080163
has answer: http://stackoverflow.com/a/48080279
has answer: http://stackoverflow.com/a/48080307
has comment: http://stackoverflow.com/comment/83134495
downvote count: 1
has answer: http://stackoverflow.com/a/48080323
type: Question
has body: I have an unicode array and I want to convert it to array. Given input format and output format below: p = u'(abcd, pqrs, fghj, mjki, loki)' And I want output as below: output = ('abcd', 'pqrs', 'fghj', 'mjki', 'loki')
accepted answer: http://stackoverflow.com/a/48080307
tagged with: arrays
has title: Converting string representation of array (of string) to the array in python
score: -1
upvote count: 0
tagged with: string
tagged with: unicode
favorite count: 0
has comment: http://stackoverflow.com/comment/83134452
has comment: http://stackoverflow.com/comment/83134676
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48081291
has comment: http://stackoverflow.com/comment/83134437
has answer: http://stackoverflow.com/a/48080339
has comment: http://stackoverflow.com/comment/83134458
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48080279
has comment: http://stackoverflow.com/comment/83137379

http://stackoverflow.com/q/48046252
has title: How to set radius with specific inches/cm of pie chart on matplotlib
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: matplotlib
type: Question
tagged with: pie-chart
has body: I am making a pie chart using matplotlib and I want to make the radius size exactly 1.5 inches. How can this be done? I know you can set the figure size with specific inches, but this is not what I am trying to do -- I am trying to specifically set the size of the pie chart itself. thanks!
has comment: http://stackoverflow.com/comment/83064393
score: 0
has comment: http://stackoverflow.com/comment/83282360

http://stackoverflow.com/comment/83067040
has text: you get list `list1 = response.css("").extract()` and later you replace it with `link1 = 'https:...' + str(i)` - why ?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48047024

http://stackoverflow.com/comment/83169684
has text: This issue aside, your second function ('veldkleuren') will be buggy - it will respond to an input of 10 by setting y to 150 instead of -210, for instance.
type: Comment
comment on: http://stackoverflow.com/q/48097188
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83078300
type: Comment
type: QuestionComment
score: 0
has text: No, you should just install the FFmpeg development header files that belong to the libraries that you installed.
comment on: http://stackoverflow.com/q/48052032

union
type: Tag
tag name: union
tags question: http://stackoverflow.com/q/48149626

http://stackoverflow.com/q/48029089
has title: Importing CV2 does not work in Spyder but works in PyCharm
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/48029193
tagged with: spyder
type: UnansweredQuestion
tagged with: python
has body: I have Anaconda 3 installed (Python 3.6.3) and I am working on a project that uses the CV2 package in python. Now I am relatively new to python but I have been using this package (via "import cv2" command) in PyCharm with no problems. However, today, I wanted to give Spyder a try. I started using the IDE and everything was working. But all of a sudden, Spyder kept giving me an error when I try to import cv2. I really did not change anything and I only was debugging the script. The error I am getting is as follows: """ In [1]: import cv2 Traceback (most recent call last): File "", line 1, in import cv2 ImportError: DLL load failed: The specified procedure could not be found. """ I cannot figure out how this can be related to the IDE since PyCharm still can import it. Could anybody give me a hint please?
tagged with: opencv
has comment: http://stackoverflow.com/comment/83028364
has comment: http://stackoverflow.com/comment/83138656
type: Question

http://stackoverflow.com/comment/83188941
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48106544
score: 0
has text: Thank you! that worked perfectly!

http://stackoverflow.com/comment/83238075
comment on: http://stackoverflow.com/q/48130355
has text: look at the `csv` module from the stdlib!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83236715
type: Comment
type: QuestionComment
has text: There is a unicode issue with you `_id` field. I am not sure how to fix it, but try to cast the id into a string and/or creating your dictionary using the `dict()` constructor. Also, there is no need for a `body` key in the `_source` field
score: 0
comment on: http://stackoverflow.com/q/48127047

http://stackoverflow.com/a/53643230
type: Answer
has body: The path in different system: Linux: ~/.keras/models/ Win: settings/.keras/models/ of Python Anaconda on Win D:\Anaconda3\Lib\site-packages\tensorflow\contrib\keras\api\keras\applications\vgg16 Putting the downloaded .h5 file to these local folder seems to work.
answers question: http://stackoverflow.com/q/48129804
score: 0

http://stackoverflow.com/comment/83130697
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48078218
has text: Your argument to `readlines` [does not do](https://docs.python.org/3/library/codecs.html?highlight=readlines#codecs.StreamReader.readlines) what you seem to think.

http://stackoverflow.com/a/48062326
has comment: http://stackoverflow.com/comment/83098537
upvote count: 1
has body: I think you need dict comprehension and filter by boolean indexing with isin, ~ is for inverting boolean mask: vals = [3, 5, 6, 7, 8, 9, 10, 11, 12, 13] d1 = {k:df[~df['EVENTMSGTYPE'].isin(vals)] for k, df in dfs.items()} Or use query: d1 = {k:df.query('EVENTMSGTYPE not in @vals') for k, df in dfs.items()} For filtering out empty DataFrames use: d1 = {k:df[~df['EVENTMSGTYPE'].isin(vals)] for k, df in dfs.items() if not df['EVENTMSGTYPE'].isin(vals).all()} EDIT: d1 = {} last = 0 for k,df in dfs.items(): m = ~df['EVENTMSGTYPE'].isin(vals) m = m &amp; m.all() if m.all(): d1[last] = df last += 1
has comment: http://stackoverflow.com/comment/83098856
has comment: http://stackoverflow.com/comment/83097384
has comment: http://stackoverflow.com/comment/83097811
has comment: http://stackoverflow.com/comment/83097414
has comment: http://stackoverflow.com/comment/83098481
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83099004
score: 1
has comment: http://stackoverflow.com/comment/83099292
accepted answer of: http://stackoverflow.com/q/48062296
type: Answer
has comment: http://stackoverflow.com/comment/83098466
answers question: http://stackoverflow.com/q/48062296
has comment: http://stackoverflow.com/comment/83099203

http://stackoverflow.com/comment/83022264
score: 0
has text: I don't see anything here that would specify 32-bit floating-point data. Does AIFF even support that? It sounds like you need to make an AIFF-C file, and set the compression type.
type: QuestionComment
comment on: http://stackoverflow.com/q/48026172
type: Comment

http://stackoverflow.com/q/48156092
has answer: http://stackoverflow.com/a/48156238
answer count: 1
tagged with: data-science
score: 0
tagged with: pandas
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83291331
has body: I want to filter a rather large Pandas dataframe (about 3 million rows) by date. For some reason the drop method when used with boolean criteria does not work at all. It just returns the same old dataframe. Dropping single rows is no problem though. This is the code is used initially, which essentially does nothing at all: import pandas as pd #open the file df = pd.read_csv('examplepath/examplefile.csv', names=['File Name','FileSize','File Type','Date Created','Date Last Accessed','Date Last Modified','Path'],\ delimiter=';', header=None, encoding="ISO-8859-1",) #convert to german style date df['Date Created'] = pd.to_datetime(df['Date Created'], dayfirst=True) #drop rows and assign new dataframe df_filtered = df.drop(df[df['Date Created'] &gt; datetime(2010,1,1)]) I then came up with this code, which seemingly works like a charm: import pandas as pd #open the file df = pd.read_csv('examplepath/examplefile.csv', names=['File Name','FileSize','File Type','Date Created','Date Last Accessed','Date Last Modified','Path'],\ delimiter=';', header=None, encoding="ISO-8859-1",) #convert to german style date df['Date Created'] = pd.to_datetime(df['Date Created'], dayfirst=True) #select rows and assign new dataframe df_filtered = df['Date Created'] &lt; datetime(2010,1,1) Both codes in theory should do the same thing, right? Is one of the codes to be preferred? Can I just work with my second code? In the future I may have to add a second filterdate. I hope someone can help me. Thanks and best regards, Stefan
has comment: http://stackoverflow.com/comment/83291639
tagged with: dataframe
type: Question
has title: Pandas drop method does not work.

http://stackoverflow.com/comment/83260332
score: 0
type: Comment
has text: That's interesting; I would otherwise delete my answer as irrelevant but I'll keep it for the sake of the comments.
type: AnswerComment
comment on: http://stackoverflow.com/a/48141000

http://stackoverflow.com/comment/83253614
score: 0
comment on: http://stackoverflow.com/a/48138122
has text: I updated the question to separate run_hook from my test code
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83074854
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48051390
has text: @Divakar I just edited my question.
type: Comment

http://stackoverflow.com/q/48112226
linked to: http://stackoverflow.com/q/35852170
favorite count: 0
has answer: http://stackoverflow.com/a/48229609
tagged with: python
has comment: http://stackoverflow.com/comment/83721067
has title: Update a function during debugging (pdb or ipdb)
tagged with: ipdb
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83536392
has body: Imagine I am debugging the following script: import ipdb def slow_function(something): # I'm a very slow function return something_else def fast_function(something_else): # There's a bug here return final_output something = 1 something_else = slow_function(something) ipdb.set_trace() final_output = fast_function(something_else) ipdb.set_trace() When the ipdb.set_trace() line is met the debugger shell is prompted and I can now execute the final_output = fast_function(something_else) statement to check whether fast_function is behaving as intended. I see there's a bug so I go into the source code and I fix it. Now I want to see whether the fix is correct but I don't want to run the script a second time (because it's slow), nor I want to save something_else on disk (because, maybe, it's very large). Is there a way to update fast_function() in the debugger shell so that the new source code is used?
tagged with: pdb
type: Question
tagged with: debugging
has answer: http://stackoverflow.com/a/48207526
upvote count: 9
score: 9
has answer: http://stackoverflow.com/a/48207436
answer count: 3
downvote count: 0

http://stackoverflow.com/a/48095507
downvote count: 0
type: Answer
upvote count: 6
score: 6
has body: An approximate approach could be to: extract the outer boundary of individual components of the MultiPolygon of interest expand-shrink each of the outer boundaries in order to fill "holes" which these boundaries approximately encompass, e.g., to handle a "doughnut with a cut" merge all geometries obtained in previous step For example: #!/usr/bin/env python from shapely.geometry import MultiPolygon, Polygon from shapely.ops import cascaded_union a = 0.25 delta = 0.49 P = MultiPolygon([ ( ((0,0),(0,3),(3,3),(3,2-delta),(2,2-delta),(2,2),(1,2),(1,1),(2,1),(2,1+delta),(3,1+delta),(3,0),(0,0)), [((a, a), (1-a,a), (1-a,1-a), (a,1-a), (a,a))] ) ]) eps = 0.01 omega = cascaded_union([ Polygon(component.exterior).buffer(eps).buffer(-eps) for component in P ]) for x,y in zip(*omega.exterior.coords.xy): print(x, y) The MultiPolygon P looks like: while the script listed above produces as expected an approximate square with side of length 3, i.e., it fills the hole in the lower-left corner as well as the "empty space" in the center of the MultiPolygon which is rendered equivalent to a hole in the expand-shrink procedure with sufficient high value of parameter eps.
answers question: http://stackoverflow.com/q/48082553

http://stackoverflow.com/a/48154218
score: 4
has body: How about deleting the Hash with a DEL command? You can wrap it in a transaction that also sets (HSET) the new values in it.
answers question: http://stackoverflow.com/q/48150251
upvote count: 4
downvote count: 0
type: Answer

http://stackoverflow.com/a/48055041
upvote count: 1
answers question: http://stackoverflow.com/q/48055016
downvote count: 0
has body: You can do it like this: from functools import reduce product = reduce((lambda x, y: x * y), [3, -1, 4, -1, -5]) print(product) This outputs -60 Optionally, you can declare any list l = [3, -1, 4, -1, -5] and then call product = reduce((lambda x, y: x * y), l)
type: Answer
score: 1

http://stackoverflow.com/comment/83290853
type: Comment
score: 0
has text: look in the docs for `os.walk`
comment on: http://stackoverflow.com/q/48155701
type: QuestionComment

http://stackoverflow.com/comment/83143254
has text: Whoops, yeah, this ignores `id_indiv`! I'll edit my answer to address this. Not sure if my solution is better or faster than yours, but at least it'll be an alternative approach.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48083600
type: Comment

http://stackoverflow.com/q/48119447
type: UnansweredQuestion
has body: Right now I'm running Python in Atom with Platformio as my terminal. First off, what's the keyboard shortcut to run the file? Secondly, is there a better terminal package out there? I'd like more features such as right clicking and selecting run the file or something that makes running the file easier (maybe a run button). I switch between files quite frequently so I'd like an alternative other than using the up arrow to run previous command.
type: Question
has title: Python- Alternative terminal in Atom text editor
score: 0
tagged with: atom-editor
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48119925

http://stackoverflow.com/q/48171492
has answer: http://stackoverflow.com/a/61868618
type: Question
accepted answer: http://stackoverflow.com/a/48171723
type: AnsweredQuestion
score: 10
upvote count: 10
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/48171690
favorite count: 0
has answer: http://stackoverflow.com/a/48171690
has answer: http://stackoverflow.com/a/48171723
tagged with: pandas
tagged with: python
has title: "No numeric types to aggregate" after groupby and mean
has body: I'm dealing with time series and try to write function to calculation monthly average of data. Here are some function for prepare: import datetime import numpy as numpy def date_range_0(start,end): dates = [start + datetime.timedelta(days=i) for i in range((end-start).days+1)] return numpy.array(dates) def date_range_1(start,days): #days should be an interger return date_range_0(start,start+datetime.timedelta(days-1)) x=date_range_1(datetime.datetime(2015, 5, 17),4) x, the output is a simple time list: array([datetime.datetime(2015, 5, 17, 0, 0), datetime.datetime(2015, 5, 18, 0, 0), datetime.datetime(2015, 5, 19, 0, 0), datetime.datetime(2015, 5, 20, 0, 0)], dtype=object) Then I learn groupby function from http://blog.csdn.net/youngbit007/article/details/54288603 I have tried one example in website above and it works fine: df = pandas.DataFrame({'key1':date_range_1(datetime.datetime(2015, 1, 17),5), 'key2': [2015001,2015001,2015001,2015001,2015001], 'data1': 1+0.1*numpy.arange(1,6) }) df gives data1 key1 key2 0 1.1 2015-01-17 2015001 1 1.2 2015-01-18 2015001 2 1.3 2015-01-19 2015001 3 1.4 2015-01-20 2015001 4 1.5 2015-01-21 2015001 and grouped=df['data1'].groupby(df['key2']) grouped.mean() gives key2 2015001 0.2 Name: data1, dtype: float64 Then I try my own example: datedat=numpy.array([date_range_1(datetime.datetime(2015, 1, 17),5),1+0.1*numpy.arange(1,6)]).T months = [day.month for day in datedat[:,0]] years = [day.year for day in datedat[:,0]] datedatF = pandas.DataFrame({'key1':datedat[:,0],'key2':list((numpy.array(years)*1000 +numpy.array(months))),'data1':datedat[:,1]}) datedatF which generated data1 key1 key2 0 1.1 2015-01-17 2015001 1 1.2 2015-01-18 2015001 2 1.3 2015-01-19 2015001 3 1.4 2015-01-20 2015001 4 1.5 2015-01-21 2015001 Note this is exactly the very same table as above! so far so good. Then I run: grouped2=datedatF['data1'].groupby(datedatF['key2']) grouped2.mean() it throw out this: ---------------------------------------------------------------…

http://stackoverflow.com/comment/83000279
has text: @tarashypka is that the same format for chart.js?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48015114

http://stackoverflow.com/q/48059985
has body: I am trying to create a boolean column using GroupBy.transform on a df like this, id type 1 1.00000 1 1.00000 2 2.00000 2 3.00000 3 2.00000 the code is like, df['has_two'] = df.groupby('id')['type'].transform(lambda x: x == 2) but instead of boolean values, has_two has float values, e.g. 0.0. I am wondering why is that. UPDATE I created a test case, df = pd.DataFrame({'id':['1', '1', '2', '2', '3'], 'type':[1.0, 1.0, 2.0, 1.0, 2.0]}) df['has_2'] = df.groupby('id')['type'].transform(lambda x: x == 2) this gave me, id type has_2 0 1 1.0 0.0 1 1 1.0 0.0 2 2 2.0 1.0 3 2 1.0 0.0 4 3 2.0 1.0 if I am using df['has_2'] = df['type'] == 2 as suggested by jezrael, it is fine, id type has_2 0 1 1.0 False 1 1 1.0 False 2 2 2.0 True 3 2 1.0 False 4 3 2.0 True I am using pandas==0.20.3 on Python 3.5.2. I am wondering what's going on, do I need an update on pandas or python 3? UPDATE Updated pandas to 0.22.0 fixed this issue.
accepted answer: http://stackoverflow.com/a/48060037
answer count: 2
tagged with: pandas-groupby
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48060155
downvote count: 0
has comment: http://stackoverflow.com/comment/83094476
has answer: http://stackoverflow.com/a/48060037
favorite count: 0
has comment: http://stackoverflow.com/comment/83092414
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83092391
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83094485
has comment: http://stackoverflow.com/comment/83094711
has title: pandas create boolean column using groupby transform
upvote count: 3
has answer: http://stackoverflow.com/a/48060155
has comment: http://stackoverflow.com/comment/83092355
type: Question
score: 3

http://stackoverflow.com/q/48077286
tagged with: newtons-method
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83222956
has comment: http://stackoverflow.com/comment/83147173
tagged with: scipy
has comment: http://stackoverflow.com/comment/83145427
has body: I have been struggling with this for a long time now and i hope that someone can help me. I have a function named "ULS" which looks something like this def uls(muliple, known, values): # result = (a value calculated by the known values and the unknown x0) return result The function contain multiple equations which depends on the known values plus one unknown value x0. The sum of all these equations should be zero (Target) and i want to know for which x0 value my target can be met. (Kinda like a goal seek). Currently i have all this in a loop and i am running through many x0 values until a condition is met. Can Scipy method be used here ? The equations are linear. More info. Im looking at this specific problem. For a chosen value of x_bot all the lists and variable are calculated and the expression abs(equN - N) is evaluated. Now i want to find the value of x_bot which makes the abs(equN-N) &lt; 1. def ULS(xp_bot): xp_top = 0.00014 xp_all = [] slope = (xp_bot-xp_top)/(Ln) for i in range(0,100,1): xp_calc = i*slope + xp_top xp_all.append(xp_calc) xp_all.append(xp_bot) xmi_all = [] for i in range(0,100,1): xmi_calc = (xp_all[i] + xp_all[i+1])/2 xmi_all.append(xmi_calc) xi_all = [] for i in range(0,100,1): xi_calc = xmi_all[i] + xni_all[i] xi_all.append(xi_calc) sic_all = [] for item in xi_all: if item &gt;= 0: sic = item*Ecm sic_all.append(sic) else: sic = 0 sic_all.append(sic) fic_step = np.multiply(sic_all,a) fic = np.divide(fic_step,1000) sis_all = [] for item in xi_all: sis = item*Es sis_all.append(sis) fis_step = np.multiply(sis_all,a_s) fis = np.divide(fis_step,1000) M_conc = [] for i in range(0,100): multi_c = np.divide(fic,1000) M_conc = np.multiply(leverarm,multi_c) multi_s = np.divide(fis,1000) M_steel = np.multiply(leverarm,multi_s) M_sls = sum(M_conc) + sum(M_steel) equN = sum(fic) + sum(fis) return abs(equN - N)
type: Question
tagged with: numpy
score: 0
has comment: http://stackoverflow.com/comment/83145453
has title: How to create a "Goal Seek" using SciPy's functions
has comment: http://stackoverflow.com/comment/83129762
tagged with: python

http://stackoverflow.com/q/48064468
tagged with: python
tagged with: merge
accepted answer: http://stackoverflow.com/a/48064696
type: AnsweredQuestion
has title: Merging multi-index dataframes based on similar groups/indexes
score: 1
upvote count: 1
type: Question
tagged with: sorting
tagged with: pandas
has body: I have a multi-index dataframe that contains some economic and social indicators A sample dataframe can be generated by this code import pandas as pd import numpy as np arrays = [['USA', 'USA', 'Egypt', 'Egypt', 'U.S.A.', 'U.S.A.', 'ARE, eg', 'ARE, eg', 'United States', 'France', 'France', 'France'], [1950, 1980,1980, 2010, 2010, 1990, 1960, 1990, 2015, 1980, 1995, 2010]] tuples = list(zip(*arrays)) index2 = pd.MultiIndex.from_tuples(list(zip(*arrays)), names=['Country', 'Year']) cols= ['ind1', 'ind2', 'ind3', 'ind4'] df = pd.DataFrame(np.random.randn(12, 4), index=index2, columns=cols) df.iloc[1::4,0] = np.nan; df.iloc[2::4,1] = np.nan; df.iloc[::3,2] = np.nan; df.iloc[1::3,3] = np.nan df Here is a sample output: The problem is that the dataframe contains many typo-like keys in the dataframe index. for example, the USA is entered once as USA, U.S.A., US, or United States, etc. I want to merge these groups based on a list that contains possible names, where the values of the columns are merged (as average value if repeated) and sorted. new_names={'USA':['USA', 'U.S.A.', 'US', 'United States'], 'Egypt': ['Egypt', 'ARE', 'Egypt, the Arab Republic of', 'ARE, eg']} How can I perform this merge efficiently in this multi-index pandas dataframe?
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48064696

http://stackoverflow.com/a/48033275
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83036929
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48032488
accepted answer of: http://stackoverflow.com/q/48032488
has body: Problem is that you have code in modules and you use globals() But globals() gives global variables inside module, not in full program. In main file use dictionary to keep data - it can be global dictionary or dictionary in main class self.all_dfs = {} and send this dictionary to other classes as argument self.p1 = PyDataTest1(self, self.all_dfs) self.p2 = PyDataTest2(self, self.all_dfs) main.py import tkinter as tk import tkinter.ttk as ttk import tkinter.messagebox as messagebox import pandas as pd from PyDataTest1 import PyDataTest1 from PyDataTest2 import PyDataTest2 class PyDataTestMain(ttk.Frame): def __init__(self, master=None): # Construct the Frame object. ttk.Frame.__init__(self, master) self.grid(sticky=tk.N+tk.S+tk.E+tk.W) self.all_dfs = { # example dataframe at start #'a': pd.DataFrame(), #'b': pd.DataFrame(), } self.createWidgets() #%% Create widgets def createWidgets(self): # Get top window self.top = self.winfo_toplevel() # Make it stretchable self.top.rowconfigure(0, weight=1) self.top.columnconfigure(0, weight=1) # Add several PyDataTest widgets self.p1 = PyDataTest1(self, self.all_dfs) self.p1.grid(row=0, column=0, sticky=tk.W, padx=5, pady=5) self.p2 = PyDataTest2(self, self.all_dfs) self.p2.grid(row=1, column=0, sticky=tk.W, padx=5, pady=5) self.p3 = PyDataTest1(self, self.all_dfs) self.p3.grid(row=2, column=0, sticky=tk.W, padx=5, pady=5) self.p4 = PyDataTest2(self, self.all_dfs) self.p4.grid(row=3, column=0, sticky=tk.W, padx=5, pady=5) #--- PyDataTestMain().mainloop() PyDataTest1.py import tkinter as tk import tkinter.ttk as ttk import tkinter.messagebox as messagebox import pandas as pd class PyDataTest1(ttk.Frame): def __init__(self, master=None, dfs=None): # Construct the Frame object. ttk.Frame.__init__(self, master) self.grid(sticky=tk.N+tk.S+tk.E+tk.W) self.createWidgets() self.dfs = dfs if self.dfs is None: raise("Need DataFrames dictionary") def save(self): var = self.pythonVar.get() self.dfs[var] = pd.DataFrame({'AAA' : [1., 2., 3., …

http://stackoverflow.com/a/48737184
has body: How about subTest? import unittest class TestFoo(unittest.TestCase): def test_bar(self): with self.subTest('Failed'): self.assertEqual(5, 2 + 2) with self.subTest('Passed'): self.assertEqual(1, 1) olivecode's example will looks like this: class TestBar(unittest.TestCase): def test_rest_api_foo(self): r = request("http://dummyurl") with self.subTest('Test status code'): self.assertEqual(r.status_code, 200) with self.subTest('Test text'): self.assertEqual(r.text, "hello world")
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/84497493
score: 2
answers question: http://stackoverflow.com/q/48072486
downvote count: 0

http://stackoverflow.com/comment/83309790
comment on: http://stackoverflow.com/q/48164969
type: Comment
type: QuestionComment
score: 1
has text: You are overwriting the xlsx file with each iteration through the `for` loop. Either build a Pandas dataframe in the loop and write the xlsx file outside the loop or just omit Pandas and use XlsxWriter directly by creating the workbook and worksheet outside the loop and writing the data inside the loop.

http://stackoverflow.com/comment/83239614
type: AnswerComment
type: Comment
has text: Use `int16(h.Numerator)`
comment on: http://stackoverflow.com/a/48131234
score: 0

http://stackoverflow.com/comment/83081999
has text: The python program must be running a loop (the *while True:*) that checks if it is time to run a job. For the method to be executed you have to have executed the line *schedule.every().day.at("01:00").do(job,'It is 01:00')* once before. That line is saying that every day at 1am it should run the method job.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48031438

http://stackoverflow.com/comment/101532195
comment on: http://stackoverflow.com/a/50690729
score: 0
type: AnswerComment
type: Comment
has text: @ImportanceOfBeingErnest you did awesome. Can you please little further modify a code. Because in including "hue" argument in sns.PairGrid(), it is overwriting correlation in upper diagonal. Please see the link for image and code "https://i.sstatic.net/af9He.png" and "https://i.sstatic.net/G1DCY.png"

http://stackoverflow.com/comment/83294725
has text: Seems like a good idea to me.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48157575

http://stackoverflow.com/comment/83252841
score: 1
type: AnswerComment
type: Comment
has text: Thank you so much for your suggestion! Although I didn't use it, I really appreciate your help. I fixed it by using sqlite3, I like this solution because I could use the DB Browser with it.
comment on: http://stackoverflow.com/a/48054296

http://stackoverflow.com/a/48648133
upvote count: 0
has body: related： How do I unload (reload) a Python module? Why are there dummy modules in sys.modules? my answer: import sys for n in filter(lambda x: x.startswith('demo') and x != 'demo', sys.modules): del(sys.modules[n]) reload(demo)
type: Answer
downvote count: 1
score: -1
answers question: http://stackoverflow.com/q/48038180

http://stackoverflow.com/comment/83246512
has text: @Blender that's what I figured too, so how do I make it work, do I need to store the salt separately or how do I get this to work in two separate rest end points?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48134551

http://stackoverflow.com/comment/90820783
type: QuestionComment
comment on: http://stackoverflow.com/q/48050437
has text: I went down this path and ended up using the Docker container: https://github.com/BVLC/caffe/tree/master/docker
score: 0
type: Comment

http://stackoverflow.com/comment/131788766
type: Comment
score: 0
type: AnswerComment
has text: My problem was with the line: panel1.image = image1 # keep a reference Don't know why this is needed? Is it perhaps a bug? Anyways this fixed my problem.
comment on: http://stackoverflow.com/a/48114495

http://stackoverflow.com/comment/83140076
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48082785
has text: Convert them to a string, then operate on that string. `my_float = 0.001; str(my_float).find("1")`
type: Comment

http://stackoverflow.com/q/48104944
score: 0
has title: For Loop Only Iterating Once
answer count: 1
accepted answer: http://stackoverflow.com/a/48160100
tagged with: python-3.x
has body: I'm using the pyvmomi module to export data from our vCenter. I'm very close to getting the desired output, but my script is only iterating through once. Why? If I print(d) in the for loop before updating the dictionary, it will print all of the data. Script Summary: top_dict = {"data": []} def get_obj(content, vimtype, name=None): return [item for item in content.viewManager.CreateContainerView( content.rootFolder, [vimtype], recursive=True).view] ## MAIN ## ... content = si.RetrieveContent() d = {} idnum = 0 for dc in get_obj(content, vim.Datacenter): for cluster in get_obj(content, vim.ClusterComputeResource): for h in cluster.host: host_wwpn1 = '' for adaptr in h.config.storageDevice.hostBusAdapter: if hasattr(adaptr, 'portWorldWideName'): if host_wwpn1 == '': host_wwpn1 = (hex(adaptr.portWorldWideName)[2:18]) else: host_wwpn2 = (hex(adaptr.portWorldWideName)[2:18]) d['id'] = idnum d['datacenter'] = dc.name d['cluster'] = cluster.name d['host'] = h.name d['pwwn_F1'] = host_wwpn1 d['pwwn_F2'] = host_wwpn2 idnum = idnum + 1 top_dict.update({"data": [d]}) Current Output: { "data": [ { "id": 0, "datacenter": "MY_DATACENTER", "cluster": "MY_CLUSTER", "host": "MY_HOSTNAME", "pwwn_F1": "XXXXXXXXXXXXXXXX", "pwwn_F2": "XXXXXXXXXXXXXXXX" } ] }
tagged with: python
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/48160100
type: Question

http://stackoverflow.com/comment/83247647
comment on: http://stackoverflow.com/q/48135100
has text: Thank you so much....I am trying to locate the stacktrace.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83006590
has text: requests==2.18.4@johnII
comment on: http://stackoverflow.com/q/48018622
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83256316
type: QuestionComment
comment on: http://stackoverflow.com/q/48139310
has text: Are you using virtual environment?
score: 0
type: Comment

http://stackoverflow.com/a/48200165
has comment: http://stackoverflow.com/comment/83381494
upvote count: 2
has comment: http://stackoverflow.com/comment/83381814
type: AcceptedAnswer
has body: The Downloads section is not accessible via SSH. You'll need to use other forms of authentication over HTTPS to retrieve those files. (Application passwords may be your best option here, since they can be scoped very specifically and discarded as necessary.)
has comment: http://stackoverflow.com/comment/83381422
has comment: http://stackoverflow.com/comment/83498365
type: Answer
accepted answer of: http://stackoverflow.com/q/48047296
has comment: http://stackoverflow.com/comment/83381353
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48047296

http://stackoverflow.com/comment/83107293
comment on: http://stackoverflow.com/q/48066933
score: 0
type: QuestionComment
type: Comment
has text: Thanks for your repsonses, I will edit the original question to show more rows!

http://stackoverflow.com/comment/86563888
has text: In msys2, the pip is not installed as part of the default packages when python is installed (The version of python installed is 3.6.2). Installation using the pacman did not yield any result was getting error: target not found: error. So downloaded the file manually from location to install pip (9.0.3).
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49737790

http://stackoverflow.com/q/48087336
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48087555
tagged with: python
accepted answer: http://stackoverflow.com/a/48087555
has body: I am using Pycharm 2017.3. My python version is 3.4. I am trying to insert data into table using sqlite4 and pyqt. I have successfully created a table but could not insert even a single data. Here is what I am importing from PyQt4.QtGui import * site_pack_path = "C:\\Python34\\Lib\\site-packages" QApplication.addLibraryPath('{0}\\PyQt4\\plugins'.format(site_pack_path)) from PyQt4.QtSql import * from PyQt4.QtCore import * import sys from urllib.request import Request, urlopen Here is how I have created a table query.exec_("CREATE TABLE dictin(ID INTEGER PRIMARY KEY AUTOINCREMENT, " "word varchar(100), searchShortDefn varchar(300),mnemonics varchar(500), " "defArr varchar(500), defDict varchar(500))") Then there is a function whose purpose is to insert data into table which is not working. def getWordsAndInsert(word, searchShortDefn, mnemonics, defArr, defDict): word=str(word) searchShortDefn=str(searchShortDefn) mnemonics=str(mnemonics) defArr=str(defArr) defDict=str(defDict) print(query.exec_("INSERT INTO dictin(word, searchShortDefn, mnemonics, defArr, defDict) " "VALUES(word, searchShortDefn, mnemonics, defArr, defDict)")) As you can see that I have converted everything to string as my contents are not string. Type of the argument being passed to the getWordsAndInsert method is class 'str' class 'str' class 'str' class 'list' class 'list' respectively. Here is the example of the function getWordsAndInsert being called getWordsAndInsert("abbreviate", "shorten", "abbreviate consists of brevity(means brief)", ['(verb) reduce in scope while retaining essential elements', '(verb) shorten'], [{'syn': ['renounce'], 'sent': ['The King abdicated when he married a divorcee']}]) Though I can insert when I replace variables with actual string but obviously it does not get the work done. print(query.exec_("INSERT INTO dictin(word, searchShortDefn, mnemonics, defArr, defDict) " "VALUES('word', 'searchShortDefn', 'mnemonics', 'defArr', 'defDict')"))
type: AnsweredQuestion
score: 2
upvote count: 2
has title: Can't INSERT data into database using sqlite and pyqt
tagged with: qtsql
type: Question
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/83149613
tagged with: pyqt
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83149907
favorite count: 0

http://stackoverflow.com/q/48143533
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48153132
has comment: http://stackoverflow.com/comment/83283537
type: Question
has comment: http://stackoverflow.com/comment/83265345
has comment: http://stackoverflow.com/comment/83265689
has comment: http://stackoverflow.com/comment/83265246
has comment: http://stackoverflow.com/comment/83283496
has title: why i still can't use the NumPy module even the terminal says "requirement already satisfied"?
has answer: http://stackoverflow.com/a/48160885
has comment: http://stackoverflow.com/comment/83283450
tagged with: numpy
answer count: 2
has body: i was using pip install numpy to install NumPy on my Mac. Then the terminal says that Requirement already satisfied: numpy in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python I guess it means Numpy is already installed? but when i wrote from numpy import array a=array([1,3],int) the python shell says Traceback (most recent call last): File "/Users/bamford/Documents/python/untitled-3.py", line 1, in &lt;module&gt; from numpy import array builtins.ModuleNotFoundError: No module named 'numpy' what is going on?
score: 0

http://stackoverflow.com/q/48094970
type: Question
upvote count: 0
has body: In my django project I did set DEBUG setting to true, and I'm accessing the server from localhost. Despite that instead of error page I get: "A server error occurred. Please contact the administrator.".
answer count: 1
has answer: http://stackoverflow.com/a/48094971
favorite count: 0
accepted answer: http://stackoverflow.com/a/48094971
tagged with: django
tagged with: python
downvote count: 1
type: AnsweredQuestion
score: -1
has title: Django did not display DEBUG error page despite being run on localhost and ``DEBUG=True``

http://stackoverflow.com/comment/83174041
comment on: http://stackoverflow.com/q/48096547
score: 0
type: QuestionComment
type: Comment
has text: I can't upvote yet, but I eventually will

http://stackoverflow.com/a/48086509
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48085001
has body: The Sprite class on codesters appears to have get_x and get_y methods. You should be able implement your position check using something like this: if my_sprite.get_y() &gt; -100: my_sprite.say("I win!") I was able to get an output console by clicking on the console button: I added the following code to get a list of Sprite attributes and methods: for entry in dir(sprite): print entry I did not see get_position in the output.

http://stackoverflow.com/comment/83066811
score: 0
type: Comment
type: QuestionComment
has text: I optimized the queries as fast as possible by using prefetch related and select related everywhere. Proven by the number of queries are only 8 to return lots of nested data.
comment on: http://stackoverflow.com/q/48040545

http://stackoverflow.com/q/48095737
has comment: http://stackoverflow.com/comment/83214654
score: 0
accepted answer: http://stackoverflow.com/a/48112774
answer count: 1
has comment: http://stackoverflow.com/comment/83166415
has comment: http://stackoverflow.com/comment/83214897
has comment: http://stackoverflow.com/comment/83197667
has comment: http://stackoverflow.com/comment/83166237
linked to: http://stackoverflow.com/q/24121421
has body: I have a problem with Django session and i have no idea how to solve it. Basically i store some data in the session dictionary in one view function, and calculate some thing in a second function using the values from the first view. Now if someone opens up two tabs, fills in the data in one and submits it, fills the second tab and submits it, the session dictionary will be the same for both tabs. I hope i phrase myself right. Simple explanation: def a(request): request.session["q"] = request.POST.get('q') def b(request): while True: print(request.session["q"]) So lest assume function a is rendering an index page, and getting a value from there. On a button push in this index page function b is called. Now if i open two tabs, input 1 in to the index page and submit i ll see a lot of 1 in the terminal. Now i open up another tab, input 2, submit, the printing will change. What i would like to do is to keep separate sessions (separate information to come in and go out) from my server to the user on different tabs of a browser. I am sorry if i phrase myself wrong, this is the first time i am trying to work with web servers. EDIT: As i mentioned in the comments the answer is currently not working, and i think it is just a syntax error, however i dont know where i gone wrong. My template: {% load staticfiles %} .... .... {% csrf_token %} .... My view function: def plot(request): print(request.POST.get("session")) .... However in the terminal see nothing printed, thus i think the variable is an empty string.
has title: Django new session for each browser tab
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83166143
has answer: http://stackoverflow.com/a/48112774
type: Question
has comment: http://stackoverflow.com/comment/83181021
tagged with: session

http://stackoverflow.com/comment/83242091
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48129418
has text: @JoshLee Thx a lot! The information is very helpful!
score: 0

http://stackoverflow.com/q/48070555
has body: I'm stuck debugging a custom loss function in KERAS. My problem is at one point there is a division by 0 and some values become NaN which propagates to the loss function. But the reason for 0 appearing in the denominator for me is not obvious. What I would like to see is a dump of y_true and y_pred which result in division by zero. Can I get these values somehow? Like tf.Print but dumping it to file or something similar. def yolo_loss(y_true, y_pred): grid_shape = np.array([7, 7]) # TODO: detect automatically anchors_size = 2 # TODO: detect automatically pred_box = tf.stack(tf.split(y_pred[..., 0:anchors_size * 5], num_or_size_splits=anchors_size, axis=3), axis=3) true_box = tf.stack(tf.split(y_true[..., 0:anchors_size * 5], num_or_size_splits=anchors_size, axis=3), axis=3) pred_box_xy = pred_box[..., 0:2] pred_box_wh = pred_box[..., 2:4] pred_box_conf = pred_box[..., 4:5] # tf.sigmoid( pred_class = y_pred[..., (anchors_size * 5):] true_box_xy = true_box[..., 0:2] true_box_wh = true_box[..., 2:4] true_box_mask = true_box[..., 4:5] # tf.sigmoid( true_class = y_true[..., (anchors_size * 5):] ################################# ### adjust confidence using IoU ################################# true_wh_half = true_box_wh**2 * grid_shape / 2. true_mins = true_box_xy - true_wh_half true_maxes = true_box_xy + true_wh_half pred_wh_half = pred_box_wh**2 * grid_shape / 2. pred_mins = pred_box_xy - pred_wh_half pred_maxes = pred_box_xy + pred_wh_half intersect_mins = tf.maximum(pred_mins, true_mins) intersect_maxes = tf.minimum(pred_maxes, true_maxes) intersect_wh = tf.maximum(intersect_maxes - intersect_mins, 0.) intersect_areas = intersect_wh[..., 0] * intersect_wh[..., 1] true_areas = (true_box_wh[..., 0] * true_box_wh[..., 1])**2 pred_areas = (pred_box_wh[..., 0] * pred_box_wh[..., 1])**2 union_areas = pred_areas + true_areas - intersect_areas + 1e-6 iou_scores = tf.truediv(intersect_areas, union_areas) true_box_conf = tf.expand_dims(iou_scores, 4) * true_box_mask obj_thresho…
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/83117366
has title: Debugging with Tensorflow
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48075148
tagged with: keras
favorite count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48075148
score: 1
upvote count: 1

http://stackoverflow.com/a/49822993
type: Answer
has comment: http://stackoverflow.com/comment/100042887
score: 0
answers question: http://stackoverflow.com/q/48026111
has body: Did you have a look at Job Bookmarks in Glue? It's a feature for keeping the high water mark and works with s3 only. I am not 100% sure, but it may require partitioning to be in place.

http://stackoverflow.com/a/48104835
upvote count: 2
type: Answer
score: 2
has body: To unban a user, you need their user object. The way you seem to be doing it is by passing a user_id in your command and then creating the user object based on that. You could also do it using get_bans() explained below, but I'll answer your question first. Passing user_id in command In your code, mseg is the user_id and banned is the user object. mesg = ctx.message.content[8:] banned = await client.get_user_info(mesg) Edit: As squaswin pointed out, you need to await get_user_info() You are defining user_id as ctx.message.content[8:], which in this case is the text in your message from the 8th character onward with the first character being 0. Based on your code, the following should work: (The numbers below are just to show character position) !unban2 148978391295820384 012345678... The problem with this is if your command name or prefix changes length, then you'll have to change the index in ctx.message.content[8:] to line up with the user_id in your message. The better way is to pass user_id as an argument to your command: async def unban(ctx, user_id): banned = await client.get_user_info(user_id) Now you can use it directly with client.get_user_info(). Using get_bans() You could instead use get_bans() to get a list of banned users, and then use that list to get a valid user object. For example: async def unban(ctx): ban_list = await self.bot.get_bans(ctx.message.server) # Show banned users await bot.say("Ban list:\n{}".format("\n".join([user.name for user in ban_list]))) # Unban last banned user if not ban_list: await bot.say("Ban list is empty.") return try: await bot.unban(ctx.message.server, ban_list[-1]) await bot.say("Unbanned user: `{}`".format(ban_list[-1].name)) except discord.Forbidden: await bot.say("I do not have permission to unban.") return except discord.HTTPException: await bot.say("Unban failed.") return To turn this into a working set of commands, you could create one command to show an indexed list of banned users, and another command to unban …
accepted answer of: http://stackoverflow.com/q/48103177
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48103177

flask-restless
tags question: http://stackoverflow.com/q/48167243
tag name: flask-restless
type: Tag

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/48130426
tags question: http://stackoverflow.com/q/48048623

http://stackoverflow.com/q/48135059
type: UnansweredQuestion
tagged with: python
has body: I want to use the following function of ta-lib. I want to understand the meaning of periods. MAVP MAVP([input_arrays], [minperiod=2], [maxperiod=30], [matype=0]) Moving average with variable period (Overlap Studies) Inputs: price: (any ndarray) periods: (any ndarray) Parameters: minperiod: 2 maxperiod: 30 matype: 0 (Simple Moving Average) Outputs: real It gives an error back when the length of periods is different to the length of price (additionally: it gives back a nparray, if matype is >= 0 and &lt;= 8, else an error is thrown). The original documentation: https://mrjbq7.github.io/ta-lib/func_groups/overlap_studies.html A reference to some (auto generated) documentation: https://www.backtrader.com/docu/talibindautoref.html EDIT: The underlying c code is here: http://svn.code.sf.net/p/ta-lib/code/trunk/ta-lib/c/src/ta_func/ta_MAVP.c also posted here: https://github.com/mrjbq7/ta-lib/issues/175
score: 2
has answer: http://stackoverflow.com/a/48155846
type: Question
downvote count: 0
answer count: 1
tagged with: http://stackoverflow.com/tag/c
tagged with: ta-lib
favorite count: 0
has title: Ta-Lib: What is the Idea of Periods in MAVP - (Moving average with variable period)?
upvote count: 2

http://stackoverflow.com/comment/83297849
comment on: http://stackoverflow.com/a/48159101
type: Comment
score: 2
type: AnswerComment
has text: For me , I even want to `reset_index` rather than working with multiple index , it's pain ...

http://stackoverflow.com/q/48067891
has comment: http://stackoverflow.com/comment/83109390
tagged with: python
has answer: http://stackoverflow.com/a/48067935
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48067935
has body: I make an API get call and save the responses content. I can't show all the API content but here is the name value: "name":"TT REG – 2015 / Test" I create my JSON by doing a json.loads(api_content). My JSON then has a value [{'name': 'TT REG \u2015 / Test'}] listed and I am trying to pull out the 'name' value. I am not able to upload the entire JSON Is this possible with the json[0].get('name')? I don't get back any value but it checks out as a valid JSON file. The \u is in there because the API call that grabs the content contains a - and the \u gets put in when I load the JSON. Answer I found out the issues was that the '-' was an ndash unicode character that some user had used. When running the json.loads command, it gave the equivalent of the unicode character. To resolve this, I ran `json[0].get('name).encode('utf8)
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83109779
score: -1
has comment: http://stackoverflow.com/comment/83171304
upvote count: 0
has comment: http://stackoverflow.com/comment/83109401
answer count: 1
favorite count: 0
has title: How to get a value from a JSON string?

http://stackoverflow.com/q/48131344
answer count: 1
has title: Tkinter: Creating a static frame size inside a pre-existing frame window
favorite count: 0
has answer: http://stackoverflow.com/a/48139020
tagged with: python
tagged with: frame
has body: I have an app that has a frame which houses a gridview of information regarding product data. I want frame3 to have a static window size with a scroll bar. The scroll bar, not implemented yet, will allow the user to scroll down to see the remaining product data not visibly seen inside the static window. My problem is that frame3 as of right now, doesn't seem to have a visible, static frame size. It just looks like it takes up one row in my overall app gridview, as seen in the picture: picture of current program I would like the "Bar Code - Product Description ..." section to acquire most of the screen real-state of the app but i can't seem to get it to work. I've tried creating a canvas inside frame3 but it still doesn't work. Any ideas? The code below is just a short snippet of my overall application frame3 = Frame(self, bg = "black", width = 690, height = 400, borderwidth = 1) frame3.pack() frame3Label1 = tk.Label(frame3, text="Bar Code", font=NORMAL_FONT, relief = SUNKEN, width = 16) frame3Label1.grid(row = 0, column = 0) frame3Label2 = tk.Label(frame3, text="Product Description", font=NORMAL_FONT, relief = SUNKEN, width = 30) frame3Label2.grid(row = 0, column = 1) frame3Label3 = tk.Label(frame3, text="Price", font=NORMAL_FONT, relief = SUNKEN, width = 10) frame3Label3.grid(row = 0, column = 2) frame3Label4 = tk.Label(frame3, text="Quantity", font=NORMAL_FONT, relief = SUNKEN, width = 8) frame3Label4.grid(row = 0, column = 3) frame3Label5 = tk.Label(frame3, text="Discount", font=NORMAL_FONT, relief = SUNKEN, width = 8) frame3Label5.grid(row = 0, column = 4) frame3Label6 = tk.Label(frame3, text="Cost", font=NORMAL_FONT, relief = SUNKEN, width = 10) frame3Label6.grid(row = 0, column = 5) #Function that creates more labels/entry boxes under these static existing labels
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83241659
type: UnansweredQuestion
upvote count: 1
downvote count: 1
type: Question
tagged with: dynamic-resizing
score: 0
has comment: http://stackoverflow.com/comment/83241775

http://stackoverflow.com/q/48121048
favorite count: 0
has answer: http://stackoverflow.com/a/51307811
tagged with: gunicorn
has body: I have a project that is set up to run with docker One one machine which is ubuntu I have been running it fine but recently I have tried to run it on my windows laptop and am getting a ModuleNotFoundError. [2018-01-05 20:31:46 +0000] [5] [INFO] Starting gunicorn 19.7.1 explore_1 | [2018-01-05 20:31:46 +0000] [5] [INFO] Listening at: http://0.0.0.0:8080 (5) explore_1 | [2018-01-05 20:31:46 +0000] [5] [INFO] Using worker: sync explore_1 | [2018-01-05 20:31:46 +0000] [8] [INFO] Booting worker with pid: 8 explore_1 | [2018-01-05 20:31:46 +0000] [8] [ERROR] Exception in worker process explore_1 | Traceback (most recent call last): explore_1 | File "/usr/local/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker explore_1 | worker.init_process() explore_1 | File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process explore_1 | self.load_wsgi() explore_1 | File "/usr/local/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi explore_1 | self.wsgi = self.app.wsgi() explore_1 | File "/usr/local/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi explore_1 | self.callable = self.load() explore_1 | File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load explore_1 | return self.load_wsgiapp() explore_1 | File "/usr/local/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp explore_1 | return util.import_app(self.app_uri) explore_1 | File "/usr/local/lib/python3.6/site-packages/gunicorn/util.py", line 352, in import_app explore_1 | __import__(module) explore_1 | ModuleNotFoundError: No module named 'wsgi' explore_1 | [2018-01-05 20:31:46 +0000] [8] [INFO] Worker exiting (pid: 8) explore_1 | [2018-01-05 20:31:47 +0000] [5] [INFO] Shutting down: Master explore_1 | [2018-01-05 20:31:47 +0000] [5] [INFO] Reason: Worker failed to boot. I checked to make sure my environment variables for paths are set up correctly. Are there a…
has answer: http://stackoverflow.com/a/72780574
type: Question
has comment: http://stackoverflow.com/comment/86781533
tagged with: python
has title: gunicorn: No Module named 'wsgi'
upvote count: 14
has answer: http://stackoverflow.com/a/48121524
has comment: http://stackoverflow.com/comment/83223420
type: UnansweredQuestion
tagged with: flask
has comment: http://stackoverflow.com/comment/83219389
tagged with: docker
answer count: 4
score: 14
has answer: http://stackoverflow.com/a/48121512
has comment: http://stackoverflow.com/comment/137159598
downvote count: 0

http://stackoverflow.com/comment/83305014
has text: Look at the patches in the traceback: you are running on Python 3.6, not 2.7.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48162162

http://stackoverflow.com/comment/83205328
has text: I may be wrong for this specific use-case, but I learned through experience and lectures that, usually, when you have more than 2 nested loops in python, you are doing something wrong.
type: Comment
comment on: http://stackoverflow.com/q/48114708
score: 2
type: QuestionComment

http://stackoverflow.com/comment/83315352
type: Comment
has text: @thebadguy it should be [@aria-label="Search"] not [@label="Search"]
type: QuestionComment
comment on: http://stackoverflow.com/q/48163269
score: 0

http://stackoverflow.com/comment/83159645
comment on: http://stackoverflow.com/q/48090691
score: 0
type: Comment
type: QuestionComment
has text: Thanks, David, Right now I am doing the same. However, I will be happy to know if it is possible to do through pandas plot because I am running 200 different models and manually doing it is a time-consuming task.

http://stackoverflow.com/comment/83116502
has text: Equality comparison is a different thing. `1 == '1'` also works but `1 > '1'` doesn't. (Also `1 == []`, `x == {}` and many others. I wouldn't call this inconsistent.)
comment on: http://stackoverflow.com/a/48071408
score: 2
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83297214
comment on: http://stackoverflow.com/a/48142494
type: AnswerComment
score: 0
has text: The `_` just means a variable you don't use. You can see a more complete answer [here](https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python). `for ident, _, animals in node:` is [tuple unpacking](https://stackoverflow.com/questions/10867882/tuple-unpacking-in-for-loops), its a neater alternative to using numeric indices. Whats clearer `animals` or `item[2]`?
type: Comment

http://stackoverflow.com/comment/83313089
score: 0
comment on: http://stackoverflow.com/a/48157284
type: Comment
type: AnswerComment
has text: "C:\Users\Toshiba\Anaconda3\lib\multiprocessing\process.py", line 93, in run self._target(*self._args, **self._kwargs) File "C:\Users\Toshiba\Anaconda3\lib\multiprocessing\pool.py", line 108, in worker task = get() File "C:\Users\Toshiba\Anaconda3\lib\multiprocessing\queues.py", line 337, in get return _ForkingPickler.loads(res) AttributeError: Can't get attribute 'simulateCase' on <module '__main__' (built-in)>**bold** Am I still missing a step?

http://stackoverflow.com/comment/83006114
score: 0
type: Comment
type: QuestionComment
has text: But show some url so we could see its HTML
comment on: http://stackoverflow.com/q/48018277

http://stackoverflow.com/comment/83327409
comment on: http://stackoverflow.com/a/48173892
type: AnswerComment
has text: Thanks for this, I will try to provide a python way when I have time.
type: Comment
score: 0

http://stackoverflow.com/q/48083843
has body: I have previously asked the question Pandas set element style dependent on another dataframe, which I have a working solution to, but now I am trying to apply it to a data frame with a multi index and I am getting an error, which I do not understand. Problem I have a pandas df and accompanying boolean matrix. I want to highlight the df depending on the boolean matrix. Data import pandas as pd import numpy as np from datetime import datetime date = pd.date_range(start = datetime(2016,1,1), end = datetime(2016,2,1), freq = "D") i = len(date) dic = {'X':pd.DataFrame(np.random.randn(i, 2),index = date, columns = ['A','B']), 'Y':pd.DataFrame(np.random.randn(i, 2),index = date, columns = ['A','B']), 'Z':pd.DataFrame(np.random.randn(i, 2),index = date, columns = ['A','B'])} df = pd.concat(dic.values(),axis=1,keys=dic.keys()) boo = [True, False] bool_matrix = {'X':pd.DataFrame(np.random.choice(boo, (i,2), p=[0.3,.7]), index = date, columns = ['A','B']), 'Y':pd.DataFrame(np.random.choice(boo, (i,2), p=[0.3,.7]), index = date, columns = ['A','B']), 'Z':pd.DataFrame(np.random.choice(boo, (i,2), p=[0.3,.7]), index = date, columns = ['A','B'])} bool_matrix =pd.concat(bool_matrix.values(),axis=1,keys=bool_matrix.keys()) My attempted solution def highlight(value): return 'background-color: green' my_style = df.style for column in df.columns: for i in df[column].index: data = bool_matrix.loc[i, column] if data: my_style = df.style.use(my_style.export()).applymap(highlight, subset = pd.IndexSlice[i, column]) my_style Results The above throws an AttributeError: 'Series' object has no attribute 'applymap' I do not understand what is returning as a Series. This is a single value I am subsetting and this solution worked for non multi-indexed df's as shown below. Without Multi-index import pandas as pd import numpy as np from datetime import datetime np.random.seed(24) date = pd.date_range(start = datetime(2016,1,1), end = datetime(2016,2,1), freq = "D") df = pd.DataFrame({'A': np.linspa…
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: multi-index
accepted answer: http://stackoverflow.com/a/48088927
type: Question
has title: Pandas set element style dependent on another dataframe mith multi index
has answer: http://stackoverflow.com/a/48088927
tagged with: pandas-styles
tagged with: pandas
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/47912420
favorite count: 0

http://stackoverflow.com/a/48085172
type: Answer
answers question: http://stackoverflow.com/q/48084973
upvote count: 1
score: 1
downvote count: 0
has body: In Python, every input is a string, which can be converted to a list of characters. When a list is converted to a set, it keeps the unique elements. So, when your code turns the string of digits into a set, it only keeps the unique digits. Then, when you find the length, it returns the number of unique digits.

http://stackoverflow.com/a/48123814
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48123804
type: Answer
has body: Python dictionaries have a method .get() for this: new_object = dictionary.get('first_name') It takes a key and returns either the value (if set) or a default value (which unless otherwise specified is None).

http://stackoverflow.com/q/48030433
answer count: 1
tagged with: raspberry-pi3
has answer: http://stackoverflow.com/a/48030462
tagged with: python
has title: How to install and use python PyGObject "Notify" (or equivalent) on a RPi3
type: AnsweredQuestion
tagged with: pygobject
score: 0
tagged with: pip
accepted answer: http://stackoverflow.com/a/48030462
type: Question
has body: I'm trying to install a Python based package from a github repo originally meant for another (probably Debian based) Linux distribution. The program seem to use Python2, and the imports are given as follows: import argparse import logging import Queue import collections import ConfigParser import os import socket import random import gi gi.require_version('Notify', '0.7') from gi.repository import Notify from multiprocessing import Process, Queue as MPQueue, Event ... def notif(msg): Notify.init("TheProg") notice = Notify.Notification.new("Critical !", msg) notice.set_urgency(2) However, when I try to run the program I get this: $ python2 main.py -h Traceback (most recent call last): File "main.py", line 11, in <module> gi.require_version('Notify', '0.7') File "/usr/lib/python2.7/dist-packages/gi/__init__.py", line 100, in require_version raise ValueError('Namespace %s not available' % namespace) ValueError: Namespace Notify not available I've googled myself tired and the only thing I find are some cryptic references to the PyGObject API Reference: gir1.2-notify-0.7 (0.7.7-3) Parent Project: Desktop notification library (libnotify is a library for sending desktop notifications) Description: A library that sends desktop notifications to a notification daemon, as defined in the Desktop Notifications spec. These notifications can be used to inform the user about an event or display some form of information without getting in the user’s way. Running pip2 search notify returns hundreds of seemingly irrelevant stuff. Same with apt search notify. Q: How can I find and install the correct Notify thing?
tagged with: notify

http://stackoverflow.com/comment/83033021
comment on: http://stackoverflow.com/a/48031325
has text: i got this error after uninstall tabula "ImportError: No module named tabula "
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48081478
has answer: http://stackoverflow.com/a/48085041
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Django: Trying to click on a link and remove an assigned client
has body: Good morning. I am having an issue trying to remove a client from an assigned bed. I created a one-item form called "RoomUpdate" that will allow a user to add a client to a bed that is empty via a dropdown through a ModelChoiceField. When the bed is full, it does not allow the access to the drop down, instead, I have a link that states "remove client." What I want to happen is when I click that button, it assigns the default value of None to that bed in that room. What's tricky, at least to my new-ish to Django mind, is how I do this through multiple tables. Having looked for multiple answers and tried different things, I know I've lost track of what I'm doing so I definitely could use some help. models.py class Room(models.Model): room_id = models.AutoField(primary_key=True) room_number = models.CharField(max_length=5) shelter_id = models.ForeignKey(Shelter) max_occupancy = models.CharField(max_length=3) floor_location = models.CharField(max_length=3) def __str__(self): return self.room_number class Bed(models.Model): bed_id = models.AutoField(primary_key=True) room_id = models.ForeignKey(Room, related_name='beds') bed_size = models.ForeignKey(BedSize) client_assigned = models.ForeignKey(Clients, null=True, blank=True, default=None) forms.py class RoomUpdate(forms.ModelForm): client_assigned = forms.ModelChoiceField(queryset=Clients.objects.all(), required=False) #def __init__(self, *args, **kwargs): #super(RoomUpdate, self).__init__(*args, **kwargs) #self.fields['client_assigned'].choices.insert(0, ('','---------' ) ) class Meta: model = Room fields = ( 'client_assigned', ) views.py def room_update(request, pk, template_name='shelter/room_edit.html'): rooms = get_object_or_404(Room, pk=pk) form = RoomUpdate(request.POST or None, instance=rooms) beds = Bed.objects.filter(room_id=pk) if form.is_valid(): form.save() return redirect('/shelter/') return render(request, template_name, {'form': form, 'rooms': rooms, 'beds':beds,}) def remove_client(request, pk): rooms = …
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48103052
score: 0

http://stackoverflow.com/a/48087625
type: Answer
has comment: http://stackoverflow.com/comment/83175609
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83156960
upvote count: 2
has body: Looking at the source code, it looks like giving pandas a precision higher than 19 allows you to leap-frog over a loop that is otherwise going to run (provided your dtype isn't either datetime64 or timedelta64; see Line 326). The relevant code begins on Line 393 and goes to Line 415. Double comments are mine: ## This function figures out how far to round the bins after decimal place def _round_frac(x, precision): """ Round the fractional part of the given number """ if not np.isfinite(x) or x == 0: return x else: frac, whole = np.modf(x) if whole == 0: digits = -int(np.floor(np.log10(abs(frac)))) - 1 + precision else: digits = precision return np.around(x, digits) ## This function loops through and makes the cuts more and more precise ## sequentially and only stops if either the number of unique levels created ## by the precision are equal to the number of bins or, if that doesn't ## work, just returns the precision you gave it. ## However, range(100, 20) cannot loop so you jump to the end def _infer_precision(base_precision, bins): """Infer an appropriate precision for _round_frac """ for precision in range(base_precision, 20): levels = [_round_frac(b, precision) for b in bins] if algos.unique(levels).size == bins.size: return precision return base_precision # default Edit: Contrived Example Say you have a list my_list and it has six elements that you want to split into three bins: test = [1.121, 1.123, 1.131, 1.133, 1.141, 1.143] Clearly you want the split after 1.123 and 1.133, but say you didn't give pandas the bins directly but rather the number of bins (n_bins = 3). Pretend pandas starts its guesswork with cuts that split the data evenly into 3 (NOTE: I don't know if this is how pandas picks initial cuts - this is just for example purposes): # To calculate where the bin cuts start x = (1.143 - 1.121)/3 cut1 = 1.121 + x # 1.1283 cut2 = 1.121 + (2*x) # 1.1356 bins = [cut1, cut2] But on top of this suppose you suggested pandas use precision of 1. Applying this pr…
answers question: http://stackoverflow.com/q/48081901

http://stackoverflow.com/q/48056858
tagged with: sql
tagged with: sqlite
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83096121
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/83086061
has body: I am creating a new dataframe each time through loops so that I can calculate the sum but I am getting wrong answers as the data is quite huge (around 3 million rows) Is there anyother approach to this ?: df = pd.read_sql_query( "SELECT DISTINCT SYMBOL FROM tableA WHERE TIM ==?;", conn, params={datetime_object} ) for sym in df.SYMBOL: df2 = pd.read_sql_query( "SELECT SYMBOL,OPEN FROM tableA WHERE TIM ==? AND SYMBOL ==? AND EXP==?;", conn, params={datetime_object,sym,exp} ) Total = df2['OPEN'].sum() I am getting correct sum for few rows but 0 as for others, I think some memory issue! Thanks in advance!
has title: creating a new dataframe each time and applying sum
score: 0
tagged with: pandas

cython
tags question: http://stackoverflow.com/q/48047688
tags question: http://stackoverflow.com/q/48099543
tags question: http://stackoverflow.com/q/48088886
tags question: http://stackoverflow.com/q/48040794
tags question: http://stackoverflow.com/q/48165702
tags question: http://stackoverflow.com/q/48153924
type: Tag
tag name: cython
tags question: http://stackoverflow.com/q/48099216
tags question: http://stackoverflow.com/q/48070677
tags question: http://stackoverflow.com/q/48136122
tags question: http://stackoverflow.com/q/48027613
tags question: http://stackoverflow.com/q/48103343

http://stackoverflow.com/comment/83320094
comment on: http://stackoverflow.com/q/48108496
score: 0
has text: I almost always use LP solvers for this (they perform well, and allow extensions to the model). There is lots of information around how to solve LPs from R. There are also a few more specialized R packages that deal with the transportation problem directly (google will help you).
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48098951
has body: I have built a TensorFlow model that uses a DNNClassifier to classify input into two categories. My problem is that Outcome 1 occurs upwards of 90-95% of the time. Therefore, TensorFlow is giving me the same probabilities for all of my predictions. I am trying to predict the other outcome (e.g. having a false positive for Outcome 2 is preferable to missing a possible occurrence of Outcome 2). I know that in machine learning in general, in this case it would be worthwhile to try to upweight Outcome 2. However, I don't know how to do this in TensorFlow. The documentation alludes to it being possible, but I can't find any examples of what it would actually look like. Has anyone has successfully done this, or does anyone know where I could find some example code or a thorough explanation (I'm using Python)? Note: I have seen exposed weights being manipulated when someone is using the more fundamental parts of TensorFlow and not an estimator. For maintenance reasons, I need to do this using an estimator.
linked to: http://stackoverflow.com/q/52383967
favorite count: 0
tagged with: deep-learning
upvote count: 7
has title: Upweight a Category
answer count: 1
has answer: http://stackoverflow.com/a/48099304
accepted answer: http://stackoverflow.com/a/48099304
has comment: http://stackoverflow.com/comment/110335453
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 7
linked to: http://stackoverflow.com/q/47034888
tagged with: tensorflow
type: Question

http://stackoverflow.com/a/48146924
downvote count: 1
score: 3
upvote count: 4
answers question: http://stackoverflow.com/q/48145317
has comment: http://stackoverflow.com/comment/83305688
has body: A more universal solution with a help decorator. from functools import wraps def attributes(**attrs): def decorator(f): @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) for attr_name, attr_value in attrs.items(): setattr(wrapper, attr_name, attr_value) return wrapper return decorator and rewrite you class as class A: def __init__(self): self.size = 0 @attributes(modifies='size') def change_size(self, new): self.size = new
type: Answer
has comment: http://stackoverflow.com/comment/83306497
has comment: http://stackoverflow.com/comment/83286929

bayesian
tags question: http://stackoverflow.com/q/48123091
tag name: bayesian
type: Tag

http://stackoverflow.com/comment/83143500
type: Comment
type: QuestionComment
has text: @xNinjaKittyx . you are right. The iterator belongs to Dictionary which naturally giving out only one value of the dict. I have to iter over value of 'i' inside the generator for loop
comment on: http://stackoverflow.com/q/48082725
score: 0

http://stackoverflow.com/comment/83105411
score: 1
comment on: http://stackoverflow.com/a/48049510
type: AnswerComment
type: Comment
has text: Usually, it's the project maintainer/developer who creates the wheels and uploads them to PyPI. He is responsible of building wheels that run on every platform/language implementation that are advertised to be supported (smth like `mypkg-0.1-cp35.cp36-abi3-any.whl` could be imaginable). If someone pulls your source code and builds a wheel that doesn't run, you can't be responsible for that ;-)

http://stackoverflow.com/comment/107852828
type: Comment
comment on: http://stackoverflow.com/a/54265630
has text: Good addition. Seems that Keras now supports the use of both weights simultaneously (updated my answer)
score: 0
type: AnswerComment

http://stackoverflow.com/q/48107708
linked to: http://stackoverflow.com/q/20646822
downvote count: 0
has comment: http://stackoverflow.com/comment/83191181
linked to: http://stackoverflow.com/q/28207761
type: Question
has title: how do I load image in python flask?
has comment: http://stackoverflow.com/comment/83191209
tagged with: flask
tagged with: image
linked to: http://stackoverflow.com/q/17681762
has comment: http://stackoverflow.com/comment/83191086
upvote count: 2
has body: so.... I'm a beginner in python flask trying to make a dashboard. I have a folder where my uploaded pictures are located. structure: manage.py # this is where I run the program. src |--pic |--items |-- pic_here.jpg how should I set up so I could load the picture and get it into &lt;img&gt;? I tried searching but all they showed was how to set up static folders. I don't think this is one for static, the pictures are what I upload via dashboard. in other words, src/pic/items is where my saved images are located and how do I set my flask to load this picture?
answer count: 2
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/48107969
favorite count: 0
possible better answer: http://stackoverflow.com/a/48109486
has answer: http://stackoverflow.com/a/48109486
duplicate of: http://stackoverflow.com/q/20646822
tagged with: python
has answer: http://stackoverflow.com/a/48107969
has comment: http://stackoverflow.com/comment/83190862
type: AnsweredQuestion
score: 2

http://stackoverflow.com/a/48037933
upvote count: 2
type: Answer
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48037903
has body: import numpy as np df = # your data frame df['newcolumn'] = np.where(df['cell'] &gt; x, 1, 0) See numpy.where docs for more details.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48037903

http://stackoverflow.com/comment/83156264
has text: I updated the post with the error now.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48090861
type: Comment

http://stackoverflow.com/a/48408843
downvote count: 0
has body: Here is how to install python packages in Visual Studio Right click on python environment and click Install Python Package Then in Python Environments explorer search for the package and click the link to install.
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48154250
score: 2

http://stackoverflow.com/comment/83149984
score: 1
comment on: http://stackoverflow.com/q/48087525
type: QuestionComment
has text: Possible duplicate of [query runs in sql server studio but not when called via python pyodbc](https://stackoverflow.com/questions/48086032/query-runs-in-sql-server-studio-but-not-when-called-via-python-pyodbc)
type: Comment

junit
type: Tag
tag name: junit
tags question: http://stackoverflow.com/q/48075855

http://stackoverflow.com/q/48094940
has comment: http://stackoverflow.com/comment/83167250
has comment: http://stackoverflow.com/comment/83167185
has body: I have been trying to output get result of both author name and book name is the same json dict, I got the all the books written by an author but I want author name before books too and here is the relevant code: Models class Books(models.Model): bid = models.BigIntegerField(primary_key=True) bname = models.CharField(max_length=200, blank=True, null=True) bdescription = models.TextField(blank=True, null=True) def __str__(self): return self.bname class Authors(models.Model): aid = models.AutoField(primary_key=True) aname = models.CharField(max_length=200, blank=True, null=True) adescription = models.TextField( blank=True, null=True) def __str__(self): return self.aname+"\n" class Bookauth(models.Model): bid = models.ForeignKey(Books, on_delete=models.DO_NOTHING, db_column='bid', blank=True, null=True) aid = models.ForeignKey(Authors, on_delete=models.DO_NOTHING, db_column='aid', blank=True, null=True) Views def authbook(request): l = request.GET.get('bks', '') r = Books.objects.filter(bookauth__aid = l).values('bname') s = Authors.objects.filter(aid = l).values('aname') return JsonResponse({s: list(r)}) this code obviously gives an error regarding s not being a string.
downvote count: 0
has comment: http://stackoverflow.com/comment/83165055
favorite count: 0
has comment: http://stackoverflow.com/comment/83164981
type: UnansweredQuestion
has title: How to join two different ORM query to return them as one JSON object
tagged with: python
answer count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83167117
tagged with: django-models
has comment: http://stackoverflow.com/comment/83164528
has comment: http://stackoverflow.com/comment/83166886

http://stackoverflow.com/comment/83305865
type: Comment
type: QuestionComment
has text: glad it worked out! could you pls accept the answer?
comment on: http://stackoverflow.com/q/48153854
score: 0

http://stackoverflow.com/q/48065278
has answer: http://stackoverflow.com/a/48065393
type: Question
has answer: http://stackoverflow.com/a/48065389
favorite count: 0
has title: While Loop Concatenation Exercise
answer count: 3
has answer: http://stackoverflow.com/a/48065391
accepted answer: http://stackoverflow.com/a/48065391
tagged with: python
tagged with: python-3.x
has body: I'm just starting to learn Python and have a question regarding an exercise that came up in the textbook I'm reading. I found a solution that does function, but I'm wondering if there is a simpler/recommended solution? Problem: numXs = int(input('How many times should I print the letter X? ')) toPrint = ' ' #concatenate X to print numXs times print(toPrint) My solution: numXs = int(input('How many times should I print the letter X? ')) toPrint = '' while (toPrint == ''): if numXs == 0: numXs = int(input('Enter an integer != 0 ')) else: toPrint = abs(numXs) * 'X' print(toPrint)
possible better answer: http://stackoverflow.com/a/48065389
upvote count: 3
downvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83103841
score: 1

http://stackoverflow.com/comment/83250645
has text: Thanks!!! I am able to see only the Success result, need the failed in as well. i need the result separately for success and fail in the respective variable. Since, i have to include the success result in separate email body and fail result in separate email body to send email.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48136458

http://stackoverflow.com/a/48045458
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/83105290
has comment: http://stackoverflow.com/comment/83106076
has comment: http://stackoverflow.com/comment/83106984
score: 4
accepted answer of: http://stackoverflow.com/q/48037799
answers question: http://stackoverflow.com/q/48037799
has comment: http://stackoverflow.com/comment/83106967
type: AcceptedAnswer
has body: The built in DatetimeAxis does not really expose a minor tick configuration corresponding to your use case. So your options would be: create a custom extension to return exactly the major and minor ticks you want Use a "day" ticker for every day and hide ticks you don't want to see, as you suggested. The second path (your idea) is probably the simplest to get started. Here is a complete code sample that uses FuncTickFormatter to generate "blank" tick labels except every fifth day: import numpy as np import pandas as pd from bokeh.io import output_file, show from bokeh.models import DaysTicker, FuncTickFormatter from bokeh.plotting import figure x = pd.date_range("2017-12-01", "2017-12-31") y = ([1,3,4]*11)[:31] p = figure(plot_width=800, x_range=(x[0], x[-1]), x_axis_type="datetime") p.line(x, y, line_dash="4 4", line_width=1, color='gray') p.xaxis.ticker = DaysTicker(days=np.arange(1,32)) p.xaxis.major_label_orientation = 1.5 p.xaxis.formatter = FuncTickFormatter(code=""" var date = new Date(tick) var day = date.getUTCDate(date) if ( day%5 == 0 ) { return day } else { return "" } """) output_file("foo.html") show(p) That generates this output If you want more than just the day number, you would tweak the first if branch in the JS code for the FuncTickFormatter to do more than just return day
has comment: http://stackoverflow.com/comment/83105220
type: Answer

http://stackoverflow.com/comment/83063142
has text: If you have a transcript of the git commands you've entered, a git expert (probably not me) might be able to help you recover the file. To the best of my knowledge, the changes have to have been either [staged](https://softwareengineering.stackexchange.com/q/119782/13014), [stashed](https://git-scm.com/book/en/v1/Git-Tools-Stashing), or committed to be recoverable.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48045736
type: Comment

http://stackoverflow.com/q/48123877
downvote count: 0
tagged with: python
has body: I have a tensor of type tf.int32 I would like to use tf.Print but I need the result to be in binary. Is this even possible? It is for debugging. Example: constant = tf.constant(5) #magic tf.Print(constant) # prints 101
type: AnsweredQuestion
tagged with: tensorflow
type: Question
answer count: 1
score: 4
favorite count: 0
tagged with: type-conversion
has title: Print an integer tensor in binary
has comment: http://stackoverflow.com/comment/83225436
linked to: http://stackoverflow.com/q/35304920
upvote count: 4
tagged with: integer
tagged with: binary
has answer: http://stackoverflow.com/a/48125687
accepted answer: http://stackoverflow.com/a/48125687

http://stackoverflow.com/comment/83243565
has text: @NaN Ah, my knowledge of matplotlib is very surface level... but this might help: https://stackoverflow.com/questions/28766692/intersection-of-two-graphs-in-python-find-the-x-value
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48132182
type: Comment

http://stackoverflow.com/a/49992539
upvote count: 1
answers question: http://stackoverflow.com/q/48095790
downvote count: 0
has body: I am just going through this myself - I think there are some earlier answers about setting up an external tool to produce a report, but this exists and sounds like exactly what you want. Pylint-Pycharm Pylint-Pycharm is a wrapper around Pylint that formats file paths in the Pylint output in a way that Pycharm can parse. This allows you to go to finding directly by clicking on the provided link. The tool accepts the directory of a virtual environment as parameter and requires the paths of one or more Python files as input. The Python files/modules and all additional command line parameters are handed over to Pylint. To configure as an 'external tool' in Pycharm (after you've run Setup.py): command: pylint-pycharm arguments: $FilePath$ [you can also pass in a virtualenv with --venv=, and other params for pylint such as your own pylintrc file] directory: $FileDir$ Now the messages contain a link to the line in question. To use straight pylint, configure per these instructions: https://www.mantidproject.org/How_to_run_Pylint
type: Answer
score: 1

http://stackoverflow.com/q/48134483
answer count: 0
has body: I am using Sublime Text 3 and already have anaconda installed. My question is if I install a package is their an autocomplete that goes out and searches for the modules of that package. I have noticed that anaconda has the basic datetime modules and such but I am using appJar which has a ton of CamelCase stuff I am just getting bogged down. I guess there are two options: Is there an autocomplete that can be pointed at documentation to create its library. Is there an autocomplete that has appJars modules. Is there something better out there then anaconda? Thanks in advance
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83246470
tagged with: autocomplete
downvote count: 0
score: 1
favorite count: 0
has title: Is it possible to configure sublime text to autocomplete for an installed package?
type: UnansweredQuestion
tagged with: python
tagged with: sublimetext3

http://stackoverflow.com/q/48088562
has answer: http://stackoverflow.com/a/48088691
possible better answer: http://stackoverflow.com/a/48093905
tagged with: output
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83160290
has body: I created a function that returns grammatical characteristics to a set of words: import nltk.tokenize from io import StringIO def get_pos_tag(string): detM =['un','le'] nomM =['garçon','verre','chair'] #Entréé test = nltk.word_tokenize(string) #Pos-Tag de chaque entréé for i in range(0,len(test)): #Déterminant masculin singulier if test[i] in detM: CAT = "Det" Nb = "Sg" GND = "M" return(test[i],":","CAT:",CAT,",","Genre:",GND,",","Nombre:",Nb) #Nom Masculin Singulier elif test[i] in nomM: CAT = "N" Nb = "Sg" GND = "M" return(test[i],":","CAT:",CAT,",","Genre:",GND,",","Nombre:",Nb) Now in another script when I want to save the output of the function to either a string or a list, this is what am getting: &gt;&gt;&gt;import PosTag &gt;&gt;&gt; var1=PosTag.get_pos_tag("un garçon") un : CAT: Det , Genre: M , Nombre: Sg garçon : CAT: N , Genre: M , Nombre: Sg &gt;&gt;&gt; print (var1) None &gt;&gt;&gt; var2=[] &gt;&gt;&gt; var2.append(PosTag.get_pos_tag("un garçon")) un : CAT: Det , Genre: M , Nombre: Sg garçon : CAT: N , Genre: M , Nombre: Sg &gt;&gt;&gt; print(var2) [None] And I need the result to be stored in a variable to use it next.
type: Question
accepted answer: http://stackoverflow.com/a/48088691
answer count: 2
tagged with: function
score: 0
has title: Can't save the output of a function to a list or a string, How does a function return multiple values in Python
tagged with: python
has answer: http://stackoverflow.com/a/48093905
has comment: http://stackoverflow.com/comment/83160696
tagged with: python-3.x

http://stackoverflow.com/comment/83068145
type: Comment
type: QuestionComment
has text: ok, this actually gave me the same error as above, 4 times, then said the requirement already satisfied. Any idea on whats happening ? error: Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x0000000004281780>: Failed to establish a new connection: [Errno 10061] No connection could be made because the target machine actively refused it',))': /simple/pip/
score: 0
comment on: http://stackoverflow.com/q/48048239

http://stackoverflow.com/a/48082117
has body: You can use numpy's array operations to represent your "loop". If you think of data as bellow, where pL and pR are the values you choose to "pad" your data with on the left and right: [pL, 0, 1, 2, ..., N-2, N-1, pR] What you're trying to do is this: [0, ..., N - 1] * ([pL, 0, ..., N-2] + [1, ..., N -1, pR]) / 2 Written in code it looks something like this: import numpy as np data = np.random.random(10) padded = np.concatenate(([data[0]], data, [data[-1]])) data * (padded[:-2] + padded[2:]) / 2. Repeating the first and last value is known as "extending" in image processing, but there are other edge handling methods you could try.
type: Answer
answers question: http://stackoverflow.com/q/48081412
has comment: http://stackoverflow.com/comment/83146151
accepted answer of: http://stackoverflow.com/q/48081412
has comment: http://stackoverflow.com/comment/83140595
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48149675
type: Answer
answers question: http://stackoverflow.com/q/48142485
score: 0
has body: What ended up being the solution is: quiz = Quiz.objects.get(pk=pkofquiziwanttocopy) quiz.pk = None quiz.save() old_quiz = Quiz.objects.get(pk=pkofquiziwanttocopy) quiz.question_set=old_quiz.question_set.all()

http://stackoverflow.com/a/48039360
answers question: http://stackoverflow.com/q/48039312
accepted answer of: http://stackoverflow.com/q/48039312
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/117074644
has body: You are treating x and y values as strings whilst you should parse them as numbers: xs.append(float(x)) ys.append(float(y)) Alternatively: x, y = map(float, line.split(',')) Result:
score: 6
type: Answer
downvote count: 0
upvote count: 6

http://stackoverflow.com/comment/83105982
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48063550
has text: Oh I see, makes sense.
score: 0

http://stackoverflow.com/comment/83197667
comment on: http://stackoverflow.com/q/48095737
type: Comment
type: QuestionComment
score: 0
has text: @mohammedqudah Thanks a lot, i am really stuck with this.

http://stackoverflow.com/comment/83075272
has text: @Axalix: thanks for the comment. My `.py` file check many `.txt` files for errors, that `.txt` files consistent with the rules of a one service. For example, it check, contains mandatory word in a file or no — as in example. // If I see all errors immediately, I can quickly fix them. I don't think, that exit program after each fail — is a good behavior in my case.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48051166

http://stackoverflow.com/a/48043920
answers question: http://stackoverflow.com/q/48043555
score: 0
has body: Thanks Patrick With the hint i was able to cancel every process by adding the Futures to a list and adjusting the queue size manually. Without it there are still to much processes which are getting launched. Just seems like there is no api to adjust the queue size, pause the execution or delete the process queue. However - the only way to realize this is to run the Main object in a Thread so the mainscript can kill it at any time. And im still trying to catch the "CancelledError". Looks pretty "dirty" and not pythonic for me. I'll take any other suggestions. Thanks a lot. from concurrent.futures import ProcessPoolExecutor, CancelledError from time import sleep from random import randint from threading import Thread def something_fancy(): sleep(randint(0, 5)) return 'im back!' class Work: def __init__(self): self.exe = ProcessPoolExecutor(4) self.futures = [] self.max_queue = 50 self.killed = False def start_procs(self): for i in range(200000): while not self.killed: if len(self.futures) &lt;= self.max_queue: t = self.exe.submit(something_fancy) t.add_done_callback(self.done) self.futures.append(t) break def done(self, f): print f.result() self.futures.remove(f) def kill(self): self.killed = True for future in self.futures: try: future.cancel() except CancelledError, e: print e if __name__ == '__main__': work_obj = Work() Thread(target=work_obj.start_procs).start() sleep(5) work_obj.kill() edit from concurrent.futures import ProcessPoolExecutor, CancelledError from time import sleep from random import randint from threading import Thread def something_fancy(): sleep(0.5) return 'Hello World, Future was running!' class Work: def __init__(self): cpu_usage = 4 self.exe = ProcessPoolExecutor(cpu_usage) self.futures = [] self.max_queue = cpu_usage*3 self.stop = False self.paused = False def start_procs(self): for i in range(200000): while not self.stop: if len(self.futures) &lt;= self.max_queue: if not self.paused: t = self.exe.submit(something_fancy) t.add_done_callback(…
type: Answer

http://stackoverflow.com/q/48172863
upvote count: 2
answer count: 2
tagged with: hdf5
has comment: http://stackoverflow.com/comment/83347284
has body: I have multiple pd.DataFrames which have hierarchical organization. Let's say I have: day_temperature_london_df = pd.DataFrame(...) night_temperature_london_df = pd.DataFrame(...) day_temperature_paris_df = pd.DataFrame(...) night_temperature_paris_df = pd.DataFrame(...) And I want to group them into hdf5 file so two of them go to group 'london' and two of others go to 'paris'. If I use h5py I lose the format of the pd.DataFrame, lose indexes and columns. f = h5py.File("temperature.h5", "w") grp_london = f.create_group("london") day_lon_dset = grp_london.create_dataset("day", data=day_temperature_london_df) print day_lon_dset[...] This gives me a numpy array. Is there a way to store many dataframes with hierarchy in the same way .to_hdf does - it keeps all the properties of the dataframe?
has answer: http://stackoverflow.com/a/48179235
has answer: http://stackoverflow.com/a/48185427
has title: save multiple pd.DataFrames with hierarchy to hdf5
has comment: http://stackoverflow.com/comment/83330993
tagged with: numpy
linked to: http://stackoverflow.com/q/47165911
possible better answer: http://stackoverflow.com/a/48185427
type: AnsweredQuestion
score: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48179235
type: Question
has comment: http://stackoverflow.com/comment/83336422
tagged with: h5py
tagged with: pandas
has comment: http://stackoverflow.com/comment/83328464
tagged with: python
linked to: http://stackoverflow.com/q/41173254

http://stackoverflow.com/q/48048279
favorite count: 0
has answer: http://stackoverflow.com/a/61494336
possible better answer: http://stackoverflow.com/a/60596229
answer count: 20
has answer: http://stackoverflow.com/a/60596229
has answer: http://stackoverflow.com/a/63277862
downvote count: 2
has answer: http://stackoverflow.com/a/59535067
linked to: http://stackoverflow.com/q/48760475
has answer: http://stackoverflow.com/a/59234132
tagged with: python
upvote count: 23
has answer: http://stackoverflow.com/a/62799434
linked to: http://stackoverflow.com/q/48420759
accepted answer: http://stackoverflow.com/a/48054575
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/73604717
score: 21
has answer: http://stackoverflow.com/a/58546340
has answer: http://stackoverflow.com/a/61649361
has answer: http://stackoverflow.com/a/62746022
has answer: http://stackoverflow.com/a/59949460
type: Question
has answer: http://stackoverflow.com/a/66937831
has answer: http://stackoverflow.com/a/69400219
has answer: http://stackoverflow.com/a/63550800
has answer: http://stackoverflow.com/a/48286813
has answer: http://stackoverflow.com/a/73237637
has answer: http://stackoverflow.com/a/65256640
has title: TypeError: Cannot read property '_uploadFiles' of undefined in google colaboratory
tagged with: google-colaboratory
has body: I am trying to write upload the file in Google Colaboratory and I'm going to write the code as below. from google.colab import files uploaded = files.upload() But I am getting the below error to run the code in browser. MessageError: TypeError: Cannot read property '_uploadFiles' of undefined Please help me solve the issue.
has answer: http://stackoverflow.com/a/60646168
has answer: http://stackoverflow.com/a/48054575
has answer: http://stackoverflow.com/a/78035815

http://stackoverflow.com/comment/83068316
type: Comment
has text: yup. sounds like a network issue of some sort. Just tried pip uninstall pandas... and now can't install it :-/ oops. will try to diagnose and post on here once i figure it out. Thanks for the help!
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48048239

http://stackoverflow.com/a/48039679
has comment: http://stackoverflow.com/comment/83050090
score: 1
answers question: http://stackoverflow.com/q/48039657
downvote count: 0
has body: If you have a firm requirement on the None final output I'd use this: result = [i for i in l if i &gt; 0] or None This way, if you end up with no elements it gives you None instead.
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83050070

http://stackoverflow.com/q/48117247
tagged with: python
type: AnsweredQuestion
upvote count: 1
tagged with: plot
type: Question
has answer: http://stackoverflow.com/a/48149916
score: 1
tagged with: matplotlib
tagged with: image
has body: I'm trying to plot some data as an image of a given size (for use as an overlay). However, despite calling set_axis_off() and setting bbox_inches="tight" and pad_inches=0 on savefig (as suggested in other questions), I still get padding, and a larger image size than the figsize should result in. Here's the code (the PIL dependency is for ease of use but can be removed by removing the last line): from PIL import Image import matplotlib.pyplot as plt def plot_box(data, size, filename="plot.png"): """Plot the data in an image whose dimensions are size x size pixels""" fig = plt.figure(figsize=(size/100,size/100), dpi=100) ax = fig.add_axes((0,0,1,1)) ax.set_axis_off() ax.plot(data) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.savefig(filename, bbox_inches="tight", pad_inches=0, dpi='figure', transparent=True) plt.close() return Image.open(filename) However, regardless of the size I specify, the images are always either 6 or 7 pixels wider in both directions: &gt;&gt; data = [i**2 for i in range(-100, 101)] &gt;&gt; plot_box(data, 50) &lt;PIL.PngImagePlugin.PngImageFile image mode=RGBA size=57x57 at 0xED3CB38&gt; &gt;&gt; plot_box(data, 100) &lt;PIL.PngImagePlugin.PngImageFile image mode=RGBA size=106x106 at 0xF208908&gt; &gt;&gt; plot_box(data, 1) &lt;PIL.PngImagePlugin.PngImageFile image mode=RGBA size=8x8 at 0x53D2748&gt; Any ideas? Update Here's the resulting image from plot_box(data, 100). As you can see, it looks fine other than being larger than expected due to padding (106x106 rather than 100x100).
has comment: http://stackoverflow.com/comment/83211167
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83210772
favorite count: 0
accepted answer: http://stackoverflow.com/a/48149916
has title: Remove padding in a matplotlib line plot that already uses set_axis_off, bbox_inches=tight and pad_inches=0?

http://stackoverflow.com/a/48152366
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48152309
downvote count: 0
answers question: http://stackoverflow.com/q/48152309
has body: I think you need add_suffix with join: cols = ['offer_id', 'affiliate_id', 'affiliate_source'] df2 = df1.groupby(cols)"payout_cents", "revenue_cents".sum().add_suffix('_sum') df = df1.join(df2, on=cols) print (df) offer_id affiliate_id affiliate_source affiliate_sub5 advertiser_id \ 0 428572 1327 14331605 14331605 291 1 428572 1327 1465 1465 291 2 428572 1327 1336 1336 291 3 428572 1327 14331605 14331605 291 4 428572 1327 14331605 14331605 291 payout_cents revenue_cents payout_cents_sum revenue_cents_sum 0 50 30 150 90 1 50 30 50 30 2 50 30 50 30 3 50 30 150 90 4 50 30 150 90 Another solution with transform: cols = ['offer_id', 'affiliate_id', 'affiliate_source'] cols1 = ["payout_cents", "revenue_cents"] df1[['{}_sum'.format(x) for x in cols1]] = df1.groupby(cols)[cols1].transform('sum')
type: AcceptedAnswer
type: Answer
score: 3

http://stackoverflow.com/q/48151185
downvote count: 4
answer count: 3
has comment: http://stackoverflow.com/comment/83281178
has body: I have an function that takes an array as an input. How can I modify it to work with variable arguments as well as arrays. For example I want arrSum(1,2,3) == arrSum([1,2,3]) to return True i.e. both should return 6 I have already asked this same question for JavaScript but when I tried to implement the same technique in Python I am getting totally unexpected errors. This is what I have tried to do based on my current knowledge of python. def arrSum(*args): listOfArgs = [] listOfArgs.extend([*list(args)]) return sum(listOfArgs) It works perfectly for arrSum(1,2,3) but returns error for arrSum([1,2,3]) arrSum(1,2,3) returns 6 which is the expected output. But `arrSum([1,2,3]) returns the following error: Traceback (most recent call last): File "python", line 7, in &lt;module&gt; File "python", line 4, in arrSum TypeError: unsupported operand type(s) for +: 'int' and 'list' Doing a print(listOfArgs) before return sum(listOfArgs) prints [[1,2,3]]. REPL.it link of the function
has comment: http://stackoverflow.com/comment/83280793
has answer: http://stackoverflow.com/a/48151436
has answer: http://stackoverflow.com/a/48151467
has comment: http://stackoverflow.com/comment/83280786
favorite count: 0
linked to: http://stackoverflow.com/q/2158395
has comment: http://stackoverflow.com/comment/83281053
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83281070
has comment: http://stackoverflow.com/comment/83280726
has title: Function with multiple arguments in python
has comment: http://stackoverflow.com/comment/83280868
linked to: http://stackoverflow.com/q/47941953
type: Question
has answer: http://stackoverflow.com/a/48152077
upvote count: 0
score: -4
has comment: http://stackoverflow.com/comment/83280761

http://stackoverflow.com/comment/83306240
has text: I wouldn't recommend the `pydoc` solution, as its not really intended for this purpose. If you only need to support a few types, you could use a mapping from name to type, e.g. `{"int": int, "float": float}`. There are lots of types though that your current serialization can't handle, since not all types can load themselves from a string (you can't build a dict, for instance). You may want to use `pickle` if you need to support arbitrary types. Even if your data types are simple, a more standard serialization like JSON or YAML might be better than something you make up yourself.
comment on: http://stackoverflow.com/q/48162350
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/116605298
score: 11
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48133124
has text: You can also resolve it by adding a hint like `game_data: dict[str, Any]`

http://stackoverflow.com/a/48140185
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48139886
type: Answer
answers question: http://stackoverflow.com/q/48139886
has comment: http://stackoverflow.com/comment/83258187
has body: [23, 3, 3, 0 This is the start of a TLS frame, i.e. ContentType 23 (application data) followed by the TLS version (3.3 which means TLS 1.2). This means you read from the plain socket instead from the SSL socket. The reason for this is that you are calling listenToClient with the plain socket client but the functions actually expects the SSL socket sslsoc: def listen(self): ... client, address = self.sock.accept() sslsoc = self.context.wrap_socket(client, server_side=True) threading.Thread(target = self.listenToClient,args = (client,address)).start() ... def listenToClient(self, sslsoc, address):
upvote count: 1
score: 1

http://stackoverflow.com/comment/83408383
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48120675
type: AnswerComment
has text: Bazel doesn't put generated files into source folders for a few reasons. It would be annoying for source control because now you have to exclude the generated files. It might interfere with globbing, because the globs might start picking up the generated files. Those files might also start showing up in IDEs as sources. What issues are you running into?

http://stackoverflow.com/comment/82999575
comment on: http://stackoverflow.com/q/48015191
type: Comment
has text: No, I specifically need values outside of my value range
score: 0
type: QuestionComment

http://stackoverflow.com/a/48035673
type: AcceptedAnswer
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/48035634
downvote count: 0
has body: A naive recursive implementation of the fibonacci algorithm will get slow really fast. There's two ways you can resolve this: a) Switch to an iterative version def fib(x): if x==0 or x==1: return 1 a = b = 1 for _ in range(x-1): a, b = b, a+b return b This is less elegant than the recursive solution, but has linear time complexity. b) Use memoization: from functools import lru_cache @lru_cache() def fib(x): if x==0 or x==1: return 1 else: return fib(x-1) + fib (x-2) This is the recursive solution, but with a "memory". It has the added benefit of being even faster than the iterative version if you have to call the function many times. In old versions of Python (e.g. 2.7), lru_cache didn't exist yet, but you implement a cheap copy that's enough for our use: def lru_cache(): # second-order decorator to be a drop-in replacement def decorator(fn): cache = {} def wrapped(*args, **kwargs): if args in cache: return cache[args] val = fn(*args) cache[args] = val return val return wrapped return decorator
accepted answer of: http://stackoverflow.com/q/48035634
score: 4

http://stackoverflow.com/q/48131756
has answer: http://stackoverflow.com/a/48131831
answer count: 2
linked to: http://stackoverflow.com/q/23326716
tagged with: tuples
has comment: http://stackoverflow.com/comment/83240642
score: 0
has comment: http://stackoverflow.com/comment/128100829
possible better answer: http://stackoverflow.com/a/48131831
has comment: http://stackoverflow.com/comment/83240619
has comment: http://stackoverflow.com/comment/83240647
tagged with: python
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48131810
accepted answer: http://stackoverflow.com/a/48131810
has body: I'm trying to use a for loop to iterate through the first element of a list of tuples. for i in link_list: print 'http://www.newyorksocialdiary.com%s' % link_list[i][0] However, I get this error: TypeError Traceback (most recent call last) &lt;ipython-input-72-8c0e1be937a4&gt; in &lt;module&gt;() 1 for i in link_list: ----&gt; 2 print 'http://www.newyorksocialdiary.com%s' % link_list[i][0] TypeError: list indices must be integers, not tuple How can I iterate through the list of tuples and print only the first element, such as: 'http://www.newyorksocialdiary.com/party-pictures/2014/the-thanksgiving-day-parade-from-the-ground-up' 'http://www.newyorksocialdiary.com/party-pictures/2014/gala-guests' If it helps, this is what link_list looks like: [('/party-pictures/2014/the-thanksgiving-day-parade-from-the-ground-up', datetime.datetime(2014, 12, 1, 0, 0)), ('/party-pictures/2014/gala-guests', datetime.datetime(2014, 11, 24, 0, 0)), ('/party-pictures/2014/equal-justice', datetime.datetime(2014, 11, 20, 0, 0)), ('/party-pictures/2014/celebrating-the-treasures', datetime.datetime(2014, 11, 18, 0, 0)), ('/party-pictures/2014/associates-and-friends', datetime.datetime(2014, 11, 17, 0, 0))]
has title: Python - For loop 'TypeError: list indices must be integers, not tuple'
type: Question

http://stackoverflow.com/comment/83313282
has text: what do you mean "multiple columns" - many comboboxes next to each other? Yes, you can do it. Or one combobox with text formatted so it looks like two columns ? Yes, you can do it - you may have to use monospaced font. See example with Listox which uses monospaced font to display many columns - [listbox with many columns](https://github.com/furas/python-examples/blob/master/tkinter/listbox/listbox-populate-entry/main.py)
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48166780

http://stackoverflow.com/comment/83207058
comment on: http://stackoverflow.com/q/48115462
type: Comment
type: QuestionComment
has text: Hi! Running from console (Ubuntu server). Did try export DISPLAY=:0, same result
score: 0

http://stackoverflow.com/a/48159199
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 5
upvote count: 5
has body: OK I managed to do this using https://github.com/Anorov/cloudflare-scrape import cfscrape from bs4 import BeautifulSoup # log in scraper = cfscrape.CloudflareScraper() scraper.get('https://X.com/wp-login.php') tokens = cfscrape.get_tokens('https://X.com') browser = mechanicalsoup.StatefulBrowser(session=scraper, user_agent=tokens[1]) browser.select_form('#loginform') browser['log'] = 'X' browser['pwd'] = 'X' browser.submit_selected() browser.open('https://X.com/page/')
accepted answer of: http://stackoverflow.com/q/48155877
answers question: http://stackoverflow.com/q/48155877

http://stackoverflow.com/comment/83056591
comment on: http://stackoverflow.com/q/48035684
has text: @Udi Have added the source for models and admin
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48043091
accepted answer: http://stackoverflow.com/a/48043178
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48043178
type: Question
has title: speech recognition python stopped in listen
upvote count: 1
has comment: http://stackoverflow.com/comment/83059973
answer count: 1
has comment: http://stackoverflow.com/comment/83057340
tagged with: speech-recognition
favorite count: 0
tagged with: python
has body: I am running the following code in Python 2.7 with pyAudio installed. I use this tutorial. import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: print("Speak:") audio = r.listen(source) try: print("You said " + r.recognize_google(audio)) except sr.UnknownValueError: print("Could not understand audio") except sr.RequestError as e: print("Could not request results; {0}".format(e)) python stopped in row "audio = r.listen(source)"
downvote count: 0

fractions
type: Tag
tag name: fractions
tags question: http://stackoverflow.com/q/48094595

http://stackoverflow.com/a/48080580
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48080359
downvote count: 0
score: 1
has body: You can use pandas, I suppose data is a list of list: import pandas as pd df = pd.DataFrame(data) df.loc[df.groupby([0])[1].idxmax()] 0 1 2 3 men 12 1946-Truman.txt 5 people 49 1946-Truman.txt 4 women 7 1946-Truman.txt For a result in the same format: df.loc[df.groupby([0])[1].idxmax()].values.tolist() [['men', 12, '1946-Truman.txt'], ['people', 49, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']]

http://stackoverflow.com/comment/83140016
comment on: http://stackoverflow.com/q/48082725
score: 0
has text: So , how do I get to iterate that list?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48080264
upvote count: 1
tagged with: function
answer count: 1
accepted answer: http://stackoverflow.com/a/48080278
has title: Skip specifying function arguments
tagged with: arguments
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48080278
tagged with: parameter-passing
type: AnsweredQuestion
has body: I have the following function in Python (see it on Trinket): def foo(a=1, b=2): print(a); print(b) foo(,4) When I run foo(,4), I want it to use the default when the first argument is not provided, and use the provided value if it's available. I.e. it should print: 1 4 Is this possible in Python? And, if so, how can I do this?
score: -1
type: Question
downvote count: 2

http://stackoverflow.com/a/48066498
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48050953
answers question: http://stackoverflow.com/q/48050953
has body: I would still like to attempt this with machine learning but I have created a Python solution that I will implement using FuzzyWuzzy. I will be generating a dynamic reference list based on a loop through the DB. So, for loop 1, I will create a unique ID for that Text. This will be stored in a table. In loop 2, I will look at the records in the new table and attempt to match it, if there is a match, that same ID will be assigned to the next record. If nothing is found that text will be added to the new table with a new unique ID. . . and so on. This method avoids machine learning and it will probably be good enough for the current set of requirements. Edit: I am adding an additional table so the tables will look as follows Table 1 = Unprocessed Source Data Table 2 = Unique Names Table 3 = All derivations of Unique Names I am also getting a unique list to start of the most common names and adding it to Table 2 and 3. This will simply be a starting off point.
type: AcceptedAnswer

http://stackoverflow.com/a/48024832
has comment: http://stackoverflow.com/comment/83021345
answers question: http://stackoverflow.com/q/48024154
upvote count: 1
has comment: http://stackoverflow.com/comment/83021816
has body: Here is a re approach: x = 'abcde' [re.sub(f'(.)(.)(?=.{{{i}}}$)', "\\2\\1", x) for i in reversed(range(len(x)-1))] # ['bacde', 'acbde', 'abdce', 'abced'] And a variant that skips double characters: x = 'abbde' [s for s, i in (re.subn(f'(.)(?!\\1)(.)(?=.{{{i}}}$)', "\\2\\1", x) for i in reversed(range(len(x)-1))) if i] # ['babde', 'abdbe', 'abbed']
score: 1
has comment: http://stackoverflow.com/comment/83021152
downvote count: 0
has comment: http://stackoverflow.com/comment/83020975
type: Answer
has comment: http://stackoverflow.com/comment/83021796

http://stackoverflow.com/comment/83117694
comment on: http://stackoverflow.com/q/48071972
score: 0
type: Comment
type: QuestionComment
has text: Have you tried using `<a href="{% url 'accounts:edit-user-profile' pk=form.instance.pk %}` (or just `<a href="{% url 'accounts:edit-user-profile' form.instance.pk %}`)?

http://stackoverflow.com/comment/83405051
comment on: http://stackoverflow.com/q/48170490
score: 0
type: Comment
type: QuestionComment
has text: Yes. I want to get link and title separately.

http://stackoverflow.com/comment/83101194
has text: What is `file`? Please post a complete example.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48064058
score: 0

http://stackoverflow.com/comment/83255386
comment on: http://stackoverflow.com/a/48136273
score: 0
type: Comment
has text: If series is `s` then change only `df['A']` to `s`
type: AnswerComment

http://stackoverflow.com/a/48114190
has body: I eventually used: weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True) It worked just fine, except that I got the following message. C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning: convert_objects is deprecated. Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/83253931
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/92274275
answers question: http://stackoverflow.com/q/48094854
has comment: http://stackoverflow.com/comment/83204104

convolution
tags question: http://stackoverflow.com/q/48084007
tag name: convolution
tags question: http://stackoverflow.com/q/48097941
tags question: http://stackoverflow.com/q/48067824
type: Tag

http://stackoverflow.com/comment/83247537
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48135100
score: 0
has text: We need more information to help you here. First, make sure you always post the stacktrace. Second, I'd like to see what all the columns of `df` are. Show the output of `print(df.columns)`.

http://stackoverflow.com/q/48171894
favorite count: 0
accepted answer: http://stackoverflow.com/a/48173224
has title: Mix two csv data in one
has comment: http://stackoverflow.com/comment/83323639
tagged with: python
upvote count: 1
has comment: http://stackoverflow.com/comment/83323564
has comment: http://stackoverflow.com/comment/83323787
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48173224
score: 1
has body: I need to mix 2 csv in 1. I converted both in lists because I think is the best way to do it! Also, remember that the Client and Date are in different columns and maybe the order of data are not the same in both files! list1 csv: Cliente Fecha Status interlatin 01/01/2018 Alerta Revenue: aumento Subastadas - descenso eCPM y Fillrate interlatin 31/12/2017 Alerta Fillrate -- Incremento Revenue - Imp Vendidas - Subastadas: Precaucion Fillrate buena Mejora mmmm 01/01/2018 Alerta Revenue: aumento Subastadas - descenso eCPM y Fillrate mmmm 31/12/2017 Alerta Fillrate -- Incremento Revenue - Imp Vendidas - Subastadas: Precaucion Fillrate buena Mejora KKKKK 01/01/2018 Alerta Revenue: aumento Subastadas - descenso eCPM y Fillrate KKKKK 31/12/2017 Alerta Fillrate -- Incremento Revenue - Imp Vendidas - Subastadas: Precaucion Fillrate buena Mejora list2 csv: Fecha Cliente Subastas Impresiones_exchange Fill_rate Importe_a_pagar_a_medio ECPM_medio 31/12/2017 interlatin 2141801 303970 14.19 339.12 1.12 01/01/2018 interlatin 308759 70938 22.98 41.9 0.59 31/12/2017 mmmm 2141801 303970 14.19 339.12 1.12 01/01/2018 mmmm 308759 70938 22.98 41.9 0.59 31/12/2017 KKKKK 2141801 303970 14.19 339.12 1.12 01/01/2018 KKKKK 308759 70938 22.98 41.9 0.59 What I´m looking for: Cliente Fecha Subastas Impresiones_exchange Fill_rate Importe_a_pagar_a_medio ECPM_medio Status interlati 01/01/2018 2141801 303970 14.19 339.12 1.12 Alerta Revenue: aumento Subastadas - descenso eCPM y Fillrate interlati 31/12/2017 308759 70938 22.98 41.9 0.59 Alerta Fillrate -- Incremento Revenue - Imp Vendidas - Subastadas: Precaucion Fillrate buena Mejora mmmm 01/01/2018 2141801 303970 14.19 339.12 1.12 Alerta Revenue: aumento Subastadas - descenso eCPM y Fillrate mmmm 31/12/2017 308759 70938 22.98 41.9 0.59 Alerta Fillrate -- Incremento Revenue - Imp Vendidas - Subastadas: Precaucion Fillrate buena Mejora KKKKK 01/01/2018 2141801 303970 14.19 339.12 1.12 Alerta Revenue: aumento Subastadas - descenso eCPM y Fillrate KKKKK…
has comment: http://stackoverflow.com/comment/83324574
tagged with: python-2.7
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/83319912
comment on: http://stackoverflow.com/a/48168337
score: 0
type: Comment
type: AnswerComment
has text: Even that has changed a simple `conda install` or `pip install` into a: `conda create --clone env --name env-2` `source activate env-2` `conda install package` `<test to make sure it works>` `source activate env` `conda install package` `conda env remove --name env-2` I know this is a little out of scope of the question, but wouldn't it be nicer if `conda` offically supported installing pip packages in a way that `conda` could manage them & make them play nice?

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/48110492
tags question: http://stackoverflow.com/q/48039787
tags question: http://stackoverflow.com/q/48146748
tags question: http://stackoverflow.com/q/48112466

http://stackoverflow.com/comment/83096989
type: Comment
has text: Yes, thanks for this. However I get the following error now: `mask_face = np.zeros(RGB_img.shape[:2] + [3], np.uint8) TypeError: can only concatenate tuple (not "list") to tuple`. Why is this?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48061850

http://stackoverflow.com/comment/83084760
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48056265
has text: No images, only text

http://stackoverflow.com/a/48070888
upvote count: 1
score: 1
downvote count: 0
has body: The successive commas are being included in a single match. You want a regex which doesn't include them in the replacement itself but ensures that they're there re.sub(r'(?&lt;=[,"])(,)(?=[,"])', '|', s) This uses lookahead and lookbehinds to check that the , or " is present without replacing them. (,) Match a comma (?&lt;=[,"]) Immediately preceded by either a comma or double quote (?=[,"]) Immediately followed by either a comma or double quote The (? in the first and third groups ensure that these groups are not included in the replacement
answers question: http://stackoverflow.com/q/48070802
type: Answer

http://stackoverflow.com/comment/83220385
score: 0
has text: @roganjosh any suggestion
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48121763

http://stackoverflow.com/comment/83235661
type: Comment
type: QuestionComment
has text: @MichealO'Dwyer thanks, i was thinking the same, but i haven't figured out why yet...
comment on: http://stackoverflow.com/q/48127128
score: 0

http://stackoverflow.com/q/48024559
has comment: http://stackoverflow.com/comment/83018642
upvote count: 2
has comment: http://stackoverflow.com/comment/83019312
tagged with: resampling
has comment: http://stackoverflow.com/comment/83018393
has title: pandas: resample No numeric types to aggregate
type: UnansweredQuestion
has body: I am trying to smoothen some data using pandas but I get stuck at an error telling me there are no numeric types to aggregate. I found various solutions on the internet, but I couldn't get past that error. I am using data available at: http://archive.luftdaten.info/2017-12-01/2017-12-01_sds011_sensor_3687.csv I import the csv with: sensor = pd.read_csv("all.csv", sep=";") I parse the timestamp column with sensor["timestamp"] = pd.to_datetime(sensor["timestamp"], infer_datetime_format=True, errors="coerce") and set the timestamp as index sensor = sensor.set_index("timestamp") To keep it simple I extract a single column p_1 = sensor["P1"] I would now like to resample the data for one hour using: p_1.resample("1H").mean() But this returns an error: pandas.core.base.DataError: No numeric types to aggregate From what I gathered searching for the error, I have to somehow convert the columns into numeric values but I couldn't find any function that would leave me with a table which would work. Edit: I found this, but I really don't know how to apply this to my situation: https://stackoverflow.com/a/30660772/9153439 Edit2 (solved): I was able to resample the data by changing the datatype in sensor with sensor["P1"] = sensor["P1"].apply(pd.to_numeric, errors='coerce') I am quite sure that I tried this before on the p_1 subset but couldn't get it to work.
score: 2
answer count: 0
downvote count: 0
favorite count: 0
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/83018988
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
linked to: http://stackoverflow.com/q/12844529

http://stackoverflow.com/a/48094064
upvote count: 1
has body: There are two things you need to change: The first .*? lazy pattern must be turned to greedy .* (in this case, the subpatterns after .* will match the last occurrence in the string) The group you need to use is Group 2, not Group 1 (as it is the group that stores the year data). Or make the first capturing group non-capturing. See this demo: rg = re.compile('.*([\[\(]?((?:19[0-9]|20[01])[0-9])[\]\)]?)', re.IGNORECASE|re.DOTALL) ... releaseYear = match.group(2) Or: rg = re.compile('.*(?:[\[\(]?((?:19[0-9]|20[01])[0-9])[\]\)]?)', re.IGNORECASE|re.DOTALL) ... releaseYear = match.group(1)
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48093977
type: Answer
answers question: http://stackoverflow.com/q/48093977

http://stackoverflow.com/a/48033787
type: Answer
downvote count: 0
score: 2
has body: Scipy's mode does exactly that: from scipy.stats import mode m, c = mode([1, 1, 2, 2, 4, 5]) Then m is the lowest mode (1) and c is its frequency (2).
upvote count: 2
answers question: http://stackoverflow.com/q/48031699

http://stackoverflow.com/a/48089100
has comment: http://stackoverflow.com/comment/83152773
has comment: http://stackoverflow.com/comment/83175545
score: 3
has comment: http://stackoverflow.com/comment/83152860
has body: While you asked for use of the library mystic, you probably don't need such fine-grained control when starting out with nonlinear optimization. The module scipy ought to suffice. What follows is a more-or-less complete solution, correcting what I perceive to be a typo in the original whitepaper regarding the pricing bounds: import numpy as np from scipy.optimize import minimize P_nom = 89 P_max = None price_elasticity = 2 number_of_days = 7 demand = lambda a, L: 1./L total_rooms = [5]*number_of_days def objective(P, *args): return -np.dot(P, O(P, *args)) def worst_leftover(P, C, *args): return min(np.subtract(C, O(P, *args))) def X(P, a, L, d, e, P_nom): return d(a, L)*(sum(P[a:a+L])/P_nom/L)**e def d(a, L): return 1. def O_l(P, l, l_max, *args): return sum([X(P, a, L, *args) for a in xrange(0, l) for L in xrange(l-a+1, l_max+1)]) def O(P, *args): return [O_l(P, l, *args) for l in xrange(len(P))] result = minimize( objective, [P_nom]*number_of_days, args=(number_of_days-1, demand, price_elasticity, P_nom), method='SLSQP', bounds=[(0, P_max)]*number_of_days, constraints={ 'type': 'ineq', 'fun': worst_leftover, 'args': (total_rooms, number_of_days-1, demand, price_elasticity, P_nom) }, tol=1e-1, options={'maxiter': 10**3} ) print result.x A couple of points worth mentioning: The objective function has an added minus sign for use with scipy's minimize() routine, contrasting with the maximization referenced in the original whitepaper. This will cause result.fun to be negative rather than indicating total revenue. The formula seems to be a bit sensitive to the parameters. The minimization is correct (at least, it's correct when it says it executed correctly -- check result.success), but if the inputs are too far off from reality then you're likely to find prices much higher than anticipated. You also probably want to use more days than I did in the following sample. There seems to be something like a periodic effect your whitepaper induces. I'm not really a fan of the wh…
downvote count: 0
answers question: http://stackoverflow.com/q/48088516
has comment: http://stackoverflow.com/comment/83218293
has comment: http://stackoverflow.com/comment/83187625
has comment: http://stackoverflow.com/comment/83153553
type: Answer
upvote count: 3

http://stackoverflow.com/q/48016569
has body: I have a raster that is being stored in a numpy array that holds an aerial photo of an area that may be any shape. There is a good amount of noise in the data within the area that needs to be smoothed out. The edge of the image (where no data is) is marked by 0s that extend to the edge of the raster. I have tried using the gaussian filter in scipy.ndimage.filters, but that reduces the values of the pixels at the edge of the data set. I can't find a flag to set nodata value. Is there a better way to do this in Python?
type: Question
downvote count: 0
tagged with: raster
favorite count: 0
tagged with: python
has title: SciPy: Interpolation/Smoothing without edge bleeding
tagged with: interpolation
answer count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: scipy

http://stackoverflow.com/q/48159515
duplicate of: http://stackoverflow.com/q/1680528
has comment: http://stackoverflow.com/comment/83298561
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/83298806
tagged with: construction
has comment: http://stackoverflow.com/comment/83298566
has title: A list in a class seems to be static?
tagged with: static
has comment: http://stackoverflow.com/comment/83298546
type: UnansweredQuestion
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/83298564
answer count: 0
has body: In a Python class I wrote the following method: class user(): address_list = [] def __init__(self): self.address_list.append("a") When I use it as this: ur1 = user() ur1.address_list.append("b") ur2 = user() ur2.address_list.append("c") ur2.address_list.append("d") print("user1's address: ", len(ur1.address_list)) print("user2's address: ", len(ur2.address_list)) The output was: user1's address: 5 user2's address: 5 But my expectation was: user1's address: 2 #a, b user2's address: 3 #a,c,d What's wrong with my code?
linked to: http://stackoverflow.com/q/1680528
type: Question

http://stackoverflow.com/q/48153720
has comment: http://stackoverflow.com/comment/83286895
has comment: http://stackoverflow.com/comment/83286748
has comment: http://stackoverflow.com/comment/83286672
tagged with: memory
downvote count: 0
has comment: http://stackoverflow.com/comment/83286439
has comment: http://stackoverflow.com/comment/83286826
has comment: http://stackoverflow.com/comment/89137881
has comment: http://stackoverflow.com/comment/83286545
has comment: http://stackoverflow.com/comment/83288276
favorite count: 0
linked to: http://stackoverflow.com/q/17513036
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83287442
tagged with: pickle
has body: Here is my approximate workflow import multiprocessing as mp import pickle import numpy as np import psutil test = [np.random.choice(range(1, 1000), 1000000) for el in range(1,1000)] step_size = 10**4 for i in range(0,len(test), step_size): p = mp.Pool(10) temp_list = test[i:i+step_size] results = p.map(some_function, temp_list) gc.collect() mem = psutil.virtual_memory() print('Memory available in GB' + str(mem.available/(1024**3))) with open('file_to_store'+ str(int(i/(step_size))+'.pickle', 'wb') as f: pickle.dump(results, f) p.close() It generates the following output Memory available in GB36.038265228271484 Memory available in GB23.011260986328125 Memory available in GB9.837642669677734 and then error: --------------------------------------------------------------------------- MemoryError Traceback (most recent call last) &lt;ipython-input-9-d17700b466c3&gt; in &lt;module&gt;() 260 261 with open(file_path_1+str(int(i/step_size))+'.pickle', 'wb') as f: --&gt; 262 pickle.dump(vec_1, f) 263 with open(file_path_2+str(int(i/step_size))+'.pickle', 'wb') as f: 264 pickle.dump(vec_2, f) MemoryError: some_function does some minor processing and does not create any global variable that can hang in memory. I do not understand why amount of available memory is reducing and why it runs out of memory?
tagged with: python
tagged with: pathos
has comment: http://stackoverflow.com/comment/83286434
score: 2
has comment: http://stackoverflow.com/comment/83287457
answer count: 0
has comment: http://stackoverflow.com/comment/83287519
upvote count: 2
has title: Running out of RAM python - where does it go
has comment: http://stackoverflow.com/comment/83290311
has comment: http://stackoverflow.com/comment/83289144
tagged with: multiprocessing
type: Question

http://stackoverflow.com/a/48118764
answers question: http://stackoverflow.com/q/48118664
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/83214593
has body: I think you are trying to assign variable names using strings. Try getting rid of the for-loop and putting it in a list comprehension. idx = pd.IndexSlice vars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] a, b, c, d, e, f, g, h = [df.loc[:,idx[:,[v, 'Column 1']]] for v in vars] Why it works: What you were doing for v in vars: # evaluates each v 1 at a time ... = df.loc[:,idx[:,[v, 'Column 1']]] # returns 1 item corresponding to current v since your df.loc[...] was evaluating each v 1 at a time there was nothing to "unpack" aka you can't unpack 8 variables from a variable such as x = 11 because it's only 1 item. Note that had each If your df.loc[... returned a collection of 8 items it would have broken out those 8 items into a...h overwriting them each time. What I did a, b, c, d, e, f, g, h = [df.loc[:,idx[:,[v, 'Column 1']]] for v in vars] # returns _collection_ of 8 items Using a list comprehension i'm just executing all your df.loc queries at once returning a collection of 8 results. Since there are now 8 items on the right hand side of the = assignment, the unpacking works correctly.
has comment: http://stackoverflow.com/comment/83214330
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48118664

http://stackoverflow.com/comment/83119815
type: Comment
comment on: http://stackoverflow.com/a/48073073
has text: Ohh raw string vs normal.. got it.. the JSON source is encoding as `\x3E` (invalid/broken) and not `\u003E` (valid JSON encoding).. I wonder if it might return `\xZZ` for other values of ZZ in the future.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83239458
type: QuestionComment
comment on: http://stackoverflow.com/q/48131172
score: 0
type: Comment
has text: I'm aware of the readability factor which is why I'm only using this for a single variable, and added parentheses to make it a little easier on the eyes. I saw the error after I posted the question, perhaps it's time for some more coffee. Thank you for the help.

http://stackoverflow.com/q/48038293
has body: I have two python scripts for my app to work. I want them to start at boot but only one (the gunicorn/mon) script starts. My Crontab: @reboot /home/daniel/mon/start.sh @reboot /home/daniel/bot1/start.sh Mon start.sh #!/bin/bash /usr/bin/screen -dmS bb-mon /bin/bash -c 'cd /home/daniel/mon &amp;&amp; /usr/local/bin/gunicorn app:app --bind 0.0.0.0:9999' works. Bot1 start.sh #!/bin/bash /usr/bin/screen -dmS bb-bot /bin/bash -c 'cd /home/daniel/bot1 &amp;&amp; /usr/bin/python3 app.py' Not working. I tested several outputs in my screen session which appears. The screen session will be started also but the python script does not start. If I add something like &gt; log.txt after the python call the file is empty. Starting the script without screen doesn't work too.
tagged with: python
answer count: 1
downvote count: 1
tagged with: raspberry-pi
upvote count: 0
type: UnansweredQuestion
favorite count: 0
tagged with: linux
tagged with: bash
type: Question
has title: Crontab doesn't run Python script on reboot
tagged with: shell
has answer: http://stackoverflow.com/a/48038415
score: -1

http://stackoverflow.com/a/48101707
has body: The following comprehensions will work: &gt;&gt;&gt; [[*x, y] for x, y in it.product(it.combinations(a, 2), b)] # Py3 &gt;&gt;&gt; [list(x) + [y] for x, y in it.product(it.combinations(a, 2), b)] # all Py versions [[1, 2, 5], [1, 2, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6], [3, 4, 5], [3, 4, 6]]
type: Answer
accepted answer of: http://stackoverflow.com/q/48101672
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83180393
has comment: http://stackoverflow.com/comment/83178857
has comment: http://stackoverflow.com/comment/83178810
score: 4
answers question: http://stackoverflow.com/q/48101672

http://stackoverflow.com/q/48070388
accepted answer: http://stackoverflow.com/a/48070675
has body: test = np.array([20, 21, 22, 23, 22, 21]) test = test.astype(float) result = np.zeros((1,1)) for i in range(len(test)-3): d = np.abs(test[i+3]-test[i]) #print(d) v = 0 for j in range(3): v = v + np.asscalar( np.abs(test[i+3-j] - test[i+3-(j+1)])) out = d / v result = np.hstack((result, out)) I want the result of this code to be shape of numpy array like this -> (3,1) The normal output should originally appear as follows: [1, 0.333, 0.333] However, when I run this code, I got an error like the title.
type: Question
tagged with: numpy
tagged with: arrays
answer count: 1
has title: ValueError: all the input arrays must have same number of dimensions, (numpy error)
tagged with: python
has answer: http://stackoverflow.com/a/48070675
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83114993
score: 0

http://stackoverflow.com/a/48085910
has body: Try something like this: (prob need to make some modifications but it will be close to what you want this example is for login form): install lxml import requests from lxml import html payload = { "username": "&lt;USER NAME&gt;", "password": "&lt;PASSWORD&gt;", "csrfmiddlewaretoken": "&lt;CSRF_TOKEN&gt;" } sessionReq = requests.session() login_url = "https://example.be/account/login.php" result = sessionReq.get(login_url) tree = html.fromstring(result.text) authenticity_token = list(set(tree.xpath("//input[@name='csrfmiddlewaretoken']/@value")))[0] result = sessionReq.post(login_url,data = payload, headers = dict(referer = login_url) url = 'https://bitbucket.org/dashboard/overview' I hope this helps you :)
answers question: http://stackoverflow.com/q/48085692
downvote count: 1
score: -1
upvote count: 0
type: Answer

http://stackoverflow.com/comment/83153097
type: QuestionComment
comment on: http://stackoverflow.com/q/48089313
has text: Because everything in python is an object, including functions. **BUT** keep in mind that the fact you can do something, doesn't mean you *should* do it... Allow me to make a bit of [Spam](https://stackoverflow.com/a/48031685/289011) of my own answer... **:-D**
score: 0
type: Comment

http://stackoverflow.com/a/48106654
answers question: http://stackoverflow.com/q/48106347
has comment: http://stackoverflow.com/comment/83213700
has body: Does it say somewhere in the docs that the test should work without subclassing django.test.TestCase? I don't think that django-pytest does anything special in regards to loading django apps. So, if your class continues to inherit from TestCase, you should be able to use everything else from pytest, such as it's assertions, fixtures, etc.
score: 0
upvote count: 1
downvote count: 1
type: Answer

http://stackoverflow.com/comment/83106208
has text: Yes sorry my comment was wrong. Everything goes perfectly. I have just 1 additional issue: the `output.csv` I obtain in this way is a "read-only" file, therefore I can't modify it. Also, could be cool to have `test1` , `test2`, etc instead of `test1.csv`, `test2.csv`, and so on.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48065926

http://stackoverflow.com/q/48053305
answer count: 8
has answer: http://stackoverflow.com/a/48062086
has answer: http://stackoverflow.com/a/48053377
tagged with: list-comprehension
linked to: http://stackoverflow.com/q/6076270
has body: I am processing a text file whose columns are separated by tabs .I want to get all the unique values of the first column. Text Input e.g: "a\t\xxx\t..\zzz\n a\t\xxx\t....\n b\t\xxx\t.....\n b\t\xxx\t.....\n c\t\xxx\t.....\n" So in this case i would like to get an array: uniques=["a","b","c"] Code: def getData(fin): input = open(fin, 'r',encoding='utf-16') headers=input.readline().split() lines=input.readlines()[1:] uniques=[(lambda line: itertools.takewhile(lambda char: char!='\t',line))for line in lines] Instead of the desired values i get a list of : &lt;function getData.&lt;locals&gt;.&lt;listcomp&gt;.&lt;lambda&gt; at 0x000000000C46DB70&gt; I have already read this article Python: Lambda function in List Comprehensions and I unserstood that you have to use parenthesis to ensure the right execution order.Still i get the same result.
upvote count: 1
accepted answer: http://stackoverflow.com/a/48053448
has answer: http://stackoverflow.com/a/48053364
has title: How to get the unique elements of the first column of a text file?
has answer: http://stackoverflow.com/a/48053388
favorite count: 0
has answer: http://stackoverflow.com/a/48053448
has comment: http://stackoverflow.com/comment/83079114
tagged with: python
possible better answer: http://stackoverflow.com/a/48053377
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48053401
score: 1
has answer: http://stackoverflow.com/a/48053348
has answer: http://stackoverflow.com/a/48055054
type: Question

http://stackoverflow.com/comment/83183795
has text: its my overcombinated param, that should be empty
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48104052
type: Comment

http://stackoverflow.com/q/48139782
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/83257750
has comment: http://stackoverflow.com/comment/83257189
type: Question
linked to: http://stackoverflow.com/q/21053380
linked to: http://stackoverflow.com/q/1316767
has title: Does a del statement open up memory?
downvote count: 0
has answer: http://stackoverflow.com/a/48139858
duplicate of: http://stackoverflow.com/q/21053380
answer count: 1
has body: I wrote a python script that backs up my files while I'm sleeping at night. The program is designed to run whenever the computer is on and to automatically shut down the computer after the backups are done. My code looks like this: from datetime import datetime from os import system from backup import backup while True: today = datetime.now() # Perform backups on Monday at 3:00am. if today.weekday() == 0 and today.hour == 3: print('Starting backups...') # Perform backups. backup("C:\\Users\\Jeff Moorhead\\Desktop", "E:\\") backup("C:\\Users\\Jeff Moorhead\\Desktop", "F:\\") backup("C:\\Users\\Jeff Moorhead\\OneDrive\\Documents", "E:\\") backup("C:\\Users\\Jeff Moorhead\\OneDrive\\Documents", "F:\\") # Shutdown computer after backups finish. system('shutdown /s /t 10') break else: del today continue The backup function is from another file that I wrote to perform more customized backups on a case by by case basis. This code all works perfectly fine, but I'm wondering if the del statement del today is really necessary. I put it in thinking that it would prevent my memory from getting filled up by thousands of datetime objects, but then I read that Python uses garbage collection, similar to Java. Further, does the todayvariable automatically get replaced with each pass through the while loop? I know that the program works as intended with the del statement, but if it is unnecessary, then I would like to get rid of it if only for the sake of brevity! What are it's actual effects on memory?
favorite count: 0
has comment: http://stackoverflow.com/comment/83257405
has comment: http://stackoverflow.com/comment/83257252
accepted answer: http://stackoverflow.com/a/48139858
tagged with: del

http://stackoverflow.com/comment/83004010
score: 2
comment on: http://stackoverflow.com/q/48017236
type: Comment
has text: Not sure why you need `np.where` here for a simple 0/1. Use `.astype(int)` instead.
type: QuestionComment

http://stackoverflow.com/q/48019434
has answer: http://stackoverflow.com/a/48022885
accepted answer: http://stackoverflow.com/a/48022885
has body: I have this weird behaviour in a pandas Dataframe. I am using .apply(single_seats_comma) on a column with the following example content: (1,2). However, it seems to return it as range(1,3) instead of a string (1,2). Other rows have more than 2 entries as well, e.g. (30,31,32). I have a function which splits on , and converts each value in brackets into a new row however with (x,x) it breaks. def single_seats_comma(row): strlist = str(row).split(',') strlist = filter(None, strlist) intlist = [] for el in strlist: intlist.append(int(el)) return intlist Example for 'apply': tickets['seats'][:1].apply(single_seats_comma) The Error output of the def is ValueError: invalid literal for int() with base 10: 'range(1' Trying to find a solution, I found this: str(tickets['seats'][:1]) &gt;&gt;'0 (1, 2)\nName: seats, dtype: object' tickets['seats'][:1].values &gt;&gt; '[range(1, 3)]' It works on a column if the values are just 1,2. Any help help is much appreciated!
score: 2
tagged with: range
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48019616
tagged with: apply
type: Question
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48019652
tagged with: string
favorite count: 0
has title: Force pandas to interpret (1,2) in column as string and not as range?
has answer: http://stackoverflow.com/a/48019616
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/83278855
comment on: http://stackoverflow.com/q/48150271
score: 0
has text: How are you running `a.py`?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/135012268
has text: Additional clarification: the configuration in `launch.json` is also used to run without debugging. To me, the documentation is a bit misleading as it refers to debugging only. Hence, if you only want to run your code without debugging, you also need to set the configuration in `launch.json`.
score: 1
comment on: http://stackoverflow.com/a/48195425
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48017592
has body: i have script to select the button like below driver.find_element_by_id("Product").click() driver.find_element_by_id("id1").click() driver.find_element_by_id("id1").click() driver.find_element_by_id("id2").click() driver.find_element_by_id("id2").click() driver.find_element_by_id("id3").click() driver.find_element_by_id("id3").click() driver.find_element_by_id("id4").click() driver.find_element_by_id("id4").click() driver.find_element_by_id("id5").click() driver.find_element_by_id("id5").click() driver.find_element_by_id("id6").click() driver.find_element_by_id("id6").click() driver.find_element_by_id("id7").click() driver.find_element_by_id("id7").click() so here i am selection the button product and then it has multiple items. each code will select the product and deselect it How can loop this id selections instead writing long script like once product button selected then a loop to select all the items in the product
favorite count: 0
has title: loop the id in selenium python
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48018382
tagged with: selenium
tagged with: loops
has comment: http://stackoverflow.com/comment/83004277
downvote count: 1
type: Question
upvote count: 0
score: -1
has answer: http://stackoverflow.com/a/48017612
answer count: 2
tagged with: getelementbyid

http://stackoverflow.com/comment/83039057
has text: How are you running that script? What does `sys.stdout.encoding` tell you?
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48034534

http://stackoverflow.com/comment/83019701
has text: This is the only answer that explains what's actually wrong with OP's technique.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48025138
type: AnswerComment

pythonnet
type: Tag
tag name: pythonnet
tags question: http://stackoverflow.com/q/48156741
tags question: http://stackoverflow.com/q/48082043

http://stackoverflow.com/comment/83276687
type: QuestionComment
comment on: http://stackoverflow.com/q/48142526
score: 0
has text: When I try this I get the following errors, I pre-loaded the images to avoid a lagging game. Bulleti = pygame.image.load('bullet.png').convert() pygame.error: cannot convert without pygame.display initialized And when i try the .conver_alpha I get this: line 47, in __init__ self.rect = self.image.get_rect() AttributeError: 'builtin_function_or_method' object has no attribute 'get_rec and line 88, in <module> mob = Mob(Monster)
type: Comment

http://stackoverflow.com/a/58076673
answers question: http://stackoverflow.com/q/48024654
downvote count: 0
type: Answer
upvote count: 3
has body: You have to install kivy manually on pycharm, follow these six steps: Click on Files on top left corner. Click on settings. Click on Project and click on project interpreter. Click on (➕) icon on right. Click on "Search" and type "Kivy" you will find a lot of packages, then choose Kivy and install it. Enjoy!
score: 3

http://stackoverflow.com/comment/83050728
comment on: http://stackoverflow.com/a/48040061
type: AnswerComment
has text: @ubadub I intend to use k as a string of music chord. Hence it might be random.
score: 0
type: Comment

http://stackoverflow.com/q/48049300
tagged with: flask
upvote count: 3
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/48049401
favorite count: 0
has title: Page Redirect after X seconds wait using Flask-python/jinja
tagged with: python
has answer: http://stackoverflow.com/a/48049401
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3715047
has body: I want to redirect to another page after staying in a page for x seconds. is it possible to do using python or jinja in flask.A code sinppet can be Helpful
duplicate of: http://stackoverflow.com/q/8711888
tagged with: jinja2
type: Question
duplicate of: http://stackoverflow.com/q/3715047

http://stackoverflow.com/q/48070250
tagged with: javascript
tagged with: jquery
favorite count: 0
has title: JQuery not working with classes generated with Jinja
tagged with: http://stackoverflow.com/tag/html
has body: When referring to classes that have been generated with Jinja, JQuery no longer recognises them and works. This is the code I have. {% for name,quantity in movies %} {{name}} [X] {% endfor %} Alternatively, works, but is not what I am after. Cheers.
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83114480
tagged with: python
tagged with: jinja2
downvote count: 1
has comment: http://stackoverflow.com/comment/83115419
score: 1
has comment: http://stackoverflow.com/comment/83114424
type: Question
has comment: http://stackoverflow.com/comment/83114569

http://stackoverflow.com/q/48064800
has comment: http://stackoverflow.com/comment/87802237
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
has title: Reading HDF5 inputs in TensorFlow
score: 1
has comment: http://stackoverflow.com/comment/83102885
tagged with: tensorflow
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/83102864
has comment: http://stackoverflow.com/comment/87750047
favorite count: 0
tagged with: h5py
has body: I'm training a neural network in TensorFlow that currently takes in PNGs as inputs. While this works fine, I'd like to move to using HDF5 format inputs for more flexibility, but I'm having issues adapting the code. In both cases, a text file contains a list of the paths to all the PNG/H5 files that are to be used as training examples, one example per line. My simplified version of the current code for PNGs that works is as follows: class ImageReader(object): def __init__(self, image_list, coord): ''' image_list: string array of training image paths. coord: TensorFlow queue coordinator. ''' self.image_list = image_list self.coord = coord self.images = tf.convert_to_tensor(self.image_list, dtype=tf.string) self.queue = tf.train.slice_input_producer([self.images]) self.image = read_images_from_disk(self.queue) def dequeue(self, batch_size): image_batch = tf.train.batch([self.image], batch_size) return image_batch def read_images_from_disk(input_queue): img_contents = tf.read_file(input_queue[0]) img = tf.image.decode_png(img_contents, channels=1, dtype=tf.uint16) return img What I would like to be able to do is to replace the read_images_from_disk method to handle HDF5 files, specifically something along these lines: def read_images_from_disk(input_queue): h5_contents=h5py.File(input_queue[0],'r') img=h5_contents['image'] return img Obviously, this doesn't work as h5py wants a string as an input and not a Tensor, and I get the error: AttributeError: 'Tensor' object has no attribute 'encode' What do I need to modify to get this working?

http://stackoverflow.com/q/48130961
has body: I am trying to solve a first order differential equation using Euler's method, and then compare it with the actual solution by plotting them together using a range of 0 to 4 and 0.5 intervals. Below is the code. It shows a syntax error at line 19(array = []). Can someone please explain why is it so? import matplotlib.pyplot as plt def derivative(x): return (-2 * (x ** 3) + 12 * (x **2) - 20 * x + 8.5) def value_new(value, derivative): return value + derivative * 0.5 def real_value(x): return (-0.5 * (x ** 4) + 4 * (x ** 3) - 10 * (x ** 2) + 8.5 * x + 1) x = [0.5 * i for i in range(9)] value = [1] for i in x: y.append(value_new(y[-1], derivative(i)) actual = [] # this line shows invalid syntax for i in x: actual.append(real_value(i)) plt.plot(x, value, x, actual, 'ro') plt.show()
has answer: http://stackoverflow.com/a/48131147
has comment: http://stackoverflow.com/comment/83239191
upvote count: 0
answer count: 1
has title: syntax error while assigning list
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: -2
tagged with: syntax
downvote count: 2
has comment: http://stackoverflow.com/comment/83239198
type: Question

http://stackoverflow.com/comment/83241922
comment on: http://stackoverflow.com/q/48131616
score: 0
type: Comment
has text: looks like your correct my issue seems to be related me missing zlib packages. looks like I needed the following yum install zlib.i686. I do hit another error but seems related to openssl which ill look to resolve elsewhere.
type: QuestionComment

http://stackoverflow.com/q/48017220
has answer: http://stackoverflow.com/a/60491275
favorite count: 0
has title: How to use iperf to test the throughput of one client and multiple servers?
has answer: http://stackoverflow.com/a/48070716
type: UnansweredQuestion
tagged with: python
tagged with: iperf
type: Question
tagged with: network-programming
tagged with: mininet
score: -1
tagged with: pox
has body: As title, I want to test the throughput of a network containing 2 servers(h1,h3) ,only 1 client(h2) and some switches between the hosts and destination , the topology may look like this , I have implemented the topology using mininet, and controlled the routing rule using pox controller. Now I want to test the throughput of the network and I hope h3 and h1 sent data to h2 at the same time, how can I do that using iperf ? I haved tried the code below(python code) , but the data in first 10 seconds when h3->h2 will disappear(if I wrote h3->h2 before h1->h2 , than the data in first 10 seconds of h1->h2 will disappear) h1.cmd('iperf -s -p 5201 -u -i 1 &gt; results &amp;') print h2.cmd('iperf -c 10.0.0.1 -p 5201 -u -b 10m -t 20') h3.cmd('iperf -s -p 5205 -u -i 1 &gt; results2 &amp;') print h2.cmd('iperf -c 10.0.0.3 -p 5205 -u -b 10m -t 20') h1.cmd('kill %iperf') h3.cmd('kill %iperf') How can I fixed this problem or someone can tell me how to let h3 and h1 sent data to h2 at the same time using other methods, thanks.
answer count: 2
downvote count: 2
upvote count: 1

http://stackoverflow.com/comment/83215840
comment on: http://stackoverflow.com/q/48119592
score: 0
type: Comment
type: QuestionComment
has text: If there are no duplicates keep the row.

http://stackoverflow.com/comment/83041706
type: QuestionComment
has text: tried that (now).. but that doesn't really indent for me.. may be i do it wrong? ```'{HHCAA:{00:GGEDB:{00:FFFFF,01:``` (still prints in same style)
comment on: http://stackoverflow.com/q/48035862
score: 0
type: Comment

http://stackoverflow.com/q/48078836
favorite count: 0
type: Question
tagged with: flask-ask
tagged with: python
has title: Detecting supported interfaces in Flask-Ask Alexa Echo Show
upvote count: 1
answer count: 1
has body: I am trying to build a voice skill for both Echo Show [Screen Enabled] and Echo Dot [Audio only]. Apparently the response directives have to be changed depending on the device if not, it would result in "Alexa having trouble accessing the skill". How do we determine the supported interfaces in Flask-ASK ? ... "context": { "System": { "application": { "applicationId": "&lt;value&gt;" }, "user": { "userId": "amzn1.ask.account.&lt;value&gt;" }, "device": { "supportedInterfaces": { "Display": {}, "AudioPlayer": {}, "VideoApp": {} } } } }, ...
tagged with: alexa-skills-kit
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48511455
downvote count: 0
tagged with: alexa-voice-service
score: 1

http://stackoverflow.com/comment/83183976
type: QuestionComment
comment on: http://stackoverflow.com/q/48103749
has text: What about `df.groupby('Teams')['V1','V2','V3','V4'].mean().apply(lambda x: x/sum(x)).T``. How far is that from your desired result?
score: 0
type: Comment

http://stackoverflow.com/q/48018710
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48018798
has title: urllib.requests or urllib.request
has answer: http://stackoverflow.com/a/48018804
has body: under "urlib" library whether we have 'requests' module or 'request' module When running the below code from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("http://pythonscraping.com/pages/page1.html") bsObj = BeautifulSoup(html.read()) print (bsObj.h1) shell is throwing the warning Warning (from warnings module): File "C:\Python34\lib\site-packages\bs4\__init__.py", line 181 markup_type=markup_type)) UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. The code that caused this warning is on line 1 of the file <string>. To get rid of this warning, change code that looks like this: BeautifulSoup(YOUR_MARKUP}) to this: BeautifulSoup(YOUR_MARKUP, "html.parser")** An Interesting Title when i do this >>>import requests which shell successfully imports the requests module but when I change the above code to from urllib.requests import urlopen from bs4 import BeautifulSoup html = urlopen("http://pythonscraping.com/pages/page1.html") bsObj = BeautifulSoup(html.read()) print (bsObj.h1) shell throws the error message Traceback (most recent call last): File "C:\Python34\scrapetest.py", line 1, in <module> from urllib.requests import urlopen ImportError: No module named 'urllib.requests' and pip tool installs both the modules (request, requests) successfully C:Python34\Scripts>pip install request Requirement already satisfied <use --upgrade to upgrade>: request in c:\python34\lib\site-packages cleaning up... C:Python34\Scripts>pip install requests Requirement already satisfied <use --upgrade to upgrade>: requests in c:\python34\lib\site-packages cleaning up...
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: shell
score: 0
answer count: 2

http://stackoverflow.com/comment/83312924
has text: @usr2564301 [That pattern](https://regex101.com/r/hzkSnc/1) will still match commas inside `[...]` if there are more than one.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48166760
score: 1

http://stackoverflow.com/a/48029402
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48029355
has body: You're almost there. When you use .join on a list it creates a string so you can omit that step. import re activity = "Basketball - Girls 9th" activity = re.sub(r'\s', ' ', activity).split('-') activity = activity[1:2] + activity[0:1] print(" ".join(activity))
answers question: http://stackoverflow.com/q/48029355
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/107281628
type: Comment
has text: Please add some commentary to your answer. Code-only answer are more likely to be deleted from the site.
comment on: http://stackoverflow.com/a/60638343
score: 0
type: AnswerComment

http://stackoverflow.com/q/48143126
answer count: 4
has comment: http://stackoverflow.com/comment/83264577
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48143201
has comment: http://stackoverflow.com/comment/83264517
has comment: http://stackoverflow.com/comment/83264489
has answer: http://stackoverflow.com/a/48143218
has comment: http://stackoverflow.com/comment/83275094
has comment: http://stackoverflow.com/comment/83264557
has answer: http://stackoverflow.com/a/48143309
type: Question
has title: html table scraping in python
has comment: http://stackoverflow.com/comment/83264505
tagged with: tablehtml
score: 0
has body: I wanted to scrape an html table with this code import requests from bs4 import BeautifulSoup page1 = requests.get("http://kworb.net/spotify/country/br_weekly.html") soup = BeautifulSoup(page1.content, 'html.parser') for tr in soup.findAll('tr'): tds =tr.find_all('td') print(tds[0].text) it seems to work: I'm able to get the table and each of its rows in a different tds list. Except that when I try to get the first column for each row (tds[0].text) there's an error. Could you provide some clues?
has comment: http://stackoverflow.com/comment/83264511
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/48143201
possible better answer: http://stackoverflow.com/a/48143218
has answer: http://stackoverflow.com/a/48147387
tagged with: python

http://stackoverflow.com/q/48122608
upvote count: 6
score: -1
has comment: http://stackoverflow.com/comment/83223321
has title: How do I generate random float and round it to 1 decimal place
has comment: http://stackoverflow.com/comment/83223366
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/48122691
has body: How would I go about generating a random float and then rounding that float to the nearest decimal point in Python 3.4?
has answer: http://stackoverflow.com/a/48122637
has comment: http://stackoverflow.com/comment/83221995
has comment: http://stackoverflow.com/comment/83223305
has comment: http://stackoverflow.com/comment/83223340
downvote count: 7
tagged with: python
has comment: http://stackoverflow.com/comment/83222020
linked to: http://stackoverflow.com/q/6088077
tagged with: python-3.x
type: UnansweredQuestion
type: Question

http://stackoverflow.com/a/68536319
accepted answer of: http://stackoverflow.com/q/48160071
answers question: http://stackoverflow.com/q/48160071
type: AcceptedAnswer
score: 0
type: Answer
has body: As mentioned by Daniel Pryden in the comments, the data is different. Some parts of the first bin are quoted as strings, whereas the second bin is standard JSON. I first figured out a way to classify the two different files. I found that the fully JSON one was the default generated manually, and that the partially string one was generated from a config file. Therefore, I added a 'config' flag to the config file, ["PLANETARY", "Naboo", "{'Optimal': [], 'Default': ['B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle Droids', 'B1 Battle D…

http://stackoverflow.com/comment/83321237
comment on: http://stackoverflow.com/q/48153604
score: 0
has text: unfortunately text-align is not supported in . that's what brought me to try this.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48042158
has comment: http://stackoverflow.com/comment/83055842
score: 2
tagged with: hotkeys
linked to: http://stackoverflow.com/q/783531
has answer: http://stackoverflow.com/a/48042519
type: Question
has comment: http://stackoverflow.com/comment/83055050
has title: Run Python script quickly via HotKey
has comment: http://stackoverflow.com/comment/110759130
downvote count: 0
has comment: http://stackoverflow.com/comment/110759106
answer count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/83055292
has comment: http://stackoverflow.com/comment/83054965
has body: I've created a simple script that executes a "moving mouse and keyboard" sequence. Although currently to get this to work I use a Shell (Idle) to run and that is to slow with boot up time and such. Is there a way to have this python file on desktop och with a hotkey swiftly run the code? I tried doing it through terminal but it doesn't like my module. Some info: This is for both mac and windows. The module I imported is pyautogui from PyPi and it works in the shell. Thank you in advance!
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/48098611
has answer: http://stackoverflow.com/a/48100763
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: buildozer
has title: Error during using buildozer for kivy packing
tagged with: kivy
score: 1
has body: For packining I used instrumentalities which are recommended in kivy manual I use for kivy packing virtual machine from https://kivy.org/#download (Oracle virtual box and settings of virtual machine) For buildozer installating I used process https://github.com/kivy/buildozer, for Python 3. I manualy added to buildozer.spec file lines: requirements = python3crystax,kivy android.ndk_path = ~/buildozer/crystax-ndk log_level = 2 Packing is described by next text: . . . . . . . . . [INFO]: Unpacking sdl2_image for armeabi-v7a [INFO]: -&gt; running basename https://www.libsdl.org/projects/SDL_image/release/SDL2_image-2.0.1.tar.gz [INFO]: -&gt; directory context /media/sf_ForBuildozer/.buildozer/android/platform/build/build/bootstrap_builds/sdl2_gradle-python3crystax/jni Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/media/sf_ForBuildozer/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/toolchain.py", line 978, in &lt;module&gt; main() File "/media/sf_ForBuildozer/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/toolchain.py", line 975, in main ToolchainCL() File "/media/sf_ForBuildozer/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/toolchain.py", line 512, in __init__ getattr(self, args.subparser_name.replace('-', '_'))(args) File "/media/sf_ForBuildozer/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/toolchain.py", line 149, in wrapper_func build_dist_from_args(ctx, dist, args) File "/media/sf_ForBuildozer/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/toolchain.py", line 193, in build_dist_from_args build_recipes(build_order, python_modules, ctx) File "pythonforandroid/build.py", line 559, in build_recipes File "pythonforandroid/recipe.py", l…
linked to: http://stackoverflow.com/q/10763440
type: UnansweredQuestion
upvote count: 1
tagged with: python

pandas-groupby
tags question: http://stackoverflow.com/q/48099843
tags question: http://stackoverflow.com/q/48151066
tags question: http://stackoverflow.com/q/48131812
tags question: http://stackoverflow.com/q/48101314
tags question: http://stackoverflow.com/q/48059985
tags question: http://stackoverflow.com/q/48072537
tags question: http://stackoverflow.com/q/48026806
tags question: http://stackoverflow.com/q/48118537
tags question: http://stackoverflow.com/q/48071970
tags question: http://stackoverflow.com/q/48077878
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/48028234
tags question: http://stackoverflow.com/q/48044859
tags question: http://stackoverflow.com/q/48111404
tags question: http://stackoverflow.com/q/48126766
tags question: http://stackoverflow.com/q/48103845
type: Tag
tags question: http://stackoverflow.com/q/48084196
tags question: http://stackoverflow.com/q/48037945
tags question: http://stackoverflow.com/q/48108025
tags question: http://stackoverflow.com/q/48083944
tags question: http://stackoverflow.com/q/48160197
tags question: http://stackoverflow.com/q/48083093
tags question: http://stackoverflow.com/q/48082523
tags question: http://stackoverflow.com/q/48041482
tags question: http://stackoverflow.com/q/48127096
tags question: http://stackoverflow.com/q/48029070
tags question: http://stackoverflow.com/q/48166840
tags question: http://stackoverflow.com/q/48142757
tags question: http://stackoverflow.com/q/48139112
tags question: http://stackoverflow.com/q/48082403
tags question: http://stackoverflow.com/q/48086457

http://stackoverflow.com/comment/83013645
type: Comment
has text: this worked, but why did it happen? Also, how do I know my other numeric fields aren't messed up same way?
type: AnswerComment
comment on: http://stackoverflow.com/a/48022256
score: 0

http://stackoverflow.com/q/48139949
tagged with: python
has title: Get a path from an input
linked to: http://stackoverflow.com/q/21122540
has comment: http://stackoverflow.com/comment/83257817
has comment: http://stackoverflow.com/comment/83259709
duplicate of: http://stackoverflow.com/q/21122540
upvote count: 1
linked to: http://stackoverflow.com/q/6908143
has comment: http://stackoverflow.com/comment/83258313
has comment: http://stackoverflow.com/comment/83257608
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83257576
has comment: http://stackoverflow.com/comment/83328393
answer count: 0
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
has body: I'm using Python 3.5.2. I'm a beginner with Python and I'm trying to get a path from an input. However I get this error and I don't understand it. Traceback (most recent call last): File "./install.py", line 12, in &lt;module&gt; path = input("Path: ") File "&lt;string&gt;", line 1 /home/nicolas/test.txt ^ SyntaxError: invalid syntax Source: #! /usr/bin/python # -*- coding: utf8 -*- import os import sys import time print('---- Test ----- \n') time.sleep(1) path = input("Path: ") print(path) Thank's a lot for help!
type: Question
has comment: http://stackoverflow.com/comment/83260446

http://stackoverflow.com/a/48019116
score: 1
has body: The if check should use rows[0] not list1[0]. for row in list1: if row[0] in list2: list3.append(rows) This can be condensed into a list comprehension. list3 = [row for row in list1 if row[0] in list2]
answers question: http://stackoverflow.com/q/48018999
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/83024041
type: Comment
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/48027076
has text: Defining things as `global` is generally not a great idea. Try getting rid of `global reduced_item`, change the function definition to `def reduce_item(key, value, reduced_item):` and call it from inside `main()` with `reduced_item = reduce_item(node, item, reduced_item)` instead of `reduce_item(node, item)`. There's quite a bit of code to go through here so not sure if that alone will work.

http://stackoverflow.com/a/48069468
upvote count: 2
answers question: http://stackoverflow.com/q/48061681
has comment: http://stackoverflow.com/comment/83130016
has comment: http://stackoverflow.com/comment/83129110
has body: I couldn't get tweepy to install using Anaconda. I'm using the Anaconda distribution on a Mac. I tried pip install tweepy and it installed with no error messages.
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83125362
has comment: http://stackoverflow.com/comment/83130215
has comment: http://stackoverflow.com/comment/83129954
score: 2

http://stackoverflow.com/comment/83001788
comment on: http://stackoverflow.com/q/48016168
has text: Added additional information explaining the problem. `get_or_create` would work, but I'm trying to `bulk_create` as it's much faster for my use case.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83216853
type: Comment
comment on: http://stackoverflow.com/a/48119994
score: 0
type: AnswerComment
has text: Maybe I'm missing something but how do I add this to column A and column B? I see the example output you provided is column 1 and 2. If I do df['A'], df['B'] = yourCode I get values of 1 and 2 instead of what's expected

http://stackoverflow.com/comment/83215711
type: Comment
has text: Hai Vu Yes. that's exactly what im looking for
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48107788

http://stackoverflow.com/comment/83330566
type: AnswerComment
type: Comment
has text: @TadhgMcDonald-Jensen Thanks for the feedback, but I would disagree. When I started off learning the basics of Python, seeing how others would accomplish the same task, especially if there was some explanation alongside really helped me personally.
comment on: http://stackoverflow.com/a/48173557
score: 0

http://stackoverflow.com/comment/83159461
comment on: http://stackoverflow.com/q/48092558
has text: is that the instance property`get_absolute_url` exists?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48138157
has comment: http://stackoverflow.com/comment/83320246
has comment: http://stackoverflow.com/comment/83356579
has body: Changing such line (const std::string ADDON_PYTHON_EXT = "*.py"; changed this line to *.pyo) is not a good solution Main reason is that the kodi is configured to use .py extension to be load from addon.xml file which tradition is followed by all the addon. Changing such headers file will only result to work addon only in your custom build kodi and you have to modify all other addon along with it. The solution I prefer most is you should follow below steps: Create a function in your python script (let's call it as function named service() which execute all the necessary code from your file named service.py) Now create a python file (include.py) to include it in addon.xml containing code as below: include.py import service service.service()
has comment: http://stackoverflow.com/comment/83259350
has comment: http://stackoverflow.com/comment/83265872
has comment: http://stackoverflow.com/comment/83357091
has comment: http://stackoverflow.com/comment/83355543
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48125138

http://stackoverflow.com/comment/124984801
has text: I have invested many hours trying to improve performance without success. Someone with more mathplotlib+pygame knowledge might still improve it. What I want to say, that I was having this problem with my attempts too.
type: Comment
comment on: http://stackoverflow.com/a/67139316
score: 0
type: AnswerComment

http://stackoverflow.com/q/48115669
answer count: 1
has answer: http://stackoverflow.com/a/48115935
score: 0
tagged with: python
has body: I'm trying to parallelize a for loop in python. I get a memory error in the permutations phase of the parameters. I can see why this might fail, but what is the other way to do the same thing. import itertools import multiprocessing LOAD_GEN_KEYS = range(138259) ES_DATA_K = range(9606834) paramlist = list(itertools.product(LOAD_GEN_KEYS, ES_DATA_K)) pool = multiprocessing.Pool() VALID_TS = pool.map(curate_results, paramlist) def curate_results(params): LG = params[0] ES = params[1] ES_S = str(int(ES)/1000) if ES_S == LG: return [LG, ES] else: return [] Any help will be appreciated.
has title: memory error with itertools when parallelizing for loop
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48115935
type: Question

http://stackoverflow.com/comment/83178379
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48101560
has text: Can you give the example output of name `D` as it shares different lengths in `count_users` and `count_samples`.

http://stackoverflow.com/a/68198917
has comment: http://stackoverflow.com/comment/120826263
type: Answer
answers question: http://stackoverflow.com/q/48015613
upvote count: 1
score: 0
downvote count: 1
has body: Call q.task_done() after q.get() ref: https://docs.python.org/3/library/queue.html#queue.Queue.task_done Besides, see this: https://bugs.python.org/issue43911

apache
tag name: apache
tags question: http://stackoverflow.com/q/48069557
tags question: http://stackoverflow.com/q/48147361
tags question: http://stackoverflow.com/q/48134897
tags question: http://stackoverflow.com/q/48097888
tags question: http://stackoverflow.com/q/48018915
tags question: http://stackoverflow.com/q/48070008
tags question: http://stackoverflow.com/q/48096737
tags question: http://stackoverflow.com/q/48122283
tags question: http://stackoverflow.com/q/48153448
tags question: http://stackoverflow.com/q/48067228
tags question: http://stackoverflow.com/q/48035929
type: Tag
tags question: http://stackoverflow.com/q/48115038
tags question: http://stackoverflow.com/q/48155486

http://stackoverflow.com/comment/83212810
comment on: http://stackoverflow.com/q/48117575
type: Comment
type: QuestionComment
has text: Sorry I did not include the root.mainloop though it is in my script. I have updated the script info to show it. I also fixed the display to show proper indenting as in my script. - I will need to check display more carefully in the future
score: 0

http://stackoverflow.com/q/48163799
answer count: 2
has body: I have an array of strings with some elements such as 'na' that can't be converted to float by using x.astype(np.float) as given here. Please suggest any better way than the way I did it. Please find the procedure below (it is a snippet from my jupyter notebook, I have shown the intermediate steps just to demonstrate the changes): In [4]: val_inc Out [4]: array(['na', '38.012', '38.7816', '38.0736', '40.7118', '44.7382', '39.6416', '38.9177', '36.9031', 43.2611, '38.2732', 40.7129, '37.2844', '39.5835', 43.9194, '42.5485', '36.9052', 'na', 41.9264, 45.3568, '44.6239', 38.1079, 45.2393, '32.785', '44.6239', '38.0216', '38.4608', '42.5644', '35.3127', 33.2936, '33.0556', '40.4476', 35.6581, '35.5574', '43.1096', '34.4751', 42.0554, 40.3944, '40.2466', '32.2567', 'na', '38.8594', '43.947', 41.7973, '41.8105', 40.3797, 31.2868, '45.3644', '40.7177', '41.8558', '38.9249', '33.2077', '42.4053', '42.559'], dtype=object) In [5]: val_inc[val_inc == 'na']='0' In [6]: val_inc Out [6]: array(['0', '38.012', '38.7816', '38.0736', '40.7118', '44.7382', '39.6416', '38.9177', '36.9031', 43.2611, '38.2732', 40.7129, '37.2844', '39.5835', 43.9194, '42.5485', '36.9052', '0', 41.9264, 45.3568, '44.6239', 38.1079, 45.2393, '32.785', '44.6239', '38.0216', '38.4608', '42.5644', '35.3127', 33.2936, '33.0556', '40.4476', 35.6581, '35.5574', '43.1096', '34.4751', 42.0554, 40.3944, '40.2466', '32.2567', '0', '38.8594', '43.947', 41.7973, '41.8105', 40.3797, 31.2868, '45.3644', '40.7177', '41.8558', '38.9249', '33.2077', '42.4053', '42.559'], dtype=object) In [7]: val_inc = val_inc.astype(np.float) In [8]: val_inc Out [8]: array([ 0. , 38.012 , 38.7816, 38.0736, 40.7118, 44.7382, 39.6416, 38.9177, 36.9031, 43.2611, 38.2732, 40.7129, 37.2844, 39.5835, 43.9194, 42.5485, 36.9052, 0. , 41.9264, 45.3568, 44.6239, 38.1079, 45.2393, 32.785 , 44.6239, 38.0216, 38.4608, 42.5644, 35.3127, 33.2936, 33.0556, 40.4476, 35.6581, 35.5574, 43.1096, 34.4751, 42.0554, 40.3944, 40.2466, 32.2567, 0. , 38.8594, 43.…
has answer: http://stackoverflow.com/a/48164169
downvote count: 0
tagged with: string
favorite count: 0
duplicate of: http://stackoverflow.com/q/18689235
linked to: http://stackoverflow.com/q/3877209
has title: Is there a better way to convert 'object' type array to numpy array by replacing 'na' with mean?
has comment: http://stackoverflow.com/comment/83368582
has comment: http://stackoverflow.com/comment/83306742
tagged with: python
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/16223483
possible better answer: http://stackoverflow.com/a/48164169
upvote count: 3
linked to: http://stackoverflow.com/q/18689235
accepted answer: http://stackoverflow.com/a/48163830
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83368185
tagged with: arrays
has comment: http://stackoverflow.com/comment/83367924
has answer: http://stackoverflow.com/a/48163830

http://stackoverflow.com/comment/83203734
type: QuestionComment
comment on: http://stackoverflow.com/q/48113848
has text: Have you looked into this https://docs.pytest.org/en/latest/xunit_setup.html
score: 0
type: Comment

http://stackoverflow.com/a/70921549
has body: I found a weird way of doing this when making my first discord bot not knowing of the "case_insensitive" property. I instead used this in my "on_message" function. await bot.process_commands(msg.content.lower()) You can use commands.process_commands() instead since you are in a Cog.
type: Answer
answers question: http://stackoverflow.com/q/48120312
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/a/48080564
answers question: http://stackoverflow.com/q/48080359
score: 2
downvote count: 0
has body: You may use pandas packages. By defining the data frame : import pandas as pd df = pd.DataFrame([['men', 2, '1945-Truman.txt'], ['women', 2, '1945-Truman.txt'], ['people', 10, '1945-Truman.txt'], ['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt'], ['people', 49, '1946-Truman.txt'], ['men', 7, '1947-Truman.txt'], ['women', 2, '1947-Truman.txt'], ['people', 12, '1947-Truman.txt'], ['men', 4, '1948-Truman.txt'], ['women', 1, '1948-Truman.txt'], ['people', 22, '1948-Truman.txt'], ['men', 2, '1949-Truman.txt'], ['women', 1, '1949-Truman.txt'], ['people', 15, '1949-Truman.txt'], ['men', 6, '1950-Truman.txt'], ['women', 2, '1950-Truman.txt'], ['people', 15, '1950-Truman.txt'], ['men', 8, '1951-Truman.txt'], ['women', 2, '1951-Truman.txt'], ['people', 9, '1951-Truman.txt'], ['men', 3, '1953-Eisenhower.txt'], ['women', 0, '1953-Eisenhower.txt'], ['people', 17, '1953-Eisenhower.txt']]) Then df.groupby([0], sort=False)[1].max() return 0 men 12 women 7 people 49 Name: 1, dtype: int64 Is that what you want ?
upvote count: 2
type: Answer

http://stackoverflow.com/a/48156476
type: AcceptedAnswer
score: 15
answers question: http://stackoverflow.com/q/48152754
upvote count: 15
accepted answer of: http://stackoverflow.com/q/48152754
has comment: http://stackoverflow.com/comment/116907895
type: Answer
has body: Just as usual with a scatter plot you may define an array of values and a colormap that maps those values to colors. You can change this array in each iteration to make older points have a different value. In the following we take a value of 0 as transparent and a value of 1 as dark blue and create a colormap with those colors. In each iteration old values are multiplied by a number smaller than one, new values are set to have a value of 1. Running the animation will hence produce fading points. import numpy as np import matplotlib.pyplot as plt import matplotlib.animation from matplotlib.colors import LinearSegmentedColormap fig, ax = plt.subplots() ax.set_xlabel('X Axis', size = 12) ax.set_ylabel('Y Axis', size = 12) ax.axis([0,1,0,1]) x_vals = [] y_vals = [] intensity = [] iterations = 100 t_vals = np.linspace(0,1, iterations) colors = [[0,0,1,0],[0,0,1,0.5],[0,0.2,0.4,1]] cmap = LinearSegmentedColormap.from_list("", colors) scatter = ax.scatter(x_vals,y_vals, c=[], cmap=cmap, vmin=0,vmax=1) def get_new_vals(): n = np.random.randint(1,5) x = np.random.rand(n) y = np.random.rand(n) return list(x), list(y) def update(t): global x_vals, y_vals, intensity # Get intermediate points new_xvals, new_yvals = get_new_vals() x_vals.extend(new_xvals) y_vals.extend(new_yvals) # Put new values in your plot scatter.set_offsets(np.c_[x_vals,y_vals]) #calculate new color values intensity = np.concatenate((np.array(intensity)*0.96, np.ones(len(new_xvals)))) scatter.set_array(intensity) # Set title ax.set_title('Time: %0.3f' %t) ani = matplotlib.animation.FuncAnimation(fig, update, frames=t_vals,interval=50) plt.show()
downvote count: 0

http://stackoverflow.com/a/48072768
type: Answer
score: 3
upvote count: 3
downvote count: 0
has body: Your database name shouldn't contain any of these characters: ' ', '.', '$', '/', '\\', '\x00', '"' Check your database name. The Mongo driver also enforces this rule so the chance that you have a database with a dot in its name is slim.
has comment: http://stackoverflow.com/comment/97905026
answers question: http://stackoverflow.com/q/48059662

http://stackoverflow.com/comment/83344002
type: AnswerComment
type: Comment
has text: There are lots of data , which support the condition of user/id and lots of data is [ a.A_Date < b.B_Date ] . The answer enlighten me to see the source of built-in functions. But it join with every greater data , but i need latest a.A_date to be smaller that b.B_Date
comment on: http://stackoverflow.com/a/48174639
score: 0

http://stackoverflow.com/a/48060672
score: 5
type: AcceptedAnswer
type: Answer
upvote count: 5
downvote count: 0
has body: When you are clicking the links in the interface, React is re-rendering the page without any server-side intervention, and then updating the route in the URL bar. When loading however, you are making that route request to the server direct, and Flask does not have that route registered. Simplest way is to register these routes in the decorator for the function serving your homepage view @app.route('/') @app.route('/users') @app.route('/contracts') def home_page(): If there are many many routes, you may want to use the catch-all URL pattern.
accepted answer of: http://stackoverflow.com/q/48060556
answers question: http://stackoverflow.com/q/48060556

http://stackoverflow.com/comment/83080377
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48053463
has text: If I used a `QThread`, would I be able to send signals to the UI to, say, update a status bar? `Foo.bar()` needs to do several things, and I want the interface to show what it's doing

http://stackoverflow.com/comment/83236809
has text: Fills with NAN :(
type: Comment
comment on: http://stackoverflow.com/a/48125512
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83232094
type: QuestionComment
comment on: http://stackoverflow.com/q/48127586
has text: Sorry, fixed now,
type: Comment
score: 0

http://stackoverflow.com/comment/83014557
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48022472
has text: But i'm trying to traslate from Robber's language to English

http://stackoverflow.com/comment/83197388
type: QuestionComment
comment on: http://stackoverflow.com/q/48110802
score: 0
has text: `But that's not very efficient, ` - do you think is not nice change `Arsenal` for all teams?
type: Comment

http://stackoverflow.com/a/48058166
answers question: http://stackoverflow.com/q/48058082
has body: \ - New line in a multi-line string It is used for splitting a string which has a vast number of characters into multi lines as it is inconvenient to write in a single line. This is something that has effect in the code only. \n - Line break This one on the other hand is a typical line break statement for printing something in a new line. The same thing we use in C and C++ languages. this is something that has effect in the output.
score: 2
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/83190724
type: Comment
comment on: http://stackoverflow.com/a/48103963
has text: Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/350567) by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83291364
type: AnswerComment
score: 0
type: Comment
has text: the points appear blue in the video. In the code above on my pc it appear grey. I will search now how to achieve the different colors of the scatter "dark blue" and "light grey"
comment on: http://stackoverflow.com/a/48147473

http://stackoverflow.com/comment/83219494
comment on: http://stackoverflow.com/a/48121353
type: Comment
has text: all with characteristics 'aab', all with characteristics 'abb', all with characteristics 'aaa'
score: 0
type: AnswerComment

http://stackoverflow.com/q/48111052
tagged with: python
favorite count: 0
type: UnansweredQuestion
score: 6
upvote count: 6
has body: I want to change only the background-color style with BeautifulSoup : My html : I would like to do something like this : soup_td = BeautifulSoup(html_td, "html.parser") soup_td.td["style"]["background-color"] = "red;"
has title: BeautifulSoup, change specific style attribute
type: Question
answer count: 2
downvote count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/53635461
has answer: http://stackoverflow.com/a/48111579

http://stackoverflow.com/comment/83176940
comment on: http://stackoverflow.com/a/48099268
score: 0
type: AnswerComment
has text: Thank you, how could I add the equation of the line and the R^2 values?
type: Comment

http://stackoverflow.com/comment/83093227
has text: I appreciate the help but that did not work for me. I changed the code as described (I added the code to the question above), however, as I describe above, I still don't see the required information (e.g. when I grep the peptide sequence in output file from the suggested code, the peptide sequence is not there?). Thank you for the help though, i appreciate it.
comment on: http://stackoverflow.com/a/48060325
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48043758
answer count: 1
has comment: http://stackoverflow.com/comment/83068223
has title: Python multiprocessing with parallel save to netCDF4 file
has answer: http://stackoverflow.com/a/48044319
tagged with: python
linked to: http://stackoverflow.com/q/25557686
accepted answer: http://stackoverflow.com/a/48044319
tagged with: parallel-processing
type: AnsweredQuestion
has body: I am performing a simulation in which I want to save the snapshots of the state vector, and calculate do it for different parameters. I have two control parameters that I which to scan (p and a in the example bellow). I therefore save the simulation results for one netCDF4 file, in which two of the dimensions are for the two control parameters. When I run the simulation for one parameters set the file is saved correctly, but when I try to run apply_async from multiprocessing the netCDF4 at the end of the process is unaccessible. My full code is at this github repository, but basically what I'm trying to do is this: import multiprocessing as mp import time as timer import netCDF4 import numpy as np def run_sim_for_p_a(p,a,pstep,astep,step,max_time,u0,fname): time_ar=np.arange(0,max_time,step) u = np.ones((len(time_ar),1024)) u[0]=u0 print "Calculating for p,a:",p,a for i,t in enumerate(time_ar[1:]): u[i+1] = u[i]*np.cos(t)*np.sin(a)*np.sin(p) for tstep,t in enumerate(time_ar): save_p_a_snapshot(fname,pstep,astep,tstep,p,a,t,u[tstep]) # save the results into the netCDF4 file def apply_async_and_save_grid(pmin,pmax,fname, Np=10,Na=10, step=None,max_time=500.0,numproc=10): start = timer.time() setup_p_a_scan(fname) # Setup a netCDF4 file for the simulations if step is None: step=max_time p_range = np.linspace(pmin,pmax,Np) init = np.random.random((1024)) a_range = np.linspace(0,1,Na) availble_cpus = int(available_cpu_count() - 2) numproc=min(numproc,availble_cpus) print "Using",numproc," processors" pool = mp.Pool(processes=numproc) for i,p in enumerate(p_range): for j,a in enumerate(a_range): pool.apply_async(run_sim_for_p_a, args = (p,a,i,j,step,max_time,init,fname)) pool.close() pool.join() print "Took ",timer.time()-start if __name__=="__main__": apply_async_and_save_grid(1.0,2.0,"test",Np=2,Na=4,step=1.0,max_time=10)
tagged with: netcdf4
has comment: http://stackoverflow.com/comment/83059140
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
score: 0

http://stackoverflow.com/comment/83170928
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48097838
has text: Sometimes when you know most use case will involved a fixed number of arguments that are not contained in a list, yet you don't know that number because you don't know the use case, it's cleaner to use `*args`. Consider `zip`. It much nicer to write `zip(list1, list2)` or `zip(l1,l2,l3)` than `zip([list1, list2])` or `zip([l1, l2, l3])`.
type: AnswerComment

http://stackoverflow.com/comment/133305141
type: Comment
has text: Also, do you have to manually change this every time you want to debug a different file?
score: 4
type: AnswerComment
comment on: http://stackoverflow.com/a/48195425

http://stackoverflow.com/a/53910933
upvote count: 39
downvote count: 0
has body: Isn't this more economical (albeit longer): a = torch.zeros(10, dtype=torch.bool) or, in older versions, a = torch.zeros(10, dtype=torch.uint8) (Thanks @drevicko for the pointer to bool.)
type: Answer
has comment: http://stackoverflow.com/comment/105570092
answers question: http://stackoverflow.com/q/48151637
score: 39
has comment: http://stackoverflow.com/comment/125143360

http://stackoverflow.com/comment/83165004
has text: does that just mean running it on in an admin account? if so then yes, if not then how may I find out?
score: 0
comment on: http://stackoverflow.com/q/48093726
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83029682
comment on: http://stackoverflow.com/a/48029730
type: AnswerComment
score: 0
type: Comment
has text: thanks, it works now. Sorry for the non-formatted code in the comment

http://stackoverflow.com/comment/83398720
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48097838
has text: Just a few days after having to ask why on earth would I ever do this, I'm writing a function where using *args is the only reasonable solution. The function requests information about a series of data fields, the number of data fields is variable, from one to whatever and passing a list of field names is cumbersome.
type: AnswerComment

http://stackoverflow.com/comment/83246019
comment on: http://stackoverflow.com/q/48134314
score: 0
type: Comment
type: QuestionComment
has text: you need to return the result from `walk` call too i.e `return walk(ele)` in your `if`

http://stackoverflow.com/comment/83026513
has text: the automatically word-wraps and uses a vertical scroll-bar is in a 30 x 30 area
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48018458

http://stackoverflow.com/comment/83374104
score: 0
type: Comment
has text: @ivofilipe can you edit your question to incorporate your new code then?
comment on: http://stackoverflow.com/a/48028779
type: AnswerComment

http://stackoverflow.com/comment/83191105
has text: 1- Use `name` as real `_id`(`'_id'=name`), 2- `whole_DB = db.file.find()` than `whole_DB.forEach(..............)` why scan whole db twice ? 3- `db.file.find() != db.file.aggregate(......)` So all db entry not an search results. 4- `db['PA'].aggregate(...............)` mean `P = product`, `A= product_name _first letter` Use `collections` for To avoid creating a large hash file.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48107682
type: QuestionComment

http://stackoverflow.com/comment/83269312
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48145638
has text: The `if __name__` .. *shouldn't* be *inside* the class definition (ie. it's indented too much, and should be in the "main" file whatever that is). Also, make sure the posted code is the actual code / issue .. it changed a good bit from the first edits.
type: Comment

http://stackoverflow.com/a/48131426
type: Answer
score: 5
upvote count: 5
has body: Symbolic setup If you are looking for symbolic solutions, use symbolic functions: e.g., SymPy's log not NumPy's log. The normal CDF is also available from SymPy's stats module as cdf(Normal("x", 0, 1)). The correct SymPy setup would be this: from sympy import Eq, Rational, Symbol, log from sympy.stats import cdf, Normal eqn = Eq((x-Rational('0.2'))/Rational('0.3'), cdf(Normal("x", 0, 1))(log(Rational(100, 110)) + x**2/2)/x) Notice that I put Rational('0.2') where you had 0.2. The distinction between rationals and floats is important for symbolic math. The equation now looks good from the formal point of view: Eq(10*x/3 - 2/3, (erf(sqrt(2)*(x**2/2 - log(11) + log(10))/2)/2 + 1/2)/x) Unfortunately it also looks hopeless: there's no closed form solution for things like that, involving a transcendental function equated to a polynomial. Naturally, solve(eqn) will fail. So all of the above does is demonstrate correct use of SymPy, but it doesn't change the fact that there is no symbolic solution. Numeric solution To solve this numerically, do the opposite: drop the SymPy parts and import fsolve from SciPy. from scipy.stats import norm from scipy.optimize import fsolve import numpy as np f = lambda x: (x-0.2)/0.3 - norm.cdf((np.log(100/110) + x**2/2)/x) print(fsolve(f, 1)) # 1 is a random initial guess The answer is 0.33622392.
answers question: http://stackoverflow.com/q/48131064
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48131064

http://stackoverflow.com/q/48121458
tagged with: python
has answer: http://stackoverflow.com/a/48121682
answer count: 4
score: 2
has comment: http://stackoverflow.com/comment/83219789
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83219753
tagged with: design-patterns
has title: Python design pattern to implement different variations of a function
has answer: http://stackoverflow.com/a/48121790
linked to: http://stackoverflow.com/q/963965
has comment: http://stackoverflow.com/comment/83220392
has comment: http://stackoverflow.com/comment/83220375
has comment: http://stackoverflow.com/comment/83220426
has comment: http://stackoverflow.com/comment/83220767
type: Question
has body: I have a generic smoothing function, and based on a configuration file (yaml which will be loaded as a dictionary), different implementation (boxcar or gaussian) will be called. These implementations have different number of arguments, for example boxcar requires winsize, while gaussian require winsize and variance. Here is my current implementation: def smoothing(dataDf, selected_columns, kwargs): method = kwargs['method'] if method == 'boxcar': boxcar(dataDf, selected_columns, kwargs['arguments']) elif method == 'gaussian': gaussian(dataDf, selected_columns, kwargs['arguments']) else: raise NotImplementedError Would there be a better way to implement this?
has comment: http://stackoverflow.com/comment/83220690
downvote count: 0
has answer: http://stackoverflow.com/a/48121673
favorite count: 0
linked to: http://stackoverflow.com/q/2283210
has answer: http://stackoverflow.com/a/48122086
has comment: http://stackoverflow.com/comment/83221176

http://stackoverflow.com/comment/83285983
type: Comment
has text: I thought too much and created a dict based on repeated range for grouping . Nice one.
type: AnswerComment
comment on: http://stackoverflow.com/a/48153520
score: 0

http://stackoverflow.com/q/48107855
tagged with: http://stackoverflow.com/tag/svg
upvote count: 8
type: Question
tagged with: python
answer count: 1
tagged with: matplotlib
has body: I am generating and saving SVG images using matplotlib and would like to make them as reproducible as possible. However, even after setting np.random.seed and random.seed, the various id and xlink:href values in the SVG images still change between runs of my code. I assume these differences are due to the backend that matplotlib uses to render SVG images. Is there any way to set the seed for this backend such that identical plots produce identical output between two different runs of the code? Sample code (run this twice, changing the name in plt.savefig for the second run): import random import numpy as np import matplotlib.pyplot as plt random.seed(42) np.random.seed(42) x, y = np.random.randn(4096), np.random.randn(4096) heatmap, xedges, yedges = np.histogram2d(x, y, bins=(64,64)) fig, axis = plt.subplots() plt.savefig("random_1.svg") Compare files: diff random_1.svg random_2.svg | head 35c35 &lt; " id="md3b71b67b7" style="stroke:#000000;stroke-width:0.8;"/&gt; --- &gt; " id="m7ee1b067d8" style="stroke:#000000;stroke-width:0.8;"/&gt; 38c38 &lt; &lt;use style="stroke:#000000;stroke-width:0.8;" x="57.6" xlink:href="#md3b71b67b7" y="307.584"/&gt; --- &gt; &lt;use style="stroke:#000000;stroke-width:0.8;" x="57.6" xlink:href="#m7ee1b067d8" y="307.584"/&gt; 82c82 &lt; &lt;use style="stroke:#000000;stroke-width:0.8;" x="129.024" xlink:href="#md3b71b67b7" y="307.584"/&gt;
accepted answer: http://stackoverflow.com/a/48110626
score: 8
tagged with: reproducible-research
has title: Set random seed for matplotlib plotting backend
tagged with: random
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48110626

http://stackoverflow.com/q/48134649
has answer: http://stackoverflow.com/a/48142652
linked to: http://stackoverflow.com/q/893053
has body: According to the answer to question, I installed readline for python to resolve backspace issue. If I logged in CentOS 7 as a root, I can backspace without any problems;however, if I logged in as a user, I have to run pip install readline to resolve backspace problem. I do not know where to set the readline so I do not need to reinstall it every time when I log in as a user. In my computer, it does not define "PYTHONSTARTUP" which is mentioned in one of solutions in question. Any further help and suggestion would be highly appreciated.
answer count: 1
has title: How to set configuration for readline in Python
type: Question
has comment: http://stackoverflow.com/comment/83250132
tagged with: python
tagged with: readline
has comment: http://stackoverflow.com/comment/83246563
score: 0
linked to: http://stackoverflow.com/q/36936212
type: UnansweredQuestion

http://stackoverflow.com/comment/83135241
type: QuestionComment
comment on: http://stackoverflow.com/q/48080315
has text: I see! Thanks. I'll go ahead and remove that setting then.
score: 0
type: Comment

http://stackoverflow.com/a/48048486
answers question: http://stackoverflow.com/q/48045185
has body: The PCA algorithm is based on calculating the first eigenvectors of the co-variance matrix of the samples. For this purpose, you can use MATLAB's cov, and eig functions as follows: X = rand(10,3) %generate samples randomly NUM_OF_EIGENS = 2; %number of eigen vectors to extract C = cov(X); [principalComponents, eigenValues]= eigs(C,NUM_OF_EIGENS); The two principal components can be extracted as follows: principalComponents(:,1) principalComponents(:,2)
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48045185

http://stackoverflow.com/q/48128318
has comment: http://stackoverflow.com/comment/83241178
type: Question
has comment: http://stackoverflow.com/comment/83234327
has comment: http://stackoverflow.com/comment/83318679
score: 2
downvote count: 0
has body: I am iterating over x and y in a number of rows and columns and I have a 2DArray 'inarray' which holds the brushfire algorithm cost per square similar to this: array[[900 0 1 2 3 4 5 6 7] [ 2 1 2 3 4 5 6 7 8] [ 3 2 900 4 5 6 7 8 9] [ 4 3 4 5 6 7 8 9 10] [ 5 4 5 6 7 8 9 10 11] [ 6 5 6 7 8 9 10 11 12] [ 7 6 7 8 9 10 11 12 13] [ 8 7 8 9 10 11 12 13 14] [ 9 8 9 10 11 12 13 14 15] [ 10 9 10 11 12 13 14 15 16]] Where 900 are obstacles, 0 is the goal, and the numbers are steps costs. From this 2DArray I want to generate a vectorfield so I implemented the code: def vectorfield(inarray, goal, r, c): vectorarray = np.zeros((r,c), dtype=np.int32) for y in range(0,c): for x in range(0,r): xy = (x,y) neighbours = get_direction(xy, r, c) best_nbr = min(neighbours.keys(), key=lambda n: inarray[n]) vectorarray[xy] = neighbours[best_nbr] vectorarray[goal] = -1 return vectorarray I made another 2D array to not overwrite the map so that the costs still can be referenced. Then I looped through the rows and columns, and for each point I generated directions values which are a dictionary of points:angle : directions = { (x - 1, y + 1): 225, (x, y + 1): 180, (x + 1, y + 1): 135, (x - 1, y): 270, (x + 1, y): 90, (x - 1, y - 1): 315, (x, y - 1): 0, (x + 1, y - 1): 45, } Where each point is filtered out if it is out the map. Then I use the min() function to get the point with the least cost in its neighbours. Finally, the value of the neighbours (angle pointing to the next square) is placed in the vectorarray. I should say it works without the decorators The problem is that I wanted to the @jit or @njit decorators to speed up the execution and I don't understand how to fix them. Errors with @njit: Traceback (most recent call last): File "/Users/aditya/Desktop/PycharmPrograms/RandomIdeas/lel1.py", line 334, in &lt;module&gt; main() File "/Users/aditya/Desktop/PycharmPrograms/RandomIdeas/lel1.py", line 313, in main inarray = vectorfield(inarray, (0,1), w, h) File "/Users/aditya/Library/Python/…
favorite count: 0
has comment: http://stackoverflow.com/comment/83234323
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: numba
tagged with: python
has title: Numba @jit and @njit giving errors

http://stackoverflow.com/q/48143147
score: 0
answer count: 1
tagged with: tkinter-entry
favorite count: 0
tagged with: background-color
tagged with: python
accepted answer: http://stackoverflow.com/a/48143240
type: AnsweredQuestion
tagged with: tkinter
upvote count: 1
downvote count: 1
type: Question
has title: Change background colour of entry box when button clicked, (entry box with loop)
has body: Here is my code: from tkinter import * root = Tk() fields = 'Name', 'Age' entries = [] UserInps = [] def Form(root, fields): for field in fields: row = Frame(root) vertical = Frame(root) lab = Label(row, text=field) ent = Entry(row) row.pack() vertical.pack() lab.pack() ent.pack() entries.append((field, ent)) return entries def Check(): if (entries[0][1].get()) == "B": #checks if the name inputted is "B" #HERE IS THE CODE THAT I NEED. HOW DO I CHANGE THE BACKGROUND COLOUR OF THE ENTRY BOX FOR NAME TO GREEN if __name__ == '__main__': ents = Form(root, fields) row = Frame(root) row.pack() CheckButton = Button(row, text="Check", command=Check) CheckButton.pack() root.mainloop() The code runs fine I just don't know how to change the colour of the background of the name entry box. So in this example, like it states if the user enters the name "B", I want that specific entry box (where they entered B) to change to blue. And before anyone asks why I am using a loop when there is just a form with two rows. My actual project has more rows. This is just a dumbed down version to post on here.
has answer: http://stackoverflow.com/a/48143240

http://stackoverflow.com/q/48098140
tagged with: django-rest-framework
type: UnansweredQuestion
has body: When rendering a model Model1 that has a models.ManyToManyField field to another model Model2 that has ~50K entries in the DB, the default browsable HTML rendering takes about 3s to answer, while JSON rendering takes around 30ms. Turning on the Django Debug Toolbar, shows that the following SQL request : SELECT `app_model2`.`id`, `app_model2`.`field1` ... FROM `app_model2`; takes almost 2s by itself. That query is triggered when rendering the line 14 of https://github.com/encode/django-rest-framework/blob/522d45354633f080288f82ebe1535ef4abbf0b6e/rest_framework/templates/rest_framework/horizontal/select_multiple.html#L14 Is there a way to prevent the rendering to do such expensive SQL request? In our case, we don't expect something more than just the id from these Model2 entries to be rendered.
tagged with: python
has title: Django REST framework makes huge queries when rendering browsable HTML
has answer: http://stackoverflow.com/a/48100644
tagged with: django
type: Question
score: 0
answer count: 1

http://stackoverflow.com/comment/83108260
type: AnswerComment
score: 0
has text: Thanks @DarkCygnus for details explanation much appreciated! Where i am still confused is the timesteps. Timesteps here are number of samples?
comment on: http://stackoverflow.com/a/48065234
type: Comment

http://stackoverflow.com/q/48156939
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/38969267
has comment: http://stackoverflow.com/comment/83293280
score: 1
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48158044
tagged with: python
upvote count: 1
has comment: http://stackoverflow.com/comment/83293458
type: Question
has answer: http://stackoverflow.com/a/48157190
tagged with: apache-spark-sql
has body: include_cols_path = sys.argv[5] with open(include_cols_path) as f: include_cols = f.read().splitlines() include_cols is a list of strings df1 = sqlContext.read.csv(input_path + '/' + lot_number +'.csv', header=True).toPandas() df1 is a dataframe of a large file. I would like to only retain the columns with names that contain any of the strings in include_cols.
has answer: http://stackoverflow.com/a/48164089
tagged with: pyspark
downvote count: 0
has title: Python Pandas: How to remove all columns from dataframe that contains the values in a list?
linked to: http://stackoverflow.com/q/14940743

http://stackoverflow.com/q/48121909
tagged with: python
tagged with: excel
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48122065
has body: I am trying to read a lot of excel files in a folder that have the same format. My keys are not in the first row, so when I run this code, I gives me KeyError: '"A"' it's tricky as well because the name of my columns are "A" (with the citation marks). How can I have it go through every file and read the data for each column in each file? import numpy as np import scipy.io as sio import scipy import matplotlib.pyplot as plt import os import pandas as pd from matplotlib import gridspec from tkinter import filedialog from tkinter import * import scipy.stats as st #GUI root=Tk() root.withdraw() #closes tkinter window pop-up path=filedialog.askdirectory(parent=root,title='Choose a folder') path=path+'/' print('Folder Selected',path) files=os.listdir(path) length=len(files) print('Files inside the folder',files) Files=[] for s in os.listdir(path): Files.append(pd.read_excel(path+s)) #initialize arrays A=[None]*length B=[None]*length C=[None]*length for filenumber in range(0,length): A[filenumber] = Files[filenumber]['"A"'] B[filenumber] = Files[filenumber]['"B"'] C[filenumber] = Files[filenumber]['"C"']
score: 0
answer count: 2
has title: Reading excel with python when keys are not in first row
has answer: http://stackoverflow.com/a/48122065
has answer: http://stackoverflow.com/a/48123832
possible better answer: http://stackoverflow.com/a/48123832

http://stackoverflow.com/q/48126818
tagged with: python
has body: can you help me make this more compact? I need to make it so that for every value of board[0] I get another picture. My script works but I find it too long and bulky. if board[0] == 0 : square_1_button.config(image=T0S) if board[0] == 1 : square_1_button.config(image=T1S) if board[0] == 2 : square_1_button.config(image=T2S) if board[0] == 3 : square_1_button.config(image=T3S) if board[0] == 4 : square_1_button.config(image=T4S) if board[0] == 5 : square_1_button.config(image=T5S) if board[0] == 6 : square_1_button.config(image=T6S) if board[0] == 7 : square_1_button.config(image=T7S) if board[0] == 8 : square_1_button.config(image=T8S) if board[0] == 9 : square_1_button.config(image=T9S) if board[0] == 10 : square_1_button.config(image=T10S) if board[0] == 11 : square_1_button.config(image=T11S) if board[0] == 12 : square_1_button.config(image=T12S) if board[0] == 13 : square_1_button.config(image=T13S) if board[0] == 14 : square_1_button.config(image=T14S) if board[0] == 15 : square_1_button.config(image=T15S) if board[0] == 16 : square_1_button.config(image=T16S) if board[0] == 17 : square_1_button.config(image=T17S) if board[0] == 18 : square_1_button.config(image=T18S) if board[0] == 19 : square_1_button.config(image=T19S) if board[0] == 20 : square_1_button.config(image=T20S) if board[0] == 21 : square_1_button.config(image=T21S) if board[0] == 22 : square_1_button.config(image=T22S) if board[0] == 23 : square_1_button.config(image=T23S) if board[0] &gt;= 24 : square_1_button.config(image=T24S)
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83561721
upvote count: 1
has comment: http://stackoverflow.com/comment/83230504
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48126979
linked to: http://stackoverflow.com/q/1087255
has answer: http://stackoverflow.com/a/48287581
answer count: 2
tagged with: user-interface
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/83230749
has title: How to make code more compact?

http://stackoverflow.com/a/48081756
has comment: http://stackoverflow.com/comment/83142150
has body: Brief Your best bet is to create a regex for all the possible emoticons. The regular expressions below should help you formulate a pattern that matches the emoticons you need. Code You can use either of the following: See regex in use here (?&lt;!:)[()] See regex in use here \b[()]|[()]\b Explanation (?&lt;!:)[()] Matches a ( or ) where the preceding character is not : \b[()]|[()]\b Matches a ( or ) where a word boundary position is found on either the left or right side of the character
answers question: http://stackoverflow.com/q/48081491
type: Answer
score: 2
upvote count: 3
downvote count: 1

http://stackoverflow.com/q/48038974
has title: Python 3rd Party Modules in AWS Lambda through Cloud9
tagged with: aws-cloud9
type: UnansweredQuestion
tagged with: cloud9
tagged with: amazon-web-services
has body: I had a quick question. I recently started to learn python and have been using Cloud9 as my environment. I've created a code for Alexa in python that uses BeautifulSoup, meaning that AWS Lambda throws an error every time I run it (as it does not recognize BeautifulSoup as a model). I was wondering, since I'm working in Cloud9, how do I allow/permit AWS Lambda to work with BeautifulSoup?
answer count: 1
downvote count: 0
score: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48044751
tagged with: python
tagged with: lambda
upvote count: 1

http://stackoverflow.com/comment/83217191
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48120181
has text: https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form
type: Comment

http://stackoverflow.com/comment/83022819
has text: Ok man, dont worry. I think i was typed everything to everyone understand. The user "schwobaseggl" understand in this mode that i put and solve the problem. Thanks.
type: Comment
comment on: http://stackoverflow.com/q/48015960
score: 0
type: QuestionComment

http://stackoverflow.com/q/48141064
favorite count: 0
tagged with: python-3.x
has title: Parse multiple values from SOAP response
tagged with: soap
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/48141177
type: AnsweredQuestion
score: 1
has body: I have an XML SOAP response: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soapenv:Header/&gt; &lt;soapenv:Body&gt; &lt;trk:TrackResponse xmlns:trk="http://www.web.com/XMLSchema/Track/v2.0"&gt; &lt;trk:Package&gt; &lt;trk:Activity&gt; &lt;trk:ActivityLocation&gt; &lt;trk:Address&gt; &lt;trk:City&gt;RUEMLANG&lt;/trk:City&gt; &lt;trk:CountryCode&gt;CH&lt;/trk:CountryCode&gt; &lt;/trk:Address&gt; &lt;/trk:ActivityLocation&gt; &lt;/trk:Activity&gt; &lt;trk:Activity&gt; &lt;trk:ActivityLocation&gt; &lt;trk:Address&gt; &lt;trk:City&gt;BERLIN&lt;/trk:City&gt; &lt;trk:CountryCode&gt;DE&lt;/trk:CountryCode&gt; &lt;/trk:Address&gt; &lt;/trk:ActivityLocation&gt; &lt;/trk:Activity&gt; &lt;/trk:Package&gt; &lt;/trk:TrackResponse&gt; &lt;/soapenv:Body&gt; &lt;/soapenv:Envelope&gt; I'm trying to get the cities between &lt;trk:City&gt; but can't figure it out. I have tried the below without any results import xml.etree.ElementTree e = xml.etree.ElementTree.parse('test.xml').getroot() for element in e.findall('.//trk:City'): print (element.text)
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48141177
downvote count: 0
answer count: 1

http://stackoverflow.com/a/48082583
has body: it expects int value so first try putting -r in quotes and then after a space pass an integer value it will work. say for instance,the code is stored in a file named q1.py you can run it as: python q1.py '-r' 5 on running this it is expected to give Namespace(box=5)
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/48082408
score: -1
has comment: http://stackoverflow.com/comment/83139686
downvote count: 1

http://stackoverflow.com/comment/83062210
score: 0
type: QuestionComment
has text: Sorry, but none of the answers is working for me. I'm keep getting freeze with the functions
type: Comment
comment on: http://stackoverflow.com/q/48044766

http://stackoverflow.com/comment/83274780
has text: @jezrael apologies, I didn't see the code you put below the first 2 lines. I will try that, however I'm wondering whether by using a dictionary to store the data, I can use pandas functions like dataframe concatenation, which is what I would like to do with the 12 data frames
comment on: http://stackoverflow.com/a/48147832
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48058169
type: UnansweredQuestion
has title: Converting Webelement.text to a string
tagged with: selenium
has comment: http://stackoverflow.com/comment/83114554
type: Question
has comment: http://stackoverflow.com/comment/83102225
has answer: http://stackoverflow.com/a/48075012
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83094046
has comment: http://stackoverflow.com/comment/83109515
has comment: http://stackoverflow.com/comment/83088872
tagged with: python
has body: I am trying to use machine learning to perform sentiment analysis on data from twitter. To aggregate the data, I've made a class which will mine and pre-process data. In order to clean and pre-process the data, I'd like to convert each tweet's text to a string. However, when the line of code in the inner for loop in the massMine method is called, i get a WebDriverException: no such session. The relevant bits of code are below, any input is appreciated, thanks. import time from selenium import webdriver from selenium.webdriver.common.keys import Keys import numpy as np import pandas import re class TweetMiner(object): def __init__(self): self.base_url = u'https://twitter.com/search?q=from%3A' self.raw_data = [] def mineTweets(self, query, tweet_quota): ''' Mine data from a singular twitter account, input consists of a twitter handle, and a value indicating how much data to mine Ex: “@diddy” should be inputted as “diddy” ''' browser = webdriver.Chrome() url = self.base_url + query browser.get(url) time.sleep(1) body = browser.find_element_by_tag_name('body') for _ in range(tweet_quota): body.send_keys(Keys.PAGE_DOWN) time.sleep(0.2) tweets = browser.find_elements_by_class_name('tweet-text') for tweet in tweets: print(tweet.text) browser.close() return tweets def massMine(self, inputArray, dataSize): ''' Mine data from an array of twitter accounts, input array consists of twitter handles and a value indicating how much data to mine Ex: “@diddy” should be inputted as “diddy” ''' for user in inputArray: rtn = "" tweets = self.mineTweets(user,dataSize) for tweet in tweets: rtn += (tweet.text) return rtn EDIT: I don't know what caused this error - but if anyone stumbles across this post with a similar error I was able to workaround by simply writing each tweet to a text file.

http://stackoverflow.com/q/48135015
tagged with: pandas
has comment: http://stackoverflow.com/comment/83247732
type: UnansweredQuestion
tagged with: python
tagged with: merge
has body: I have a big dataset containing 100M records, where each record has two id columns as the foreign keys to two other files. After merging the datasets, each record have around 3000 columns. Since it is not possible to join this huge dataset with two other files, I have divided this dataset into 1000 files each containing 100k records. The following function reads a file and merge it with two other files: def merge_data(path): db1 = pd.read_csv('../data/db1.csv') db2 = pd.read_csv('../data/db2.csv') temp = pd.read_csv(path) temp = pd.merge(temp, db1, on='db1_id', how='left') temp = pd.merge(temp, db2, on='db2_id', how='left') return temp.drop('target', axis=1), temp['target'] Now, the following code tries to read these files sequentially: for f in files_list: Xdf, ydf = merge_data(f) # processing Xdf, ydf When I run this code, the first file is read without problem, but for the second file, the RAM overflowed and it starts to use the swap which slows down the process and freezes the jupyter notebook. I think if I can release the memory assigned to Xdf and ydf, the problem is resolved. For now, I have tried the gc.collect() and del Xdf, ydf, without any success. Any advice to handle this situation is appreciated.
has comment: http://stackoverflow.com/comment/83251917
answer count: 0
tagged with: memory
has comment: http://stackoverflow.com/comment/83247487
type: Question
has title: Memory overflow when loading multiple files sequentially in python
has comment: http://stackoverflow.com/comment/83251700
score: 0

http://stackoverflow.com/a/48170144
has comment: http://stackoverflow.com/comment/83355939
has comment: http://stackoverflow.com/comment/83332696
has comment: http://stackoverflow.com/comment/83320395
has comment: http://stackoverflow.com/comment/83327807
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48168329
score: 0
has comment: http://stackoverflow.com/comment/83321873
accepted answer of: http://stackoverflow.com/q/48168329
has comment: http://stackoverflow.com/comment/83320615
has comment: http://stackoverflow.com/comment/83329201
type: Answer
has body: You could try the following: key_list = ["animal.dog", "animal.dog.tail", "animal.cat", "tree", "fruits", "timestamp"] match = { "$match": { "cid": ObjectId("57fe39972b8dbc1387b20913") } } project = { "$project": {} } group = { "$group": {} } for item in key_list: if item == "timestamp": project["$project"]["day"] = { "$substr": ["$"+item, 0, 10] } group["$group"]["_id"] = "$day" break sum = {"$sum": ""} sum["$sum"] = "$"+item.replace(".", "_") project["$project"][item.replace(".", "_")] = "$"+item group["$group"][item.replace(".", "_")] = sum pipeline = [match, project, group]
has comment: http://stackoverflow.com/comment/83341669
has comment: http://stackoverflow.com/comment/83327770

http://stackoverflow.com/comment/83240380
score: 1
has text: `df = dataset.drop('DATE', axis=1)` or `dataset.drop('DATE', axis=1, inplace=True)`
comment on: http://stackoverflow.com/q/48131527
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48029370
downvote count: 0
score: 13
accepted answer of: http://stackoverflow.com/q/48029249
answers question: http://stackoverflow.com/q/48029249
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83028905
type: Answer
has body: The attribute __dict__ is supposed to contain user defined attributes. No, the __dict__ contains the dynamic attributes of an object. Those are not the only attributes an object can have however, the type of the object is usually also consulted to find attributes. For example, the methods on a class can be found as attributes on an instance too. Many such attributes are descriptor objects and are bound to the object when looked up. This is the job of the __getattribute__ method all classes inherit from object; attributes on an object are resolved via type(object).__getattribute__(attribute_name), at which point the descriptors on the type as well as attributes directly set on the object (in the __dict__ mapping) are considered. The __bases__ attribute of a class is provided by the class metatype, which is type() by default; it is a descriptor: &gt;&gt;&gt; class Foo: ... pass ... &gt;&gt;&gt; Foo.__bases__ (&lt;class 'object'&gt;,) &gt;&gt;&gt; type.__dict__['__bases__'] &lt;attribute '__bases__' of 'type' objects&gt; &gt;&gt;&gt; type.__dict__['__bases__'].__get__(Foo, type) (&lt;class 'object'&gt;,) __dict__ just happens to be a place to store attributes that can have any valid string name. For classes that includes several standard attributes set when the class is created (__module__ and __doc__), and others that are there as descriptors for instances of a class (__dict__ and __weakref__). The latter must be added to the class, because a class itself also has those attributes, taken from type, again as descriptors. So why is __bases__ a descriptor, but __doc__ is not? You can't set __bases__ to just anything, so the descriptor setter checks for specific conditions and is an opportunity to rebuild internal caches. The Python core developers use descriptors to restrict what can be set, or when setting a value requires additional work (like validation and updating internal structures).
upvote count: 13
has comment: http://stackoverflow.com/comment/83029369

http://stackoverflow.com/comment/83097961
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/48062504
has text: You shadow your context variable `'content'` in the loop `for content in page`. Then `content.pk` fails ...
type: Comment

http://stackoverflow.com/a/48040899
type: AcceptedAnswer
upvote count: 5
has comment: http://stackoverflow.com/comment/83052342
has comment: http://stackoverflow.com/comment/83052169
accepted answer of: http://stackoverflow.com/q/48040767
type: Answer
answers question: http://stackoverflow.com/q/48040767
has comment: http://stackoverflow.com/comment/113758148
downvote count: 0
score: 5
has body: You don't need Firebase Hosting for using Firebase Functions, and as you mentioned Firebase Hosting is for static pages. Firebase Functions are hosted on firebase (independent from Firebase Hosting for static pages), and currently don't support python. For HTTP trigger Firebase Functions you simply make HTTP requests to your function's url, from any backend or from frontend itself. Firebase DB/Storage and other trigger functions work in the same way, but don't explicitly call then they are triggered on specific events in DB/Storage etc. that you specify when defining functions.
has comment: http://stackoverflow.com/comment/113515369

http://stackoverflow.com/comment/83225436
type: QuestionComment
has text: Your best bet may be to redirect the output from the C stream, modify it using python, and the print it as binary. [See this post for details.](https://stackoverflow.com/questions/35304920/how-to-redirect-c-level-streams-in-python-in-windows)
comment on: http://stackoverflow.com/q/48123877
score: 0
type: Comment

http://stackoverflow.com/comment/83251906
type: Comment
comment on: http://stackoverflow.com/a/48136781
has text: If this worked out for you, can you accept my answer?
type: AnswerComment
score: 0

http://stackoverflow.com/q/48102882
has title: How to implement the derivative of Leaky Relu in python?
has comment: http://stackoverflow.com/comment/83186926
downvote count: 0
tagged with: activation-function
possible better answer: http://stackoverflow.com/a/71807684
has comment: http://stackoverflow.com/comment/83181757
favorite count: 0
has answer: http://stackoverflow.com/a/71807684
score: 9
has comment: http://stackoverflow.com/comment/83181714
tagged with: python
accepted answer: http://stackoverflow.com/a/48102959
type: AnsweredQuestion
type: Question
has body: How would I implement the derivative of Leaky ReLU in Python without using Tensorflow? Is there a better way than this? I want the function to return a numpy array def dlrelu(x, alpha=.01): # return alpha if x &lt; 0 else 1 return np.array ([1 if i &gt;= 0 else alpha for i in x]) Thanks in advance for the help
has comment: http://stackoverflow.com/comment/83181777
upvote count: 9
tagged with: neural-network
has comment: http://stackoverflow.com/comment/83181102
has answer: http://stackoverflow.com/a/48102959
answer count: 2

http://stackoverflow.com/comment/83305831
comment on: http://stackoverflow.com/a/48163334
type: AnswerComment
has text: searchbutton = driver.find_element_by_xpath(//button[@value="1" and @label="Search"])
score: 0
type: Comment

http://stackoverflow.com/comment/83151278
type: Comment
type: QuestionComment
has text: Section 4.1 of this article has an example that might be helpful: http://book.pythontips.com/en/latest/map_filter.html
comment on: http://stackoverflow.com/q/48039730
score: 0

http://stackoverflow.com/q/48019297
favorite count: 0
has answer: http://stackoverflow.com/a/48019310
tagged with: python
has body: Assume I have already got the grouped indices lists of a dataframe and I would like to get the sub dataframes using groupby or other functions. I know I can use isin like [df[df.index.isin(group)] for group in grouplist] to query the dataframe several times but it seems to be very slow. How could I get the groups more efficiently? grouplist = [[1],[29, 30, 31],[40],[46, 47, 48, 49],[58, 59],[68, 69, 70],[99, 100, 101],[103]]
score: 2
type: AnsweredQuestion
upvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/48019310
has title: pandas group by a list of group indces
tagged with: pandas
downvote count: 0
answer count: 1

http://stackoverflow.com/q/48070320
answer count: 1
has body: The general idea is: Read a DataFrame from Excel Add a new column where I can identify valid and invalid rows (in this example, values are initialized at None, but I've also tried initializing at False and 0) Iterate through DataFrame and assign values to the new column depending on a series of tests. (unfortunately, the tests are too complex to use applymap or similar) The expected result is to print the DataFrame and see the values of the new column properly assigned. The experienced result is the values have not changed at all. They all remain in their initial value. Here's a highly simplified code sample, where the behavior is present. import pandas as pd df = pd.read_csv('./some_file.csv', sep='\t') print(df) # View outputs below df['Valid'] = [None for _ in range(len(df))] # New column for n in df.iterrows(): if pd.notnull(n[1].Name): # Example test n[1].Valid = False else: # else clause should ensure all values change n[1].Valid = True print(df) # Shows all df.Valid values are still None Output 1 after read_csv() Name Age 0 John 20 1 Mandy 25 2 Mike 30 3 NaN 40 4 Alex 35 Output 2 at the end of the code: Name Age Valid 0 John 20 None 1 Mandy 25 None 2 Mike 30 None 3 NaN 40 None 4 Alex 35 None In the example above, when printing df, all values are still None, even though the debugger shows the process stepping into the assignment statements. Is there some sort of scope, reference, or mutability issue that I'm not seeing? Can anybody explain this behavior? Running python 3.6.0 For a sample data set, I manually built a some_file.csv file separated by tabs with (4th row has an empty string for Name while age is 40, 5th row is skipped by read_csv for obvious reasons): Name Age John 20 Mandy 25 Mike 30 40 Alex 35
has title: Changing boolean value within a DataFrame iterrows does nothing
favorite count: 0
tagged with: pandas
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48070638
accepted answer: http://stackoverflow.com/a/48070638
downvote count: 0
has comment: http://stackoverflow.com/comment/83114897
has comment: http://stackoverflow.com/comment/83114802
type: AnsweredQuestion
score: 1
type: Question
upvote count: 1

http://stackoverflow.com/comment/83201092
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48112656
has text: True. Added an alternative that just uses integer indexing ("writing a C program in Python") but still avoids the necessity for the `not_already_done_` function.
type: AnswerComment

http://stackoverflow.com/comment/83228891
comment on: http://stackoverflow.com/a/48104695
type: Comment
score: 0
type: AnswerComment
has text: Thank you. I’ll try it. I could solve it temporarily by creating new environment but still I don’t have access to some libraries such as rasterio and fiona.

http://stackoverflow.com/q/48046565
linked to: http://stackoverflow.com/q/899103
tagged with: python-3.x
has body: I have a card game that contains a list of cards in a players hand from top to bottom and I need to check up to what point the cards list break from the order of small to large(from top to bottom). I am not able to use any sort of GUI's. For example, cards in players hand: 23 24 12 5-check for the fifth element in the list that is properly sorted 4 3 2 1
has comment: http://stackoverflow.com/comment/83064570
has comment: http://stackoverflow.com/comment/83064904
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83064565
tagged with: python
has comment: http://stackoverflow.com/comment/83064965
score: 2
tagged with: list
upvote count: 2
type: Question
has title: List sorted-Python card game
has comment: http://stackoverflow.com/comment/83064644
has answer: http://stackoverflow.com/a/48046629
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83064549
favorite count: 0

http://stackoverflow.com/q/48126428
score: 3
has body: I'm trying to work with linear functions for data conversion (like meters to feet). I'm trying to find a way to build a lambda function that returns the inverse function and another lambda function that return the composition of those functions inches_to_meters=lambda x:x*0.0254 inches_to_feets=lambda x:x*(1/12) miles_to_feets=lambda x:x*5280 composition=lambda x,y,z: lambda x,y: x(y(z)) opposite=lambda x: 1/x meters_to_inches=opposite(inches_to_meters) miles_to_inches = composition(feets_to_inches, miles_to_feets) print(meters_to_inches(10)) how can I make the opposite function (F^-1(x))? (For example: y=x/12, then 12*y=x, the opposite is: 12*x=y).
tagged with: python
has title: How to make the inverse of a linear function
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48472357
has answer: http://stackoverflow.com/a/48126944
possible better answer: http://stackoverflow.com/a/48170260
has answer: http://stackoverflow.com/a/48170260
answer count: 3
tagged with: lambda
downvote count: 1
upvote count: 4
type: AnsweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/83229570
linked to: http://stackoverflow.com/q/38381556
accepted answer: http://stackoverflow.com/a/48126944
type: Question

http://stackoverflow.com/comment/83002945
has text: Look's like you have a circular import: (`PE_functions.py` imports `main.py` and `main.py` imports `PE_functions.py`).
type: Comment
comment on: http://stackoverflow.com/q/48016771
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83060830
has text: you mean like this: def do_some_task: threading.Thread(target=dosometask)).start()
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48044766
type: Comment

http://stackoverflow.com/comment/83002177
has text: perhaps you meant `request.get()`? Parens are needed because this is a function call.
comment on: http://stackoverflow.com/q/48016441
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83242810
type: Comment
type: QuestionComment
has text: You still need the name parameters, like you had in the original version.
comment on: http://stackoverflow.com/q/48132817
score: 0

http://stackoverflow.com/comment/83239856
has text: if I change true to false i still get negative numbers. why ? @jodag
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48131234
type: Comment

http://stackoverflow.com/comment/83061423
has text: Why do you use 2 variables to store count?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48045155

http://stackoverflow.com/comment/83204000
type: QuestionComment
has text: Instead of `df = pd.read_csv(StringIO(` write `df = pd.read_csv(io.StringIO(`. No need to install anything AFAIK, as the `io` packages is included per default in python
type: Comment
comment on: http://stackoverflow.com/q/48113689
score: 0

http://stackoverflow.com/comment/83307628
type: Comment
comment on: http://stackoverflow.com/a/48150479
has text: Really appreciate your kind help. But data are confidential Jezreal.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83246876
comment on: http://stackoverflow.com/a/48130014
type: AnswerComment
has text: ok you captured those images by yourself but how would you make your rover to get the foreground and background image of the same place? Image subtraction would work for the image frames of the same position only.
score: 0
type: Comment

http://stackoverflow.com/q/48161758
score: 0
has comment: http://stackoverflow.com/comment/83302913
has answer: http://stackoverflow.com/a/48161838
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83303269
has body: I have my data as below: Timestamp Outbound Utilization (%) 11/22/2017 9:55 12.356965 11/22/2017 10:00 14.4424725 11/22/2017 10:05 19.44614625 11/22/2017 10:10 49.3823 11/22/2017 10:15 51.21698 11/22/2017 10:20 50.67409188 11/22/2017 10:25 14.89324375 11/22/2017 10:30 27.1916175 11/22/2017 10:35 19.8268025 11/22/2017 10:40 9.996577813 11/22/2017 10:45 7.929271875 11/22/2017 10:50 22.7705 11/22/2017 10:55 32.611105 11/22/2017 11:00 9.761414375 11/22/2017 11:05 13.10104375 My date column should be rounded up to hourly data, but it should look like 10:05, 11:05, which means all data from 9:05 to 10:05 should be accumulated and shown as 9:05, 10:05 to 11:05 data should be shown as 10:05, something like this, does floor/round function work on this, or do we need to implement our own logic
has title: Rounding up 5-min data to a complicated hourly basis
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48161838
answer count: 1
favorite count: 0
tagged with: datetime
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48064607
has comment: http://stackoverflow.com/comment/83104782
tagged with: excel
has comment: http://stackoverflow.com/comment/83102771
type: Question
has comment: http://stackoverflow.com/comment/83103983
has comment: http://stackoverflow.com/comment/83103461
has comment: http://stackoverflow.com/comment/83105077
has comment: http://stackoverflow.com/comment/83104888
has body: I have written an encryption program that I want to be able to encrypt Excel files with and then decrypt them and output a final Excel file. I have decided to read the whole file then encrypt it as it would be easier than reading each cell from the Excel file. So far I have been able to read the file and convert it to bytes but cannot figure out how to turn it back into an Excel file. root = Tk() root.withdraw() file = filedialog.askopenfile(initialdir="C:")##Creates a file dialog to pick a file tempFile=open(file.name,encoding="Latin-1")##Encodes it with Latin-1 so all 256 bytes can be read file.close() data=tempFile.read() tempFile.close() newFile=open("testfile","w",encoding="cp1252")##Creates a new file with cp1252 encoding as that is what Excel uses newFile.write(data) newFile.close() ##Currently it just fills the Excel file with a whole bunch of random characters Edit: To be more concise, what I want to do is take the data from an Excel file with anything in it, encrypt it, decrypt it and then write it back into a new Excel file with all formatting etc intact. Is there a way to do the reading and writing of the whole file?
has comment: http://stackoverflow.com/comment/83103458
has comment: http://stackoverflow.com/comment/83102449
score: 0
has comment: http://stackoverflow.com/comment/83105044
has title: How do I convert an Excel or similar (not just a plain text file) to bytes or binary then back again
answer count: 1
has answer: http://stackoverflow.com/a/48067240
accepted answer: http://stackoverflow.com/a/48067240
has comment: http://stackoverflow.com/comment/83104817
has comment: http://stackoverflow.com/comment/83103410
tagged with: python
has comment: http://stackoverflow.com/comment/83104885
type: AnsweredQuestion
tagged with: tkinter
tagged with: file

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

http://stackoverflow.com/q/48057577
has answer: http://stackoverflow.com/a/48060469
has body: I want to print the value of intField given by user in maya using python. code import maya.cmds as cmds def fun(number): print(number) cmds.window() cmds.columnLayout() num = cmds.intField(changeCommand = 'fun()') cmds.showWindow() User will enter value in intField and i want to print that value
tagged with: maya
type: UnansweredQuestion
tagged with: python
type: Question
has title: How to print the value of intField in Maya python
has answer: http://stackoverflow.com/a/48084405
score: 0
answer count: 2

http://stackoverflow.com/comment/83222943
comment on: http://stackoverflow.com/q/48122550
score: 0
type: Comment
has text: @EliKorvigo: The overhead is higher because the goal of `set` is fast membership testing, and they're willing to pay memory for it. The actual multiplier vs. `list` is between 3x and 12x in testing, because `set`s only increase in size when the number of entries quadruples (`list`s resize more granularly). You could get lower memory usage (much lower on 3.6) in exchange for slightly slower lookups by using `dict.fromkeys` to make a `dict` where the values are ignored. `getsizeof(dict.fromkeys(words))` is 295008 on 3.6, and 393312 on 3.5. If you have the memory, `O(1)` lookups are worth it.
type: QuestionComment

http://stackoverflow.com/comment/83043698
type: Comment
type: QuestionComment
has text: how about now??? can you understand it now??
comment on: http://stackoverflow.com/q/48036468
score: 0

docker-container
type: Tag
tag name: docker-container
tags question: http://stackoverflow.com/q/48019769

http://stackoverflow.com/q/48064446
accepted answer: http://stackoverflow.com/a/48065031
has body: Hello, My CSV file looks like this: A,B,C,D 12,22000,"3,9","8,5" I want read that with: pd.read_csv('test.csv', sep = ',', decimal=',', quoting=3, engine='python') The result gives a dataframe with the correct first line, but the second is concentrated in the first column. Well it parses the first line but the second is not. I think that quotes are responsible. Do you have an idea? Thank you. Best regards SR
has comment: http://stackoverflow.com/comment/83102126
linked to: http://stackoverflow.com/q/40666589
score: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/48065031
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83102153
has title: How can I parse my CSV file
type: Question

http://stackoverflow.com/a/48090803
downvote count: 0
has comment: http://stackoverflow.com/comment/83156558
has comment: http://stackoverflow.com/comment/83156108
type: Answer
score: 11
upvote count: 11
has comment: http://stackoverflow.com/comment/83156580
accepted answer of: http://stackoverflow.com/q/48090658
has comment: http://stackoverflow.com/comment/83156170
answers question: http://stackoverflow.com/q/48090658
has body: If you have pandas, this is pretty simple. s = pd.Series(['A', 'A', 0, 'B', 0, 'A', np.nan]) s 0 A 1 A 2 0 3 B 4 0 5 A 6 NaN dtype: object Use replace to convert 0 to NaN - s = s.replace({0 : np.nan, '0' : np.nan}) s 0 A 1 A 2 NaN 3 B 4 NaN 5 A 6 NaN dtype: object Now, call pd.get_dummies, which ignores NaN values. pd.get_dummies(s) A B 0 1 0 1 1 0 2 0 0 3 0 1 4 0 0 5 1 0 6 0 0 The solution is the same for a dataframe.
type: AcceptedAnswer

http://stackoverflow.com/comment/83179732
score: 0
type: Comment
has text: @TomSawyer: no, `? :` is a conditional expression. Python's syntax for the same construct is the one I show here. `and` and `or` work the same in many other programming languages as they do in Python, and should not be used for conditional expressions either.
type: AnswerComment
comment on: http://stackoverflow.com/a/48102186

http://stackoverflow.com/q/48069241
has body: The purpose of this code is to predict the future values of forex market for the general currencies. At first, I made a unified data frame, this unified data frame is combination of 11 forex market data sets for the most widely traded currencies plus a group of 900 economic indicators. After combining these 911 data sets in the unified data frame with no problems of any sort after being tested, I begun the LSTM neural network which I also tested with just single data set and it works great. The problem begins when I combined the unified data frame with the LSTM neural network. Here is the code: import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential import os os.chdir("E:\Business\Stocks") path = os.listdir("E:\Business\Stocks") for file in path: name, ext = os.path.splitext(str(file)) column_names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume'] df1 = pd.read_csv(file, names=column_names, parse_dates={'DateTime': ['Date', 'Time']}, index_col=[0]) df1 = df1.rename(columns={'Open': name + ' ' + 'Open', 'High': name + ' ' + 'High', 'Low': name + ' ' + 'Low', 'Close': name + ' ' + 'Close', 'Volume': name + ' ' + 'Volume'}) os.chdir("E:\Business\Economic Indicators") path = os.listdir("E:\Business\Economic Indicators") for file in path: df2 = pd.read_csv(file, index_col=[0], parse_dates=[0]) name, ext1 = os.path.splitext(file) df2 = df2.rename(columns={'Actual': name + ' ' + 'Actual', 'Consensus': name + ' ' + 'Consensus', 'Previous': name + ' ' + 'Previous', 'Revised': name + ' ' + 'Revised'}) dfs = [df1 ,df2] df = pd.concat(dfs, axis=1, join='inner').sort_index(ascending=False) df.fillna(method='ffill', inplace=True) sequence_length = 120 n_features = len(df.columns) val_ratio = 0.1 n_epochs = 3000 batch_size = 500 data = df.as_matrix() data_processed = [] for inde…
tagged with: python
has title: python LSTM too many indices for array
score: 2
has answer: http://stackoverflow.com/a/48069359
upvote count: 2
type: UnansweredQuestion
tagged with: tensorflow
tagged with: anaconda
tagged with: lstm
type: Question
answer count: 1
downvote count: 0
tagged with: neural-network
linked to: http://stackoverflow.com/q/509211
favorite count: 0

http://stackoverflow.com/a/48107969
type: Answer
upvote count: 4
downvote count: 0
score: 4
type: AcceptedAnswer
has body: What i would advise is to create a view that serves the image (a simple API). app = Flask(__name__, upload_folder='upload') @app.route('/img/&lt;path:filename&gt;') def send_file(filename): return send_from_directory(app.upload_folder, filename) This should get the job done, but you can check this question for more.
accepted answer of: http://stackoverflow.com/q/48107708
answers question: http://stackoverflow.com/q/48107708

http://stackoverflow.com/comment/83053354
type: Comment
comment on: http://stackoverflow.com/a/48041329
has text: I realised that the docs did not mention that you can create a dataframe from a list.
type: AnswerComment
score: 0

http://stackoverflow.com/a/48058458
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/48057744
has body: The issue could not be replicated. Here is my full code: #!/usr/bin/env python import multiprocessing N = 4 mydata=[[x+1,x+2,x+3,x+4] for x in range(0,4000*N,4)] # fake some data def data_write_func(mydata, i, block_size=1000): fout = open('data_part_'+str(i), 'w') data_part = mydata[block_size*i: block_size*i+block_size] for line in data_part: # do some processing, say *2 for each element... line = [x*2 for x in line] # then write out.. fout.write(','.join(map(str,line))+'\n') fout.close() pool = multiprocessing.Pool(processes=N) for i in range(2): pool.apply_async(data_write_func, (mydata, i, )) pool.close() pool.join() Sample output from data_part_0: 2,4,6,8 10,12,14,16 18,20,22,24 26,28,30,32 34,36,38,40 42,44,46,48 50,52,54,56 58,60,62,64
has comment: http://stackoverflow.com/comment/83131029
type: Answer
score: 2

http://stackoverflow.com/q/48132282
answer count: 1
has comment: http://stackoverflow.com/comment/83256051
has comment: http://stackoverflow.com/comment/83242308
tagged with: python-multithreading
has answer: http://stackoverflow.com/a/48140664
type: UnansweredQuestion
tagged with: python
has title: Tkinter images glitch when placed in different thread
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83242161
score: 0
has body: So i'm trying to make a gui and make images appear on the gui, but when I place an image onto the gui it starts flashing depending on where I drag the gui on my computer... Heres code that causes this effect: from tkinter import * from threading import * root = Tk() root.resizable(False, False) image1 = PhotoImage(file="GUI.png") w = image1.width() h = image1.height() root.geometry("%dx%d+0+0" % (w, h)) panel1 = Label(root, image=image1) panel1.pack(side='top', fill='both', expand='yes') def PlaceImage(): global panel1 test = PhotoImage(file="test.png") label = Label(panel1, image=test) label.image = test label.place(x=0, y=0) def thethread(): PlaceImage() thread = Thread(target=thethread) thread.start() root.mainloop() The gui comes out just fine, but the image I place is what is glitchy. If anyone knows why this is and how to fix it that would be very helpful!
type: Question
tagged with: image
has comment: http://stackoverflow.com/comment/83242358

http://stackoverflow.com/comment/83126211
score: 0
type: QuestionComment
has text: What would you expect to happen? None of the first elements in `full` are in `skip_interfaces`...
type: Comment
comment on: http://stackoverflow.com/q/48076228

http://stackoverflow.com/comment/83178899
type: QuestionComment
comment on: http://stackoverflow.com/q/48101662
has text: I get this error when I implement in print statements: SyntaxError: Missing parentheses in call to 'print'. Did you mean print(print item). This makes me think that I'm running the spider from the wrong directory/environment. Should I be in the scrapy shell when I'm running this? The impression I get from the tutorial is that I should just be able to run this from the ourfirstspider folder and that is what I have been doing.
score: 0
type: Comment

http://stackoverflow.com/q/48042177
has answer: http://stackoverflow.com/a/48053264
type: Question
answer count: 2
upvote count: 0
has body: I am a "tech guy" who wishes to learn about home automation (with HomeAssistant.io). There is something I don't understand yet. I have seen tutorials about how to make my own home own automation Etc. In all of the tutorials I saw a lot of cables crambeling [??what??] to only switch on a simple light (while the Arduino is connected directly to the light and the Arduino connected with an Ethernet cable to the internet and the light turned on by an Android app). If I want to do a real home automation I don't want to connect every light in my house with a wire to the Arduino (sounds like a crappy home automation). I understand that there is something called ESP8266, this is a wireless chip. My questions: How to connect the ESP8266 to a light in my house without direct (wire) connection to Arduino? How to program it? Assuming that I will connect the Arduino/Raspberry directly with a wire to the router and my home devices will be without any cables going around the house like a caveman. In your answer please give some good tutorials.
has comment: http://stackoverflow.com/comment/83059261
has title: Do I need Arduino/Raspberry for every light in my house?
tagged with: esp8266
has answer: http://stackoverflow.com/a/49219532
accepted answer: http://stackoverflow.com/a/48053264
favorite count: 0
has comment: http://stackoverflow.com/comment/83055029
possible better answer: http://stackoverflow.com/a/49219532
tagged with: android
score: -3
tagged with: python
tagged with: home-automation
type: AnsweredQuestion
tagged with: arduino
downvote count: 3

http://stackoverflow.com/comment/83071494
type: Comment
type: QuestionComment
has text: Please update your question to give the xpath or css selector you tried, so that we can look into they are correct or not. (You can simply to try them in DevTool, no need to execute script again and again)
comment on: http://stackoverflow.com/q/48048663
score: 0

http://stackoverflow.com/comment/83037041
score: 0
type: QuestionComment
type: Comment
has text: you can also use module `subprocess` to run any program.
comment on: http://stackoverflow.com/q/48033369

http://stackoverflow.com/a/48080621
answers question: http://stackoverflow.com/q/48080359
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83169349
type: AcceptedAnswer
downvote count: 0
has body: pandas is a good one, but you can just use max and lambda: men = max(data, key=lambda x: x[1] if x[0] == 'men' else 0) women = max(data, key=lambda x: x[1] if x[0] == 'women' else 0) people = max(data, key=lambda x: x[1] if x[0] == 'people' else 0)
accepted answer of: http://stackoverflow.com/q/48080359
type: Answer

http://stackoverflow.com/q/48146970
has title: Python install error "A newer version of the Python launcher is already installed"
has answer: http://stackoverflow.com/a/70464698
downvote count: 0
has answer: http://stackoverflow.com/a/70681323
has answer: http://stackoverflow.com/a/76022266
favorite count: 0
type: Question
has body: I am trying to reinstall Python, so I go control panel &gt; uninstall &gt; Python 3.6.2. It succeeds, but when I try to download 3.6.*, it says that I can't download because there is already a version of Python3 installed. I tried to clean the registry, deleted all files named "Python", but still see the error. I even deleted the path Python in PATH.
has answer: http://stackoverflow.com/a/55002482
tagged with: python
has answer: http://stackoverflow.com/a/68255624
score: 17
has answer: http://stackoverflow.com/a/56264509
answer count: 11
has answer: http://stackoverflow.com/a/48147074
has answer: http://stackoverflow.com/a/73640282
upvote count: 17
has answer: http://stackoverflow.com/a/64157803
has comment: http://stackoverflow.com/comment/124951407
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83272133
has answer: http://stackoverflow.com/a/77062328
has answer: http://stackoverflow.com/a/77673610

http://stackoverflow.com/comment/83220677
type: Comment
type: QuestionComment
has text: [scipy.misc.imresize](https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html)
score: 1
comment on: http://stackoverflow.com/q/48121916

http://stackoverflow.com/a/48089521
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83222929
has body: Check whether the current row is "Monday" when the previous row is "Sunday" to generate a boolean mask. Then, perform a cumsum on the result. df['WeekCounter'] = (df.DayofWeek.eq('Monday') &amp; df.DayofWeek.shift().eq('Sunday')).cumsum() + 1 df WeekCounter DayofWeek 0 1 Monday 1 1 Monday 2 1 Tuesday 3 1 Sunday 4 2 Monday 5 2 Wednesday 6 2 Thursday 7 2 Sunday 8 3 Monday 9 3 Monday 10 3 Monday
has comment: http://stackoverflow.com/comment/83153546
type: Answer
accepted answer of: http://stackoverflow.com/q/48087700
upvote count: 3
answers question: http://stackoverflow.com/q/48087700

http://stackoverflow.com/q/48035079
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/86426146
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/21159103
has title: asyncio with multiple processors
upvote count: 5
tagged with: async-await
has body: I notice that asyncio doesn't run coroutines on separate processors. For example, if I run the following program with Python 3.6.3, then it uses one of my four cores for 15 seconds, instead of three cores for 5 seconds each. import asyncio async def myfn(n): s = 0 for x in range(int(n)): s += x print(s) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait( [myfn(x) for x in (1e8 + 1, 1e8 + 2, 1e8 + 3)])) Is there a way to use asyncio, async, or await that exploits multiple processors for processor-bound tasks?
tagged with: multiprocessing
type: Question
score: 5
duplicate of: http://stackoverflow.com/q/21159103
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/48027879
answers question: http://stackoverflow.com/q/48019013
has body: okay it was obvious I hadn't closed the files. from PyPDF2 import PdfFileReader, PdfFileMerger import pandas as pd def create_pdf(x): file2 = outs[x] file1 = certs[x] input1 = open(path + file1, "rb") input2 = open(path + 'insert.pdf', "rb") output = open(path2 + file2, "wb") merger.append(fileobj=input1, pages=(0, 1), import_bookmarks=False) merger.append(input2) merger.write(output) output.close() # *****Solution close the input files****** input1.close() input2.close() return df = pd.read_csv('Affiliate Data.csv', encoding='latin1', na_values=['nan'], keep_default_na=False) path = 'D:\\input_file Location\\' path2 = 'D:\\Output_file_Location\\' merger = PdfFileMerger() pdf_files = [] certs = df['infile'].tolist() outs= df['outfile'].tolist() x=0 while x &lt; 605 : create_pdf(x) # *****Solution close and reopen the file merger****** merger.close() merger = PdfFileMerger() x=x+1 Hat tip to my father for pointing out the obvious flaw. I wasn't looking forward to doing all these manually. J
score: 0
type: Answer

http://stackoverflow.com/q/48048577
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48048693
type: AnsweredQuestion
tagged with: group-by
tagged with: http://stackoverflow.com/tag/json
tagged with: dataframe
has title: Formatting dataframe output into JSON records by group
type: Question
has comment: http://stackoverflow.com/comment/83068855
accepted answer: http://stackoverflow.com/a/48048693
score: 0
has comment: http://stackoverflow.com/comment/83068738
tagged with: pandas
answer count: 1
has body: my dataframe looks like this df: count_arena_users count_users event timestamp 0 4458 12499 football 2017-04-30 1 2706 4605 cricket 2015-06-30 2 592 4176 tennis 2016-06-30 3 3427 10126 badminton 2017-05-31 4 717 2313 football 2016-03-31 5 101 155 hockey 2016-01-31 6 45923 191180 tennis 2015-12-31 7 1208 2824 badminton 2017-01-31 8 5577 8906 cricket 2016-02-29 9 111 205 football 2016-03-31 10 4 8 hockey 2017-09-30 the data is fetched from a psql database, Now i want to generate the output of "select * from tbl_arena" in json format. But the json format that is desired has to be something like this: [ { "event": "football", "data_to_plot": [ { "count_arena_users": 717, "count_users": 2313, "timestamp": "2016-03-31" }, { "count_arena_users": 111, "count_users": 205, "timestamp": "2016-03-31" }, { "count_arena_users": 4458, "count_users": 12499, "timestamp": "2017-04-30" } ] }, { "event": "cricket", "data_to_plot": [ { "count_arena_users": 2706, "count_users": 4605, "timestamp": "2015-06-30" }, { "count_arena_users": 5577, "count_users": 8906, "timestamp": "2016-02-29" } ] } . . . . ] the values of all the columns are grouped based on the event column and later their occurance order of sub-dictionaries is decided based on timestamp column i.e. earlier dates appearing first and newer/latest dates appearing below it. I'm using python 3.x and json.dumps to format the data into json style.
favorite count: 0
has comment: http://stackoverflow.com/comment/83068715
upvote count: 2

http://stackoverflow.com/comment/83302238
type: QuestionComment
comment on: http://stackoverflow.com/q/48161175
score: 0
type: Comment
has text: I am unclear what you are asking for. A class attribute does not do what you need? If not, why not?

sql
tags question: http://stackoverflow.com/q/48015632
tags question: http://stackoverflow.com/q/48119528
tags question: http://stackoverflow.com/q/48129540
tags question: http://stackoverflow.com/q/48056858
tags question: http://stackoverflow.com/q/48077287
tags question: http://stackoverflow.com/q/48083401
tags question: http://stackoverflow.com/q/48069177
tags question: http://stackoverflow.com/q/48103964
tags question: http://stackoverflow.com/q/48042341
tags question: http://stackoverflow.com/q/48061510
tag name: sql
type: Tag
tags question: http://stackoverflow.com/q/48153689
tags question: http://stackoverflow.com/q/48156213
tags question: http://stackoverflow.com/q/48162626
tags question: http://stackoverflow.com/q/48081036
tags question: http://stackoverflow.com/q/48015114
tags question: http://stackoverflow.com/q/48112036
tags question: http://stackoverflow.com/q/48173147
tags question: http://stackoverflow.com/q/48065753
tags question: http://stackoverflow.com/q/48028823
tags question: http://stackoverflow.com/q/48171611
tags question: http://stackoverflow.com/q/48052576
tags question: http://stackoverflow.com/q/48087117
tags question: http://stackoverflow.com/q/48065834
tags question: http://stackoverflow.com/q/48088750
tags question: http://stackoverflow.com/q/48054586
tags question: http://stackoverflow.com/q/48164751
tags question: http://stackoverflow.com/q/48055348
tags question: http://stackoverflow.com/q/48154573
tags question: http://stackoverflow.com/q/48026805

css
tags question: http://stackoverflow.com/q/48098278
tags question: http://stackoverflow.com/q/48081783
tags question: http://stackoverflow.com/q/48143581
tags question: http://stackoverflow.com/q/48015950
tags question: http://stackoverflow.com/q/48036198
tags question: http://stackoverflow.com/q/48102099
type: Tag
tags question: http://stackoverflow.com/q/48068247
tags question: http://stackoverflow.com/q/48023363
tags question: http://stackoverflow.com/q/48123895
tag name: css
tags question: http://stackoverflow.com/q/48040412
tags question: http://stackoverflow.com/q/48067768

http://stackoverflow.com/comment/83106818
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48066606
has text: @PM2Ring exactly

http://stackoverflow.com/comment/83166626
has text: I am not sure if there exists int64 in native python. Maybe you want to use numpy??
comment on: http://stackoverflow.com/q/48095890
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48045741
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48045712
has comment: http://stackoverflow.com/comment/83063996
has body: If you move the button.check() call to the event loop, it gets called only once per mouse click instead of every frame. while not done: for event in pygame.event.get(): if event.type == QUIT: terminate() elif event.type == pygame.MOUSEBUTTONDOWN: if button.check(): money += 1 I also recommend using a pygame.Rect in the Button class, then you can simply call the pygame.Rect.collidepoint method to see if the mouse collides with the button. class Button(object): def __init__(self,x,y,width,height,color): self.rect = pygame.Rect(x,y,width,height) self.image=pygame.draw.rect(screen, color,(self.rect),) self.x=x self.y=y self.width=width self.height=height def check(self): return self.rect.collidepoint(pygame.mouse.get_pos()) pygame.mouse.get_pressed() can be problematic if you want to use it with buttons, because it only checks if a mouse button is held down and not if it was just clicked once.
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/48045712

http://stackoverflow.com/q/48087184
has answer: http://stackoverflow.com/a/48087241
has answer: http://stackoverflow.com/a/48087287
tagged with: python
tagged with: dictionary
has body: I am new to Python and Stackoverflow in general, so sorry if my formatting sucks. But I created this dictionary and assigned it keys and values contained inside of lists. Here is what my code currently looks like: favorite_languages = { 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edward': ['ruby', 'go'], 'phil': ['python', 'haskell'], } for name, languages in favorite_languages.items(): for language in languages: if len(languages) &gt;= 2: print("\n" + name.title() + "'s favorite languages are:" + language.title()) elif len(languages) == 1: print(name.title() + "'s favorite language is: " + language.title()) The result of the code when ran comes out looking like this: Sarah's favorite language is: C Edward's favorite languages are:Ruby Edward's favorite languages are:Go Jen's favorite languages are:Python Jen's favorite languages are:Ruby Phil's favorite languages are:Python Phil's favorite languages are:Haskell But I only want it to repeat the sentence once for each key, while containing the corresponding values within each sentence. Like this: Sarah's favorite language is: C Edward's favorite languages are:Ruby, Go Jen's favorite languages are:Python, Ruby Phil's favorite languages are:Python, Haskell
tagged with: python-3.x
tagged with: list
accepted answer: http://stackoverflow.com/a/48087287
score: 0
type: AnsweredQuestion
has title: Using a for loop to print dictionary items once without repeating the print function for each item listed
type: Question
possible better answer: http://stackoverflow.com/a/48087241
answer count: 2
tagged with: printing

http://stackoverflow.com/q/48090617
downvote count: 0
tagged with: bokeh
type: Question
score: 3
upvote count: 3
answer count: 1
has title: How to plot candlestick hourly with bokeh?
has answer: http://stackoverflow.com/a/61307174
has body: I have try to plot the candlestick chart. From above figure you will see that the x-axis is sequences of data, I just want to replace it by use date from df['date'] I try to use df['date'] instead df['seq'] but it doesn't work because time format. How should i solve it? Here is my code: import pandas import datetime import random import numpy from bokeh.models import ColumnDataSource from bokeh.models.tools import * from bokeh.plotting import figure from bokeh.io import gridplot, show lenght = 20 df = pandas.DataFrame() date = [] for i in range(1,5): for j in range(10,15): date.append(datetime.datetime(2018, 1, i, j, 0)) df['date'] = pandas.to_datetime(date).strftime('%Y-%m-%d %H:%M') df['open'] = [random.randint(40,50) for p in range(lenght)] df['high'] = [random.randint(40,50) for p in range(lenght)] df['low'] = [random.randint(40,50) for p in range(lenght)] df['close'] = [random.randint(40,50) for p in range(lenght)] df['rsi'] = [random.randint(0,100) for p in range(lenght)] seqs=numpy.arange(df.shape[0]) df["seq"]=pandas.Series(seqs) df['mid']=df.apply(lambda x:(x['open']+x['close'])/2,axis=1) df['height']=df.apply(lambda x:abs(x['close']-x['open'] if x['close']!=x['open'] else 0.001),axis=1) df["seq"] = df['date'] inc = df.close &gt; df.open dec = df.open &gt; df.close w=0.3 #use ColumnDataSource to pass in data for tooltips sourceInc=ColumnDataSource(ColumnDataSource.from_df(df.loc[inc])) sourceDec=ColumnDataSource(ColumnDataSource.from_df(df.loc[dec])) #the values for the tooltip come from ColumnDataSource hover = HoverTool( tooltips=[ ("date", "@date"), ("close", "@close"), ] ) TOOLS = [CrosshairTool(), hover, BoxZoomTool(), WheelZoomTool()] ohlc = figure(plot_width=1000, plot_height=500, tools=TOOLS, x_axis_type='datetime') ohlc.grid.grid_line_alpha=0.3 ohlc.segment(df.seq[inc], df.high[inc], df.seq[inc], df.low[inc], color="red") ohlc.segment(df.seq[dec], df.high[dec], df.seq[dec], df.low[dec], color="green") ohlc.rect(x='date', y='mid', width=w, height='h…
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48132675
tagged with: python
tagged with: pygame
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/83242466
type: Question
has body: So I'm trying to write some code that has a list of enemies, then deletes the enemy if they go off screen. the code is as follows: for enemy in enemies: index = 0 enemy[0] += 2 if enemy[1] &gt;= 270: enemy[2] = -2 else: enemy[2] = enemy[2] + 0.01 enemy[1] = enemy[1] + enemy[2] screen.blit(enemyImg, (enemy[0],enemy[1]) if enemy[0] &gt; 470: enemies.remove(index) index += 1 I'm using a for loop which is why it has "enemy" as a a list but it's deleting the item in the list "enemies" The information stored in "enemy" is a list that has the x-value (index 0), y-value (index 1), and the y velocity (index 2). The enemies don't have a x velocity since they move at a constant rate to the right. The error says that there is invalid syntax (that's literally all it says), but I don't see a problem. Maybe I'm just missing something stupid, but I'm not sure. Thank you for any help you can give.
has comment: http://stackoverflow.com/comment/83242409
upvote count: 0
downvote count: 5
possible better answer: http://stackoverflow.com/a/48134738
has title: Using an "if" to delete an item from a list gives a syntax error
answer count: 2
accepted answer: http://stackoverflow.com/a/48132743
has answer: http://stackoverflow.com/a/48134738
has comment: http://stackoverflow.com/comment/83242485
favorite count: 0
has answer: http://stackoverflow.com/a/48132743
has comment: http://stackoverflow.com/comment/83242426

http://stackoverflow.com/comment/83159670
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48088691
has text: That only makes me get the first item recognized `un : CAT: Det , Genre: M , Nombre: Sg` but `garçon : CAT: N , Genre: M , Nombre: Sg` is not there, and I need them both!
type: AnswerComment

http://stackoverflow.com/comment/83164268
type: Comment
type: QuestionComment
has text: I can't think of any nicer way. In any case, you may want to take this question to https://codereview.stackexchange.com
score: 0
comment on: http://stackoverflow.com/q/48094725

http://stackoverflow.com/q/48082893
has comment: http://stackoverflow.com/comment/83140685
has answer: http://stackoverflow.com/a/48083131
type: Question
accepted answer: http://stackoverflow.com/a/48083131
tagged with: oop
score: 9
has answer: http://stackoverflow.com/a/48083066
has comment: http://stackoverflow.com/comment/83140708
linked to: http://stackoverflow.com/q/3277367
tagged with: inheritance
favorite count: 0
has comment: http://stackoverflow.com/comment/83140927
upvote count: 9
answer count: 5
possible better answer: http://stackoverflow.com/a/48083116
has answer: http://stackoverflow.com/a/48083069
has body: Hello awesome community, I was learning the OOPS concepts with python as a part of my curriculum. I am having a problem with multiple inheritance in python. The following is my code: #!/usr/bin/env python class Base1(object): def __init__(self): self.base1var = "this is base1" class Base2(object): def __init__(self): self.base2var = "this is base2" class MainClass(Base1, Base2): def __init__(self): super(MainClass, self).__init__() if __name__ == "__main__": a = MainClass() print a.base1var print a.base2var and when running, I am getting the following error print a.base2var AttributeError: 'MainClass' object has no attribute 'base2var' If I swap the order of classes inherited, the variable name in the error changes accordingly. Am I using super() wrong when I want to call the constructors of the two inherited classes? How can I correctly inherit from multiple base classes and use the variables and methods in the main class without this error? Thank you.
tagged with: python
has answer: http://stackoverflow.com/a/48083116
linked to: http://stackoverflow.com/q/24564908
type: AnsweredQuestion
downvote count: 0
has title: Python multiple inheritance is not showing class variables or method of second inherited base class
has answer: http://stackoverflow.com/a/48083046

http://stackoverflow.com/comment/83398613
type: Comment
type: QuestionComment
has text: @AriKanevsky, beware that if you go this route, you actually need 25 values because there is also following clause "`or t = −1 if x = y = 0`". And as for iterating, I believe that Python has a [dict](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) and tuple can be a key. So using it will probably be more efficient. On the other hand, beware that efficiency might sometimes be a bad thing for good cryptography because it might open the door to [timing attacks](https://en.wikipedia.org/wiki/Timing_attack). I haven't study the algorithm to know if this is such a place.
comment on: http://stackoverflow.com/q/48160974
score: 0

http://stackoverflow.com/comment/102472226
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48050072
has text: *"second issue is if i give a word 'Dog' can i get words like 'Puppy','Kitty','Dog','dog' etc ?"* essentially how to get a list of most similar words, provided the initial word as input - the question as per title.

http://stackoverflow.com/comment/102797855
comment on: http://stackoverflow.com/a/48028333
has text: Could you please clarify which is the modulus to be used in http://www-cs-students.stanford.edu/~tjw/jsbn/rsa.html online tool, based on the above PyCrypto example?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48061444
accepted answer of: http://stackoverflow.com/q/48061280
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Let's reduce this to a MCVE: signature = [1, 1, 1] count = 0 while True: newitem = signature[count] + signature[count+1] + signature[count+2] count = count+1 On the first iteration, count is 0 so the "problem" line will effectiveley be: newitem = signature[0] + signature[1] + signature[2] since signature is a 3 items list, this is ok. Now on the second iteration, count is 1 so this line will effectively become: newitem = signature[1] + signature[2] + signature[3] Since signature is only 3 items long, there's no signature[3] object - your Index is OutOfRange.
upvote count: 2
answers question: http://stackoverflow.com/q/48061280
score: 2

http://stackoverflow.com/a/48083629
has comment: http://stackoverflow.com/comment/83142959
has comment: http://stackoverflow.com/comment/83142731
type: Answer
has comment: http://stackoverflow.com/comment/83142928
score: 2
has comment: http://stackoverflow.com/comment/83142223
type: AcceptedAnswer
has body: In your class definitions you write things like: class TeacherDetails(models.Model): teachers = models.ForeignKey(Teachers, on_delete=models.CASCADE) present_address = models.TextField # call missing permanent_address = models.TextField # call missing teacher_phone = models.BigIntegerField # call missing gpo_box_number = models.IntegerField # call missing So the call to the constructor is missing. You did not associate present_address with a TextField instance, you associated it with the TextField type instead. You need to cll the constructor, so: class TeacherDetails(models.Model): teachers = models.ForeignKey(Teachers, on_delete=models.CASCADE) present_address = models.TextField() # call to constructor permanent_address = models.TextField() # call to constructor teacher_phone = models.BigIntegerField() # call to constructor gpo_box_number = models.IntegerField() # call to constructor Django will look for attributes associated with Model subclasses that are instances of a Field (not references to a (sub)class of Field). These are then mapped to columns in databases.
accepted answer of: http://stackoverflow.com/q/48083587
downvote count: 0
answers question: http://stackoverflow.com/q/48083587
has comment: http://stackoverflow.com/comment/83142715
upvote count: 2
has comment: http://stackoverflow.com/comment/83142282

http://stackoverflow.com/q/48042187
tagged with: python
score: -2
has body: I want to convert a sting like this: input_str = "send_message" to unique integer between 0 to 255 and also when I decode my unique integer, this returned to the same string "send_message". How to do this converting and should I save unique integers into a json file?
tagged with: unique
tagged with: integer
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48042242
downvote count: 2
answer count: 3
has title: how to convert a string into unique integer and vice versa (between 0 to 255) in python3.6
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48042359
upvote count: 0
has comment: http://stackoverflow.com/comment/83055139
tagged with: string
has answer: http://stackoverflow.com/a/48042289
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/83055203

http://stackoverflow.com/a/48016377
downvote count: 0
answers question: http://stackoverflow.com/q/48016284
score: 1
has body: You can declare the name and tag functions above the function to be decorated and pass as parameters to the outer decorator: def decoration(func1, func2): def wrapper(f1): def inner_function(content, tag, content_decoration=None, tag_decoration=None): return '&lt;{1}&gt; {0} &lt;/{1}&gt;'.format(func1(content, content_decoration ), func2(tag, tag_decoration)) return inner_function return wrapper def name_decoration(con, con_decor): return '{0} {1}'.format(con, con_decor) def tag_decoration(tag, tag_decor): return '{0} {1}'.format(tag, tag_decor) @decoration(name_decoration, tag_decoration) def get_html(content, tag, content_decoration=None, tag_decoration=None): return print(get_html(content='Alice', tag='h1', tag_decoration='fontsize=12', content_decoration='')) print(get_html(content='Bob', content_decoration='Smith', tag='p')) Output: &lt;h1 fontsize=12&gt; Alice &lt;/h1 fontsize=12&gt; &lt;p None&gt; Bob Smith &lt;/p None&gt; Or, you can use lambda functions to save space: @decoration(lambda con, con_decor:'{0} {1}'.format(con, con_decor), lambda tag, tag_decor:'{0} {1}'.format(tag, tag_decor)) def get_html(content, tag, content_decoration=None, tag_decoration=None): return
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48016284

http://stackoverflow.com/comment/83004892
type: Comment
score: 0
has text: It is up to you.
comment on: http://stackoverflow.com/a/48017926
type: AnswerComment

http://stackoverflow.com/q/48016090
has answer: http://stackoverflow.com/a/48024622
accepted answer: http://stackoverflow.com/a/48024622
tagged with: python
tagged with: kivy
upvote count: 2
has comment: http://stackoverflow.com/comment/83003950
answer count: 1
has body: I have a kivy label bound to a StringProperty(). I'm trying to get the string out of it in Python. class Screen1(Screen): food_label = StringProperty() def print_label(self): print(Screen1.food_label) It returns this: &lt;StringProperty name=food_label&gt; I set the property on the previous screen using this statement in a def: self.manager.get_screen('screen_1').food_label = food Where 'food' is a String. On the screen the label text is displayed correctly. How can I print the actual string contained in the StringProperty().
has comment: http://stackoverflow.com/comment/83001892
has comment: http://stackoverflow.com/comment/83001626
type: AnsweredQuestion
score: 2
downvote count: 0
has title: How to get the string out of a StringProperty in Python
favorite count: 0
type: Question

http://stackoverflow.com/comment/83089068
type: Comment
has text: @AntonvBR Yeah but it must also be included in it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48058301

http://stackoverflow.com/q/48033099
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/83041357
type: UnansweredQuestion
tagged with: elasticsearch
tagged with: python
has title: nested type mapping in elasticsearch with python
tagged with: mapping
answer count: 0
has comment: http://stackoverflow.com/comment/83041235
score: 1
upvote count: 1
type: Question
has body: I am trying to map elasticsearch index, but I keep getting an error with nested type. request_body = { "setting": { "number_of_shards": 3, "number_of_replicas": 1 }, "mappings": { "examplecase": { "properties": { "id": {"index": "not_analyzed", "type": "string"}, "source": {"index": "analyzed", "type": "string"}, "categories": {"index": "analyzed", "type": "string"}, "source_link": {"index": "analyzed", "type": "string"}, "article_name": {"index": "analyzed", "type": "string"}, "text": {"index": "analyzed", "type": "string"}, "date": {"index": "analyzed", "type": "string"}, "article_text": {"type": "nested", "properties": {"text": {"type": "string"}, "paragraph_name": {"type": "string"}} }, "language": {"index": "analyzed", "type": "string"} } } } } es.indices.create(index="articles", body=request_body) and I keep getting this error: 'illegal_argument_exception', "object mapping [article_text] can't be changed from nested to non-nested") All the mapping looks like in the elasticsearch documentation, I do not know whats wrong. Does anyone have any ideas ?
has comment: http://stackoverflow.com/comment/83041109

http://stackoverflow.com/comment/83232277
comment on: http://stackoverflow.com/q/48127782
has text: `firstarg=sys.argv[0].strip()` : You compare rootpath of the script against a integer... euhm...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48151022
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48150992
type: AcceptedAnswer
downvote count: 0
has body: Use a nested loop: for i in range(1, 5): for j in range(4): print '{}:{}'.format(i, j) 1:0 1:1 1:2 1:3 2:0 2:1 2:2 2:3 3:0 3:1 3:2 3:3 4:0 4:1 4:2 4:3
accepted answer of: http://stackoverflow.com/q/48150992
type: Answer

http://stackoverflow.com/comment/83172281
has text: And also in that light you don't need the manual `values()` call that just "fixes" bind params (compared to literal values or SQL expressions), as SQLAlchemy does that for you automatically.
comment on: http://stackoverflow.com/a/48096975
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/83151869
score: 0
comment on: http://stackoverflow.com/q/48078820
type: Comment
type: QuestionComment
has text: @JohnAnderson hello, its mean when i add row in scrollview that row having extra space in scrollview i want add rows in gridlist without any spacing.

http://stackoverflow.com/comment/83317335
has text: Thanks for the comment. I have not come across any indentation issues yet, so this was new to me.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48168892
type: QuestionComment

http://stackoverflow.com/comment/83183876
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48104001
score: 0
has text: I couldn't reproduce: https://imgur.com/a/j2Y6t

http://stackoverflow.com/q/48019524
type: Question
answer count: 2
has title: Converting a JSON file to pyspark dataframe and then to RDD
upvote count: 0
linked to: http://stackoverflow.com/q/32111835
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/48019613
tagged with: rdd
favorite count: 0
type: UnansweredQuestion
downvote count: 1
has answer: http://stackoverflow.com/a/48024224
has body: I have a json file with the below format which i converted to pyspark Dataframe. Converted dataframe is as below. Below is the tweets data frame: +-------------+--------------------+-------------------+ | tweet_id| tweet| user| +-------------+--------------------+-------------------+ |1112223445455|@xxx_yyyzdfgf @Yoko | user_1| |1112223445456|sample test tweet | user_2| |1112223445457|test mention @xxx_y | user_1| |1112223445458|testing @yyyyy | user_3| |1112223445459|@xxx_yyzdfgdd @frnd | user_4| +-------------+--------------------+-------------------+ I am now trying to extract all the mentions (words that start with an "@") from the column - tweet. I did it by converting it into an RDD and splitting all the lines using the below code. tweets_rdd = tweets_df.select("tweet").rdd.flatMap(list) tweets_rdd_split=tweets_rdd.flatMap(lambda text:text.split(" ")).filter(lambda word:word.startswith('@')).map(lambda x:x.split('@')[1]) Now my output is in below format. [u'xxx_yyyzdfgf', u'Yoko', u'xxx_y', u'yyyyy', u'xxx_yyzdfgdd', u'frnd'] Every row has the mentions within u' '. I think its appearing because the initial file is a json file. I tried removing it using functions like split and replace. But its not working. Could someone help me with removing these? Is there a better approach than this to extract the mentions?
tagged with: http://stackoverflow.com/tag/json
tagged with: dataframe
score: -1

http://stackoverflow.com/q/48014712
accepted answer: http://stackoverflow.com/a/48016650
score: 1
has comment: http://stackoverflow.com/comment/83000830
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82999850
tagged with: normal-distribution
type: AnsweredQuestion
upvote count: 1
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83001891
has body: I am given the log10 mean and log10 standard deviation of a log-normal distribution. I want to get a random number from this log-normal distribution. Can this be accomplished with numpy.random.lognormal, even though that function's inputs are the mean and standard of the underlying normal distribution (I do not have that)? Also, will the random number that I get back from the function be log10, natural log, or regular?
tagged with: logarithm
has answer: http://stackoverflow.com/a/48016650
has title: Get lognormal random number given log10 mean and log10 standard deviation
answer count: 1
downvote count: 0

http://stackoverflow.com/a/48070598
downvote count: 0
has comment: http://stackoverflow.com/comment/83115392
upvote count: 1
has comment: http://stackoverflow.com/comment/83115320
type: Answer
has comment: http://stackoverflow.com/comment/83115643
accepted answer of: http://stackoverflow.com/q/48070373
score: 1
answers question: http://stackoverflow.com/q/48070373
has body: *args means accept a sequence of arguments and then wrap them into one variable args when using in function definition. And means unwrap all arguments when using in passing parameters. In your first example, args=(100, 100, 100), so calling _vulcanpy.TRI_triangulation_t_point_inside(self, *args) equals to _vulcanpy.TRI_triangulation_t_point_inside(self, 100, 100, 100). In your second example, if I understand you well, you want to make it work with just one argument which is a list. In this case, you need to manually decide the type of your arguments: def point_inside(self, double_or_list, *args) -&gt; "bool": if isinstance(double_or_list, list): return _vulcanpy.TRI_triangulation_t_point_inside(self, *double_or_list) else: return _vulcanpy.TRI_triangulation_t_point_inside(self, double_or_list, *args) updated Or you can unwrap list first tri.point_inside(*[100,100,100])
type: AcceptedAnswer

http://stackoverflow.com/comment/83043414
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48036473
has text: i did, the problem did not resolved. i have added more information here.
score: 0

http://stackoverflow.com/comment/128283902
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48054994
type: Comment
has text: To be very clear about why this answer won't cover the case: this would work for an or, but the question was in terms of an and. Both conditions must be met; not just one or the other.

http://stackoverflow.com/q/48107325
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48107426
accepted answer: http://stackoverflow.com/a/48107426
has title: Python3 threading about lock.acquire
type: Question
tagged with: locking
score: 0
answer count: 1
has body: When I test import threading def job1(): global A a = lock.acquire() print(a) for i in range(10): A+=1 print('job1',A) lock.release() def job2(): global A for i in range(10): A+=10 print('job2',A) if __name__== '__main__': lock=threading.Lock() A=0 t1=threading.Thread(target=job1) t2=threading.Thread(target=job2) t1.start() t2.start() t1.join() t2.join() most of the time, the result was (condition 1): True job1 1 job1 2 job1 3 job1 4 job1 5 job1 6 job1 7 job1 8 job1 9 job1 10 job2 20 job2 30 job2 40 job2 50 job2 60 job2 70 job2 80 job2 90 job2 100 job2 110 But One of the result was (condition 2) True job1 1 job1 2 job1 3 job1 4 job1 5 job1 6 job1 7 job2 17 job2 27 job2 37 job2 47 job2 57 job2 67 job2 77 job2 87 job2 97 job2 107 job1 108 job1 109 job1 110 I should have locked the thread in job1, why did result 2 come out? I found the result will always be condition 1 if I add another lock.acquire and lock.release statement in job2, but Why ?
tagged with: python-3.x
tagged with: multithreading

http://stackoverflow.com/a/48832939
has body: I ran into this issue on a windows laptop. the other answer didn't help me... here's what I did to get it working: first I had to stop using cygwin. the various commands are a bit wonky unless you are using cmd.exe. second, I read this article and follow the instructions to essentially install Jupyter within the env I wanted it to play with. https://www.quora.com/How-can-I-work-with-Keras-on-a-Jupyter-notebook-using-Tensorflow-as-backend hopefully this will help someone!
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48109094

http://stackoverflow.com/q/48112288
type: Question
duplicate of: http://stackoverflow.com/q/46103044
has body: I have a simple indexing need that I have no idea how to use numpy to achieve it. It's usually the case that we have two dimensional array of E with shape(N,C), and one dimensional array of y with shape(N), which is a label matrix, when computing the softmax loss, there is a widely used operation: E[range(N),y]-=1, this is very efficient code, Now I have a more generalized problem, that I have array E of shape(C,H,W) and label y of shape(H,W), now C axis is the first axis and there is 3 dimension, how can I do the similar operation like E[range(H,W), y]-=1
tagged with: numpy
score: 0
has title: numpy advanced indexing with array
has comment: http://stackoverflow.com/comment/83201983
linked to: http://stackoverflow.com/q/46103044
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83201511
has comment: http://stackoverflow.com/comment/83201701
tagged with: python
has comment: http://stackoverflow.com/comment/83201612
has comment: http://stackoverflow.com/comment/83201200
has comment: http://stackoverflow.com/comment/83202200
answer count: 0
has comment: http://stackoverflow.com/comment/83201036

http://stackoverflow.com/q/48148874
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48154935
has body: I have a problem where functions that I plot within SageMath aren't visually showing up. Even if I copy and paste code from the SageMath info pages, certain functions will not show up plotted for me. I'm using SageMath 8.1 Notebook. Here's example code: import numpy as np import matplotlib.pyplot as plt myPlot = plt.plot(np.array([0, 1, 2, 5])) show(myPlot) Output: [Line2D(-line49)] Instead of a graph. As far as I can tell, this should output a visual graph rather than just the info in brackets. Some code I copy from the SageMath Help Pages works, such as: v = [(1/cos(-pi/2+pi*i/100), tan(-pi/2+pi*i/100)) for i in range(1,200) if i!=100 ] L = [(a/(a^2+b^2), b/(a^2+b^2)) for a,b in v] Which outputs a visual graph. I'm not sure what I'm doing wrong here.
type: Question
tagged with: sage
answer count: 1
has title: Plotting functions with SageMath, not Showing
score: 0
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/a/48104746
has comment: http://stackoverflow.com/comment/83185805
answers question: http://stackoverflow.com/q/48102986
score: 0
has comment: http://stackoverflow.com/comment/83185391
has comment: http://stackoverflow.com/comment/83185577
type: Answer
has comment: http://stackoverflow.com/comment/83185269
has comment: http://stackoverflow.com/comment/83185522
has comment: http://stackoverflow.com/comment/83185440
has body: #This might help from flask import Flask from flask_wtf import FlaskForm #from wtform import SubmitField from wtforms import StringField, DecimalField, validators,SubmitField from flask import render_template app = Flask(__name__) app.config.update(dict( SECRET_KEY="super awesome key" )) class MyForm(FlaskForm): you need to make an edit to your validators like this name = StringField('Product name', validators = [InputRequired(), , Length(min=0, max=30)]) #create submit option in your flask form submit = SubmitField("Submit") @app.route('/', methods=['GET', 'POST']) def index(): form = MyForm() if form.validate_on_submit(): return "Mission accomplished!" return render_template('submit.html', form=form)

save
tags question: http://stackoverflow.com/q/48039971
tags question: http://stackoverflow.com/q/48079136
type: Tag
tags question: http://stackoverflow.com/q/48134176
tag name: save
tags question: http://stackoverflow.com/q/48115885

http://stackoverflow.com/a/48104545
answers question: http://stackoverflow.com/q/48104449
score: 0
has comment: http://stackoverflow.com/comment/83184875
has comment: http://stackoverflow.com/comment/83185158
type: Answer
has comment: http://stackoverflow.com/comment/83184870
upvote count: 1
has body: Here's another look with a hashed object, set: from time import time qlist = list(range(1000)) qset = set(qlist) start = time() for i in range(1000): 0 in qlist print time() - start start = time() for i in range(1000): 999 in qlist print time() - start start = time() for i in range(1000): 0 in qset print time() - start start = time() for i in range(1000): 999 in qset print time() - start Output: 0.000172853469849 0 in list 0.0399038791656 999 in list 0.000147104263306i 0 in set 0.000195980072021 999 in set As others have said, the list implementation must do a sequential search. Set inclusion uses a hashed value, and is on par with finding the item in the first element checked.
downvote count: 1

http://stackoverflow.com/a/48225475
answers question: http://stackoverflow.com/q/48114531
downvote count: 0
has body: I have come up with a workaround: class BundleSoftwareVersion(models.Model): bundle = models.ForeignKey(ComputerSoftwareBundle, on_delete=models.CASCADE) version = models.ForeignKey(SoftwareVersion, on_delete=models.CASCADE) _software = models.ForeignKey(Software, on_delete=models.CASCADE, null=True, editable=False) class Meta: unique_together = (("bundle", "_software"),) def save(self, *args, **kwargs): self._software = self.version.software super().save(*args, **kwargs) As you can see, I now have a helper field _software which is used in unique_together and into which the self.version.software is stored on each save. So far, I have experienced one downside with this approach: trying to save a ComputerSoftwareBundle containing duplicate software instances results in an error page for IntegrityError being displayed instead of an error message within the form. I would appreciate suggestions on how to fix this downside, or even suggestions for a different approach altogether.
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/a/48151653
has comment: http://stackoverflow.com/comment/104825422
type: Answer
has comment: http://stackoverflow.com/comment/83355144
has comment: http://stackoverflow.com/comment/133559456
score: 9
upvote count: 11
has body: Already found it: a = torch.zeros(10) b = a.type(torch.ByteTensor)
downvote count: 2
answers question: http://stackoverflow.com/q/48151637

http://stackoverflow.com/comment/83087789
type: QuestionComment
score: 1
has text: @AlbinPaul This has nothing to do with the issue
comment on: http://stackoverflow.com/q/48057732
type: Comment

http://stackoverflow.com/q/48040364
answer count: 1
type: UnansweredQuestion
tagged with: selenium
has title: Is there a way to change the filename of a file, when starting to download a file using Selenium?
tagged with: python
linked to: http://stackoverflow.com/q/34338897
has answer: http://stackoverflow.com/a/48046596
type: Question
has body: I'd like to download multiple files from a single website, but the biggest quirk I have is that the server automatically generates a random filename upon requesting the file to download. The issue here is then I won't know which file is which, without having to manually go through each file. However, on the site that has the links to download the files, they all have a name. For example... File name -&gt; Resultant file name(fake file names) Week1.pdf 2asd123e.pdf Week1_1.jpg dsfgp142.jpg . . Week10.pdf 19fgmo2o.pdf Week11.pdf 0we5984w.pdf If I were to download them manually by myself, I would type click "download" and a popup "Save as" menu comes up, which gives me the option to change the file name manually, then click ok to confirm the download, to which it starts downloading. Currently, my code is made to open up the website, log into my account, go to the files page, and then find a file, with it's corresponding server request link. IE: . I am able to store the name of the file, "Week1.pdf" into a variable, and click on the request link, but the only problem is that the Save as menu, doesn't have the ability to change the name of the filename, and only gives me the option to view the file, or Save the file immediately. I've looked around a little, and tried to play around with the Firefox profile settings, but nothing has worked. How would I go about solving this problem? Thanks
score: 0

http://stackoverflow.com/q/48119915
upvote count: 1
favorite count: 0
has title: Python - Regex split data in Dataframe
has body: I have a column containing values. I want to split it based on a regex. If the regex matches, the original value will be replaced with the left-side of the split. A new column will contain the right-side of a split. Below is some sample code. I feel I am close but it isn't quite working. import pandas as pd import re df = pd.DataFrame({ 'A' : ["test123","foo"]}) // Regex example to split it if it ends in numbers r = r"^(.+?)(\d*)$" df['A'], df['B'] = zip(*df['A'].apply(lambda x: x.split(r, 1))) print(df) In the example above I would expect the following output A B 0 test 123 1 foo I am fairly new to Python and assumed this would be the way to go. However, it appears that I haven't quite hit the mark. Is anyone able to help me correct this example?
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48120045
has answer: http://stackoverflow.com/a/48120167
type: Question
accepted answer: http://stackoverflow.com/a/48120167
possible better answer: http://stackoverflow.com/a/48119994
has answer: http://stackoverflow.com/a/48119994
answer count: 3
tagged with: pandas

http://stackoverflow.com/q/48148109
has answer: http://stackoverflow.com/a/48652474
downvote count: 0
has body: I have a model that accepts an arbitrary-length stream of data and performs classification. I use Tensorflow Serving to listen to gRPC requests and perform the classification on a trained model. Google Cloud Speech API has the "Streaming Speech Recognition" feature, that is available when using gRPC requests, which "allows you to stream audio to the Cloud Speech API and receive a stream [of] speech recognition results in real time as the audio is processed". I believe this is possible due to the Bidirectional streaming RPC that is described in gRPC documentation whereby "the server and client could “ping-pong”: the server gets a request, then sends back a response, then the client sends another request based on the response, and so on". So now I'm wondering whether I can achieve something similar to Google Cloud Speech API streaming recognition using Tensorflow Serving. The only reference I could find about this in the official docs of TF Serving (unless I missed something) was when describing possible future improvements: "Servables can be of any type and interface, enabling flexibility and future improvements such as: streaming results [...]". Is it already possible to achieve this functionality (bidirectional streaming) using TF Serving? If so, how? If not, what would be the best way to go about extending TF Serving to add this feature?
tagged with: grpc
tagged with: tensorflow-serving
tagged with: tensorflow
type: Question
tagged with: google-cloud-speech
upvote count: 6
answer count: 1
has title: Bidirectional Streaming using Tensorflow Serving
favorite count: 0
type: UnansweredQuestion
score: 6
tagged with: python

http://stackoverflow.com/q/48018544
favorite count: 0
has comment: http://stackoverflow.com/comment/83085648
tagged with: amazon-redshift
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48062783
has comment: http://stackoverflow.com/comment/83006083
has comment: http://stackoverflow.com/comment/83084494
has comment: http://stackoverflow.com/comment/83116744
has comment: http://stackoverflow.com/comment/83006154
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83084467
type: Question
has title: How to process data faster in python from redshift?
has comment: http://stackoverflow.com/comment/83028063
tagged with: amazon-web-services
tagged with: data-science
has comment: http://stackoverflow.com/comment/83019890
tagged with: hadoop
has comment: http://stackoverflow.com/comment/83084644
has body: i am new to python .. i have my data in redshift and i want to process data faster in python. i am using python because i want to run various algorithms and also do various calculations on these data and this is not possible in redshift . i saw tutorials but its taking too much time everytime to load in python. here is my code: import psycopg2 con=psycopg2.connect(dbname = "xxxx", host="redshifttest-icp.cooqucvshoum.us-west-2.redshift.amazonaws.com", port= "5439", user="xxxx", password= "xxxx") cur = con.cursor() a = "select * from xxxx ;" import pandas as pd df = pd.read_sql(a,con) df = df.fillna(0) df2=df2.fillna(0) this is working perfectly well, but i want some method which could help me to process data faster.. can anyone please help me ?
answer count: 2
has answer: http://stackoverflow.com/a/72718977
has comment: http://stackoverflow.com/comment/83108008
downvote count: 0

http://stackoverflow.com/comment/83105242
has text: Where you able to show the figure? using the `show()` function?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48066009

http://stackoverflow.com/comment/83325000
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48172543
type: Comment
has text: @deadcode It doesn't hurt to keep it there for those having some similar sort of issue and needing that solution instead.

http://stackoverflow.com/comment/119614397
type: Comment
comment on: http://stackoverflow.com/a/48217306
has text: Hi Kirill, could you please show the code? I am new to use Nginx and I have tried: `systemctl restart nginx -t 3000` which shows an error: `Unknown unit type or load state '3000s'.`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83185778
type: Comment
has text: That's where the second error is coming from by the way.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48105007

http://stackoverflow.com/q/48100939
score: 8
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48101507
downvote count: 0
has title: How to detect a Scikit-learn warning programmatically
possible better answer: http://stackoverflow.com/a/48101507
type: AnsweredQuestion
upvote count: 8
type: Question
has body: While fitting a model using sklearn.neural_network.MLPClassifier I sometimes receive a warning printed in the console: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (300) reached and the optimization hasn't converged yet. Is there a way to detect the warning during runtime so I can act on it?
has answer: http://stackoverflow.com/a/48102207
accepted answer: http://stackoverflow.com/a/48102207
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/75017962
answer count: 3
tagged with: python

http://stackoverflow.com/a/48091419
has body: I don't really have experience with multiprocessing, but it is my understanding that all objects in the module namespace of start_application.py are duplicated for each process. If I'm not mistaken, this includes the core module. Therefore, core.central_queue has a separate instance for each process. At least that seems to be the case on Windows and the Python docs recommend to "Explicitly pass resources to child processes" anyway. You should use the if __name__ == '__main__': block to create a unique instance of Queue and a unique instance of AudioRecorder, too. Then you can pass those unique instances to your processes with the args argument of Process (as is shown in the above link). Apart from that, I don't really know what you are trying to achieve. Do you want to process random chunks of the audio input with a random one of the available processes? Or do you want to provide the same audio input in its entirety to each of the processes? In the latter case, you should have a separate queue per child process after all! The sd.InputStream should still be unique. And in your with statement, you should iterate over all child processes and put the current chunk of audio into each of the process queues separately. PS: I just realized that you might want to start just a single additional process for some reason. In this case you should consider dropping the whole multiprocessing mess and just doing whatever you need to do in the with statement. UPDATE: If you want to use multiple audio devices (and therefore multiple PortAudio streams) at once, you still don't necessarily need multiprocessing. You can have a with statement with multiple context managers and do your processing in there. Depending on what you want to achieve, you might have a single queue where all audio callbacks write to or one queue per callback. If you have a good reason to use multiprocessing, it should also work fine if you start all audio streams in the main process and do your processing in a new…
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83176287
accepted answer of: http://stackoverflow.com/q/48072477
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48072477
has comment: http://stackoverflow.com/comment/83223631
has comment: http://stackoverflow.com/comment/83249107

http://stackoverflow.com/q/48034656
tagged with: text
has comment: http://stackoverflow.com/comment/83059344
linked to: http://stackoverflow.com/q/48033693
type: Question
has comment: http://stackoverflow.com/comment/83043866
has comment: http://stackoverflow.com/comment/83043848
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83039223
tagged with: python
tagged with: parsing
has title: parse irregular white space separated textfile
answer count: 0
has body: I am trying to parse a set of irregularly spaced txt files. For a screenshot example see: Example 1 The text file looks like this: Date This is a Task Location Postal short code Description 01.01.2000 The weather on this Take the Lyon which is a nice 0000123451151 day must have been Trash out city. What we do not very nice. The sun know is an opaque was shining. riddle 02.01.2000 This was a very cold Eat ice- Zurich was a nice 0123124 and rainy day. There cream trip. must have been some issue with the air- conditioner. 05.01.200 Very rainy day. Sad. Feel blue Berlin 12345 I first used: pd.read_table('testfile.txt') #,sep=r"\s*") fails due to: ParserError: Error tokenizing data. C error: Expected 1 fields in line 6, saw 5 The closest I got using pandas was with fixed separator method: pd.read_fwf('testfile.txt',delim_whitespace=True,skipinitialspace =True,skip_blank_lines=True) This yields the following dataframe: fwf result where (not surprisingly due to the f in fwf) parts of a string are separated over multiple columns (Note: here this is by construction, it happened in my real world data, too). Again, elements are irregularly white spate separated. That is text testfile.txt first row has different #characters compared to say file2.txt. Thus I can't just count the spaces and apply this to other files. Visually 1 one can see that the columns are always separated by white spaces (variable length). I have been working on a (admittedly not very clean) solution: GitHub The idea is to step through the file line by line and replace white space with a delimiter following a heuristic like: "three white spaces followed by non-space character, then replace third white space by delimiter" Then fill delimiter down according to a similar heuristic. The procedure is described in more detail on GitHub. I would appreciate any tip to solve this problem in a nicer way. Thank you very much!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83046039
tagged with: whitespace
has comment: http://stackoverflow.com/comment/83046078
has comment: http://stackoverflow.com/comment/83329801
has comment: http://stackoverflow.com/comment/83049159

http://stackoverflow.com/comment/83199004
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48110641
has text: ok ill delete the question

http://stackoverflow.com/comment/83294428
comment on: http://stackoverflow.com/q/48156213
has text: can you read the table instead?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48032776
has body: In python, I'm trying to make an RPG and when I do "def townbar():" it says that it's not defined. This code is for reference to make sure that everything is making sense: class Player: def __init__(self, name): self.name = name self.health2 = 100 self.health = self.health2 self.attack = 10 # Game def main(): print("Welcome player.") print("1. Start") print("2. Load") print("3. Exit") option = input("&gt; ") if option == "1": start() elif option == "2": pass elif option == "3": sys.exit() else: main() def start(): print('\n' * 80) print("Hello, what is your name?") option = input("&gt; ") global PlayerIG PlayerIG = Player(option) start1() def start1(): print('\n' * 80) print("Name: %s" % PlayerIG.name) print("Attack: %i" % PlayerIG.attack) print("Health: %i/%i\n" % (PlayerIG.health, PlayerIG.health2)) print("1. Go to nearby town") print("2. Stand here and do nothing") option = input("&gt; ") if option == "1": town() if option == "2": print("Really? This is the guy we chose to be the hero of this story? *sigh* Pick again.") start1() else: start1() def town(): print('\n' * 80) print("You arrive at the town and you see 3 signs.\n") print("1. Go to the bar") print("2. Go to the market") print("3. Go to the king") option = input("&gt; ") if option == "1": townbar() elif option == "2": market() elif option == "3": print("The king ignores you, as you are but a peasant\n") town() else: town() This is the part that gives me problems, it says that bar is not defined (it was the old name for townbar). After I changed the name and checked that everything was fine, it still shows that error. def townbar(): print('\n' * 80) print("You see many people in the bar.") print("1. Talk to the bartender") print("2. Talk to the people in the bar") print("3. Exit the bar") option = input("&gt; ") if option == "1": print("The bartender greets you.\n") bartendertalk() elif option == "2": print("The people don't care enough or are too drunk to speak to you.\n") townbar() elif option == "3": t…
has comment: http://stackoverflow.com/comment/83035744
has comment: http://stackoverflow.com/comment/83035763
answer count: 2
downvote count: 2
tagged with: function
favorite count: 0
has comment: http://stackoverflow.com/comment/83035715
has comment: http://stackoverflow.com/comment/83035792
tagged with: python
has comment: http://stackoverflow.com/comment/83035996
has comment: http://stackoverflow.com/comment/83035757
has title: Python - Function not defined
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83035724
has answer: http://stackoverflow.com/a/48033177
has answer: http://stackoverflow.com/a/48033316
type: Question
has comment: http://stackoverflow.com/comment/83035780
score: -2

http://stackoverflow.com/a/75257221
type: Answer
answers question: http://stackoverflow.com/q/48153886
has body: I implemented a flake8 plugin flake8-in-file-ignores to allow adding "ignore" rules in the file itself (as opposed to the built-in config approach), the plugin uses the following syntax # flake8-in-file-ignores: noqa: E731,E123
upvote count: 9
score: 9
downvote count: 0

http://stackoverflow.com/comment/83244553
comment on: http://stackoverflow.com/q/48131106
score: 0
has text: @vinzee I have added the error code.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48054643
type: Answer
has body: A parameter is a local name that is bound to a object as part of the call. If a function parameter name is the same as a global name, then within the function, the name refers to the parameter, not the global. a = 0 def f(a): print(a) f(1) # prints 1, not 0 Local names within difference functions that are not nested within each other, with with variance in your code, cannot interfere with each other.
answers question: http://stackoverflow.com/q/48054569
score: 0

http://stackoverflow.com/comment/83227958
comment on: http://stackoverflow.com/q/48124321
score: 1
type: Comment
type: QuestionComment
has text: i would use [bokeh](https://bokeh.pydata.org/en/latest/)

http://stackoverflow.com/q/48047495
has body: Collecting jws&gt;=0.1.3 (from python-jwt==2.0.1-&gt;pyrebase) Using cached https://files.pythonhosted.org/packages/01/9e/1536d578ed50f5fe8196310ddcc921a3cd8e973312d60ac74488b805d395/jws-0.1.3.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 "C:\Users\Wesely\AppData\Local\Temp\pip-install-w5z8dsub\jws\setup.py", line 17, in &lt;module&gt; long_description=read('README.md'), File "C:\Users\Wesely\AppData\Local\Temp\pip-install-w5z8dsub\jws\setup.py", line 5, in read return open(os.path.join(os.path.dirname(__file__), fname)).read() UnicodeDecodeError: 'cp949' codec can't decode byte 0xe2 in position 500: illegal multibyte sequence ---------------------------------------- I tried easy_install pyrebase, and using virtualenv. I'm using Korean Windows 10.
downvote count: 1
type: Question
score: 5
has comment: http://stackoverflow.com/comment/83066673
answer count: 3
has comment: http://stackoverflow.com/comment/83066596
favorite count: 0
tagged with: python-3.x
tagged with: pip
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/54770648
has answer: http://stackoverflow.com/a/49868663
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61786036
has title: When pip install 'pyrebase', I got error ' UnicodeDecodeError: 'cp949' codec can't decode byte 0xe2 in position 500: illegal multibyte sequence'
has comment: http://stackoverflow.com/comment/83066665
possible better answer: http://stackoverflow.com/a/54770648
accepted answer: http://stackoverflow.com/a/49868663

http://stackoverflow.com/a/48166533
upvote count: 1
answers question: http://stackoverflow.com/q/48166461
has comment: http://stackoverflow.com/comment/83315480
has comment: http://stackoverflow.com/comment/83314821
downvote count: 0
has comment: http://stackoverflow.com/comment/83314863
has comment: http://stackoverflow.com/comment/83315418
has comment: http://stackoverflow.com/comment/83314899
type: Answer
has body: Try this: df[df['count'] &gt; 1000].set_index('Word').plot.bar(rot=0) Demo (using your sample data set): In [184]: df Out[184]: Word count 17 in 2 15 on 2 33 the 2 8 you 2 0 valar 1 29 all 1 24 + 1 25 hotel 1 26 are 1 In [185]: df.dtypes Out[185]: Word object count int64 # &lt;--------- NOTE ! dtype: object In [187]: df[df['count'] &gt; 1].set_index('Word').plot.bar(rot=0, grid=True) Out[187]: &lt;matplotlib.axes._subplots.AxesSubplot at 0xd608ac8&gt; Result:
score: 1

http://stackoverflow.com/comment/83018370
has text: That was just an example, but if I can at least get that, I'm sure I can go from there. Thanks
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48024512
type: Comment

regex
tags question: http://stackoverflow.com/q/48069247
tags question: http://stackoverflow.com/q/48134942
tags question: http://stackoverflow.com/q/48159098
tags question: http://stackoverflow.com/q/48039486
tags question: http://stackoverflow.com/q/48112468
tags question: http://stackoverflow.com/q/48092985
tags question: http://stackoverflow.com/q/48170829
tags question: http://stackoverflow.com/q/48072603
tags question: http://stackoverflow.com/q/48036369
tags question: http://stackoverflow.com/q/48142203
tags question: http://stackoverflow.com/q/48084139
tag name: regex
tags question: http://stackoverflow.com/q/48017311
tags question: http://stackoverflow.com/q/48171985
tags question: http://stackoverflow.com/q/48025016
tags question: http://stackoverflow.com/q/48028258
tags question: http://stackoverflow.com/q/48045260
tags question: http://stackoverflow.com/q/48027883
tags question: http://stackoverflow.com/q/48054636
tags question: http://stackoverflow.com/q/48075393
tags question: http://stackoverflow.com/q/48046350
tags question: http://stackoverflow.com/q/48110074
tags question: http://stackoverflow.com/q/48166634
tags question: http://stackoverflow.com/q/48076807
tags question: http://stackoverflow.com/q/48131551
tags question: http://stackoverflow.com/q/48106605
tags question: http://stackoverflow.com/q/48049189
tags question: http://stackoverflow.com/q/48079594
tags question: http://stackoverflow.com/q/48059420
tags question: http://stackoverflow.com/q/48138442
tags question: http://stackoverflow.com/q/48049006
tags question: http://stackoverflow.com/q/48116509
tags question: http://stackoverflow.com/q/48056360
tags question: http://stackoverflow.com/q/48069712
tags question: http://stackoverflow.com/q/48092347
tags question: http://stackoverflow.com/q/48022511
tags question: http://stackoverflow.com/q/48093746
tags question: http://stackoverflow.com/q/48106655
tags question: http://stackoverflow.com/q/48132494
tags question: http://stackoverflow.com/q/48119587
tags question: http://stackoverflow.com/q/48081491
tags question: http://stackoverflow.com/q/48142171
tags question: http://stackoverflow.com/q/48047731
tags question: http://stackoverflow.com/q/48062271
tags question: http://stackoverflow.com/q/48154938
tags question: http://stackoverflow.com/q/48047250
tags question: http://stackoverflow.com/q/48093968
tags question: http://stackoverflow.com/q/48043411
tags question: http://stackoverflow.com/q/48071149
tags question: http://stackoverflow.com/q/48074764
tags question: http://stackoverflow.com/q/48149514
tags question: http://stackoverflow.com/q/48070802
tags question: http://stackoverflow.com/q/48092426
tags question: http://stackoverflow.com/q/48046630
tags question: http://stackoverflow.com/q/48043337
tags question: http://stackoverflow.com/q/48047147
tags question: http://stackoverflow.com/q/48038838
tags question: http://stackoverflow.com/q/48133682
tags question: http://stackoverflow.com/q/48121809
tags question: http://stackoverflow.com/q/48124149
tags question: http://stackoverflow.com/q/48055069
tags question: http://stackoverflow.com/q/48140997
tags question: http://stackoverflow.com/q/48020296
tags question: http://stackoverflow.com/q/48144574
tags question: http://stackoverflow.com/q/48093977
tags question: http://stackoverflow.com/q/48088558
tags question: http://stackoverflow.com/q/48165190
tags question: http://stackoverflow.com/q/48130758
tags question: http://stackoverflow.com/q/48045456
tags question: http://stackoverflow.com/q/48155181
tags question: http://stackoverflow.com/q/48045952
tags question: http://stackoverflow.com/q/48055935
tags question: http://stackoverflow.com/q/48121303
tags question: http://stackoverflow.com/q/48141820
tags question: http://stackoverflow.com/q/48025095
tags question: http://stackoverflow.com/q/48166760
tags question: http://stackoverflow.com/q/48017666
type: Tag
tags question: http://stackoverflow.com/q/48127434
tags question: http://stackoverflow.com/q/48107922

http://stackoverflow.com/q/48026464
tagged with: data-structures
upvote count: 2
downvote count: 0
answer count: 1
favorite count: 0
has title: Separating AES/CBC IV and ciphertext in one message
type: UnansweredQuestion
tagged with: python
has body: Most examples on stackoverflow and the web at large put the CBC initialization vector (IV) as a "prefix" to ciphertext, e.g.: bytesToSend = bytesOfIV + bytesOfCipherText And then on the other side, a variety of clever/simple/flexible means are used to separate them, the slicing operator in python and assuming a 16 byte IV being particularly prevalent (and simple): bytesRead = get bytes from source IV = bytesRead[:16] cipherText = bytesRead[16:] This approach has stood the test of time and it's fine but it also is very limiting in that both sides (specifically, the listener part of both sides) must know exactly what they should do with the inbound bytes. In fact, short of slicing off the IV and using the shared secret, there's almost no other operation that can be performed. I am examining a design wherein inbound messages have two sections: one that can be encrypted and one that is NEVER encrypted. Clearly, sensitive information is NOT put into the unencrypted section, but because it is in plaintext, a listener can actually do something intelligent with the content prior to decryption. Example: message routing, identifiers for multiple encryption keys, etc. And of course, this could include the IV. Simplified example: { neverEncrypted: { cipher: "AES/CBC/PKCS5PADDING", IV: "121866AFBBDF2906C0D942C1FA7C4DAB", other: [ "hello", 2, 3 ], timestamp: date }, data: (binary cipherText WITHOUT the IV prefix) } This approach certainly "works" and IV is not assumed to be secret so it can live in neverEncrypted. I also like the fact that one does not have to get "clever" about the concatenation and splitting of material, esp. assumptions about block size initialization, etc. This is particularly true if a listener needs to listen for material encrypted with 2 (or more) ciphers. The question is: Is there any special advantage to the "prefix" approach re. security or is it more just a nice method of transferring both pieces of information without requiring any additional fancy da…
score: 2
has answer: http://stackoverflow.com/a/48028996
tagged with: encryption
type: Question
tagged with: messaging

http://stackoverflow.com/a/48151525
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48151066
downvote count: 0
has body: This will also generate type "R". You could append and sort, and assign type "R" like MaxU's function. df.loc[df.loc[:,"type"] != "A" ].groupby( ("Copy","sequence") , as_index = False).mean()

http://stackoverflow.com/a/48150484
type: Answer
has comment: http://stackoverflow.com/comment/83279616
score: 3
upvote count: 3
downvote count: 0
has body: you can iterate from bottom to top (like tail recursion): var fib_tail = function(n){ if(n == 0) return 0; if(n == 1 || n == 2) return 1; var prev_1 = 1, prev_2 = 1, current; // O(n) for(var i = 3; i &lt;= n; i++) { current = prev_1 + prev_2; prev_1 = prev_2; prev_2 = current; } return current; } console.log(fib_tail(1000))
answers question: http://stackoverflow.com/q/48150328

http://stackoverflow.com/q/48040836
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48041008
has body: I've written some code in python in combination with selenium to parse different product names from a webpage. There are few load more buttons visible if the browser is made to scroll downward. The webpage displays it's full content if the page is made to scroll downmost until there is no load more button to click. My scraper seems to be doing good but I'm not getting all the results. There are around 200 products in that page but I'm getting 90 out of them. What change should I bring about in my scraper to get them all? Thanks in advance. The webpage I'm dealing with: Page_Link This is the script I'm trying with: import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("put_above_url_here") wait = WebDriverWait(driver, 10) page = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,".listing_item"))) for scroll in range(17): page.send_keys(Keys.PAGE_DOWN) time.sleep(2) try: load = driver.find_element_by_css_selector(".lm-btm") load.click() except Exception: pass for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "[id^=item_]"))): name = item.find_element_by_css_selector(".pro-name.el2").text print(name) driver.quit()
tagged with: web-scraping
tagged with: python
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48041103
downvote count: 0
has answer: http://stackoverflow.com/a/48041103
tagged with: selenium
type: Question
upvote count: 2
answer count: 2
has title: My scraper fails to get all the items from a webpage
accepted answer: http://stackoverflow.com/a/48041008
favorite count: 0

http://stackoverflow.com/q/48145966
favorite count: 0
has answer: http://stackoverflow.com/a/48146411
tagged with: python
possible better answer: http://stackoverflow.com/a/71271500
has answer: http://stackoverflow.com/a/71271500
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/48146411
type: Question
has body: I am stuck on this problem I would like to request this URL, which is in a odata format "http://services.odata.org/V3/OData/OData.svc/Products?$format=json" and that comes from this link. I tried with the following code but it doesn't work from odata import ODataService url_test = "http://services.odata.org/V3/OData/OData.svc/Products? $format=json" service = ODataService(url, reflect_entities=False) service.entities['ID'] My end goal is to retrieve all the different ID with their Price. Thanks I have this error message --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-5-2db727483d6e> in <module>() 3 service 4 ----> 5 service.entities['ID'] KeyError: 'ID'
has comment: http://stackoverflow.com/comment/83292481
tagged with: odata
answer count: 2
score: 3
downvote count: 0
has title: ODATA, JSON and Python

http://stackoverflow.com/a/48057766
score: 1
has comment: http://stackoverflow.com/comment/83088050
upvote count: 1
answers question: http://stackoverflow.com/q/48057691
has body: You should use a raw string literal. A \ followed by an integer is interpreted as a unicode character which is an invalid file name. Try print('E:\23\4\plan_to_prod2.csv') and see the output (I would have pasted it here but these characters don't show up when the answer is rendered). You can also see the problem in the error you provided in the comment. When using raw string: print(r'E:\23\4\plan_to_prod2.csv') # E:\23\4\plan_to_prod2.csv Instead of using raw string you can also use double slashes, ie print('E:\\23\\4\\plan_to_prod2.csv') but I find using raw strings much easier.
has comment: http://stackoverflow.com/comment/83087982
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83227848
score: 0
has text: The desired output is a DataFrame consisting of respective columns and their headers being "Country", "Energy Supply", "Energy Supply per capita", "% Renewable". I am struggling to skip the header and the footer, but I am unable to.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48125438

http://stackoverflow.com/comment/83228785
type: Comment
comment on: http://stackoverflow.com/a/48119604
has text: the (1,2,H,W) was generated by some intermediate layer of the prj I'm currently on, which is not writen by me, the first dimension means batch number, here the batch size is 1
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83123746
has text: Please check this question https://stackoverflow.com/questions/47892066/sgd-classifier-partial-fit-learning-with-different-dimensional-input-data . I was suggested to use transform
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48075007

remote-debugging
tag name: remote-debugging
tags question: http://stackoverflow.com/q/48050064
type: Tag

http://stackoverflow.com/comment/83323051
comment on: http://stackoverflow.com/q/48171159
has text: Something like https://api.jquery.com/jquery.post/?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83057691
has text: I am getting the following error: set_xticklabels() missing 1 required positional argument: 'labels'
type: Comment
comment on: http://stackoverflow.com/a/48043399
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83227150
type: QuestionComment
has text: yes, that's correct
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48120106

http://stackoverflow.com/comment/83071630
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48049886
has text: Ah, that makes it a bit more interesting (but I stand by my earlier statement). So...what kind of errors does it print? Please read [mcve] and [ask] :P
type: Comment

http://stackoverflow.com/q/48147747
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83273668
type: Question
accepted answer: http://stackoverflow.com/a/48150706
score: 0
has comment: http://stackoverflow.com/comment/83277582
has body: I am new to python and trying to use git commands in python script. The requirement is that I need to call some git commands like git clean and git reset commands in my python script. I need to use subprocess for this as I can't use any external libraries like GitPython. Any help would be appreciated Thanks.
answer count: 1
has answer: http://stackoverflow.com/a/48150706
has title: How can I call the git clean -df command from a python script
linked to: http://stackoverflow.com/q/89228
tagged with: python
tagged with: git

http://stackoverflow.com/q/48083885
tagged with: numpy
has comment: http://stackoverflow.com/comment/83142647
has comment: http://stackoverflow.com/comment/83142673
answer count: 1
has title: More optimal way to find then sort from two numpy arrays
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48084134
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48084134
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83142602
has body: For simplicity, take the small example below. Lets say we have 2 sets of numpy arrays, values and distances. I'd like to find values that are above 1 and sort them by its corresponding distances. If there are values with similar distances, I'd like to have it sorted with the higher value first. v = np.array([[1.0,2.0,0.0],[1.0,0.0,0.0],[0.0,0.0,0.0]]) d = np.array([[1.5,1.0,1.5],[1.0,0.0,1.0],[1.5,1.0,1.5]]) indexes = np.argwhere(v &gt;= 1) list = ( ((d[r,c],v[r,c],(r,c))) for r, c in indexes) closest_highest = sorted(list,key=lambda t: (t[0],-t[1])) print(closest_highest) output: [(1.0, 2.0, (0, 1)), (1.0, 1.0, (1, 0)), (1.5, 1.0, (0, 0))] Each tuple contains the distance, value, and its coordinates from the two arrays. Is there a faster way to do the above using just numpy/vectorized computations? If not, is there a faster/more efficient way to do the following? I dont really need it to return a tuple, just the index is enough. Even just the index of the lowest distance with the highest value is enough.
tagged with: sorting

http://stackoverflow.com/a/48168650
has body: Use raw_input On Python 2, input() is equal to eval(raw_input()) – it evaluates your input as it was a python code.
type: Answer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48158023

http://stackoverflow.com/comment/83093697
has text: Okay ... Thanks a lot !!
type: Comment
comment on: http://stackoverflow.com/a/48059073
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83072099
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48049298
has text: It still doesn't say which sensor it is...
score: 0

http://stackoverflow.com/q/48062300
type: UnansweredQuestion
upvote count: 1
tagged with: python
answer count: 0
has title: python/kivy : set dynamically value on on_touch_down event in TextInput from treeView
has comment: http://stackoverflow.com/comment/83138800
score: 1
type: Question
has body: I have two files test1.py and test1.kv. There are a +Add more button.When click on +Add More button then row add dynamic. I added treeView on TextInput.But now i am confused that how to put selected treeView value(self.text) in current TextBox because every TextBox added dynamic so i don't know how to set selected treeView value in current TextBox test1.py import kivy kivy.require('1.9.0') # replace with your current kivy version ! import sqlite3 as lite from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty from kivy.lang import Builder from kivy.uix.popup import Popup from kivy.core.window import Window from kivy.uix.label import Label from kivy.clock import Clock from kivy.uix.treeview import TreeView, TreeViewLabel, TreeViewNode from kivy.uix.screenmanager import Screen Window.size = (450, 525) class TreeviewNumber(Popup): treeview = ObjectProperty(None) tv = ObjectProperty(None) h = NumericProperty(0) def __init__(self, **kwargs): super(TreeviewNumber, self).__init__(**kwargs) self.tv = TreeView(root_options=dict(text=""), hide_root=False, indent_level=4) rows = [('One'), ('Two'), ('Three')] tree = [] for r in rows: tree.append({'node_id': r, 'children': []}) for branch in tree: populate_tree_view(self.tv, None, branch) #self.remove_widgets() self.treeview.add_widget(self.tv) Clock.schedule_once(self.update, 1) def remove_widgets(self): for child in [child for child in self.treeview.children]: self.treeview.remove_widget(child) def update(self, *args): self.h = len([child for child in self.tv.children]) * 24 def populate_tree_view(tree_view_city, parent, node): if parent is None: tree_node = tree_view_city.add_node(TreeViewLabel(text=node['node_id'], is_open=True)) else: tree_node = tree_view_city.add_node(TreeViewLabel(text=node['node_id'], is_open=True), parent) for child_node in node['children']: populate_tree_view(tree_view_city, tree_node, …
downvote count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83099488
tagged with: kivy
favorite count: 0
tagged with: python-3.x
tagged with: kivy-language

http://stackoverflow.com/q/48019407
tagged with: qubole
has answer: http://stackoverflow.com/a/50771200
type: Question
answer count: 1
has title: Qubole: How can I download scheduler result in python?
has body: Like title, I managed myself download the Qubole result using the query id in python, however, is there a method that I can download the result using scheduler job ID instead of query ID? Thanks.
tagged with: python
type: UnansweredQuestion
score: 0

http://stackoverflow.com/comment/83007536
comment on: http://stackoverflow.com/q/48015378
score: 0
has text: Are the shapefiles available from somewhere?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83207599
type: Comment
has text: Unfortunately, at some point you have to compute the square of `K` (and store it in memory) to be able to multiply. You can work around the need to store the entire array if you compute the values in place (see https://stackoverflow.com/a/6824389/1150961 for a discussion). I've added a possible solution using cython.
comment on: http://stackoverflow.com/a/48115284
score: 0
type: AnswerComment

http://stackoverflow.com/q/48107619
tagged with: python-3.x
upvote count: 2
tagged with: python
tagged with: namespaces
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48107656
type: Question
has title: Python function's __dict__
downvote count: 0
has body: I know functions objects have a __dict__. Few times this is used to add attributes to the function. Some people even use it to add anotations to the function. My doubt is the following. If a have: def foo(): a = 2 return Where is "a" stored? I make this question because I was expecting to find it in the __dict__ of foo, but now I know this is not the purpose of a function's __dict__. If functions are instance objects of the class function, and the namespace of an object is defined by its __dict__. What is the namespace of a?
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48107656

http://stackoverflow.com/comment/83060564
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48044766
has text: How long do they freeze for in terms of time?
score: 0

http://stackoverflow.com/a/48027730
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48027655
has body: I found the problem. I was trying to decode it in python 2. Python 2 and python 3 handle this kind of conversion differently. Once I tried it in python 3 everything worked fine. Thank you all for your help!

http://stackoverflow.com/comment/83197085
score: 1
comment on: http://stackoverflow.com/q/48110810
has text: Currently you are using Python and writing the script in Notepad++, which is not a language in itself
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48156130
upvote count: 4
downvote count: 0
has body: Approach #1 : numpy.unique based Here's one approach using recently added axis functionality with np.unique - In [64]: s = np.sort(df.values, axis=1) In [65]: unq, tag, count = np.unique(s, axis=0, return_counts=1, return_inverse=1) In [66]: df[np.in1d(tag, np.flatnonzero(count &gt; 1))] Out[66]: num1 num2 num3 0 1 1 5 4 5 1 1 Alternatively, the last step could be simplified - In [63]: df[count[tag] &gt; 1] Out[63]: num1 num2 num3 0 1 1 5 4 5 1 1 Approach #2 : View and index-sorting based This one's focused on performance - # https://stackoverflow.com/a/44999009/ @Divakar def view1D(a): # a is array a = np.ascontiguousarray(a) void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1])) return a.view(void_dt).ravel() # Get duplicate rows indices off an array with order of elems being insensitive def duprows_order_insensitive(ar): # ar is array s = np.sort(ar, axis=1) s_view1D = view1D(s) sidx = s_view1D.argsort() s_view1D_sorted = s_view1D[sidx] mask0 = s_view1D_sorted[1:] == s_view1D_sorted[:-1] mask = np.r_[False,mask0] mask[:-1] |= mask0 return sidx[mask] # sort these if sorted indices are needed Hence, the desired output would be obtained like so - df.iloc[duprows_order_insensitive(df.values)] Sample run - In [234]: df Out[234]: num1 num2 num3 0 1 1 5 1 5 5 5 2 2 1 4 3 1 5 1 4 4 3 2 5 5 1 1 6 1 4 2 In [235]: df.iloc[duprows_order_insensitive(df.values)] Out[235]: num1 num2 num3 0 1 1 5 3 1 5 1 5 5 1 1 2 2 1 4 6 1 4 2
has comment: http://stackoverflow.com/comment/83291984
score: 4
type: Answer
answers question: http://stackoverflow.com/q/48156059

http://stackoverflow.com/comment/83304075
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48161562
has text: @sytech The time creation of `image_indices` is not counted and I have added a note. You can try to create 15,000 images (with .tiff extension) and tried to measure the random selection of 100 images. I believe you will be surprised of what I have found!
type: Comment

http://stackoverflow.com/a/48159123
type: AcceptedAnswer
downvote count: 0
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48055852
type: Answer
answers question: http://stackoverflow.com/q/48055852
has body: You have to make sure that the Couenne executable is in your PATH environment variable. You will know this is done correctly if you can open a terminal and type couenne and get the following output: $ couenne Couenne 0.5.6 -- an Open-Source solver for Mixed Integer Nonlinear Optimization Mailing list: couenne@list.coin-or.org Instructions: http://www.coin-or.org/Couenne No stub! usage: couenne [options] stub [-AMPL] [&lt;assignment&gt; ...] Options: -- {end of options} -= {show name= possibilities} -? {show usage} -bf {read boundsfile f} -e {suppress echoing of assignments} -of {write .sol file to file f} -s {write .sol file (without -AMPL)} -v {just show version} Similarly you should open a terminal and verify that Pyomo is successfully installed. Once you verify those two things then you can use Couenne from Pyomo simply by specifying 'couenne' as the solver.
has comment: http://stackoverflow.com/comment/137203961
score: 2

http://stackoverflow.com/comment/83197569
comment on: http://stackoverflow.com/q/48110779
type: Comment
type: QuestionComment
has text: A flush() is helpful but I will lost previous protein_annotation session after rollback() . So only raw connection is possible:(.
score: 0

http://stackoverflow.com/comment/83294414
type: Comment
comment on: http://stackoverflow.com/q/48155181
type: QuestionComment
has text: The Natural Language Toolkit (Python library for computational linguistics) to which that tag refers, seemed excessively broad for your task, that's why. I am not sure about a pure regex solution; perhaps best is a combination with simple string matching.
score: 0

http://stackoverflow.com/q/48045708
tagged with: tensorflow
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48046942
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has body: I know you can do something like this: import pandas as pd df = pd.read_csv('mushrooms.csv') df.apply(lambda x: pd.factorize(x)[0]) but what I want is to change all categories to be 0 or 1. An example would be if the headers in the CSV file are favColor and favCookie, and the options for favColor are 'red', 'orange' and 'green', and the options for favCookie are 'chocolate' and 'sugar'. If one of the rows is 'red' and 'sugar', I would want the full row to change into [1,0,0,0,1]. I was looking more for like a library so it will be easy doing this every time I use a CSV file and a neural network
has title: What is the easiest way to convert csv file into inputs for machine learning?
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/48045778

http://stackoverflow.com/comment/83013567
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48017926
type: Comment
has text: Returned, please keep me in check if I make mistakes as well. :-)

http://stackoverflow.com/comment/83130205
has text: I think he is not using anaconda so it might not help.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48076121

http://stackoverflow.com/a/48140091
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48137207
has body: My solution was to remove %PYTHONHOME% (ignore it). Looked like an Anaconda installation was present. Anaconda3 doesn't seem to care about it but doesn't add the correct path into PATH. I removed C:\Users\\Anaconda related PATH entries (Anaconda\Scripts) and substituted them by D:\Users\\Anaconda3 (D is correct here because I forced the Anaconda3 installation to go to drive D:). Maybe this is also a cause for the installation quirks.

http://stackoverflow.com/comment/83269069
score: 0
has text: Your question seems ambiguous. Can you make it more clear what's certain and what's uncertain?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48145435

http://stackoverflow.com/comment/83090465
type: Comment
type: QuestionComment
has text: In 2018 you should seriously consider switching to Python 3
score: 4
comment on: http://stackoverflow.com/q/48059093

http://stackoverflow.com/comment/83112605
type: Comment
type: QuestionComment
has text: yes it would. and based on the code i posted, the its doing predictions based on the data-'descriptions'- im giving it through an excel file. Since it can make predictions i want it to group similar 'group names'
comment on: http://stackoverflow.com/q/48067726
score: 0

http://stackoverflow.com/comment/83265442
type: Comment
type: QuestionComment
has text: You have (a) unbalanced parentheses and (b) a great chance for SQL injection attacks. Don't use % string formatting on SQL queries!
score: 1
comment on: http://stackoverflow.com/q/48143659

http://stackoverflow.com/a/48052915
type: AcceptedAnswer
upvote count: 5
downvote count: 0
has body: RSA works modulo n. Therefore, messages cannot be more than or equal to n. This can be fixed by increasing the size of the prime numbers p and q. An easy way to generate large prime numbers is with the rabin-miller primality test. You can read more about that test here Rabin-Miller Primality Test. Also, on a side note, in your code you have (message ** e) % n whilst this is fast for small values, it is much faster to use the built in pow function pow(message, e, n)
answers question: http://stackoverflow.com/q/48052799
type: Answer
accepted answer of: http://stackoverflow.com/q/48052799
score: 5

http://stackoverflow.com/comment/83003024
comment on: http://stackoverflow.com/q/48016665
score: 0
type: QuestionComment
has text: Yes I think this is heading in the right direction. The key point is that I don't want to rewrite any functions, especially of 'output_letter'
type: Comment

http://stackoverflow.com/q/48015196
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/75699132
has title: Django add hard-coded href links to an admin model's form view page
has answer: http://stackoverflow.com/a/75699132
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48015291
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: django-forms
type: Question
tagged with: django-admin
has body: In Django's admin panel, how do I add hard-coded links to a Django model's form page (/add/ page). These are links to documentation that will never change. I want these links to appear every time on the form as a reference for the user to figure out what values to input into the fields. Do I need: Custom field? Built-in field already? Modify the admin templates somehow? Add a helper function somewhere? I'm not referring to the "change list" view; I am referring to the /change/ or /add/ page view when you go and add or edit an object within a model. models.py class DateRange(models.Model): date_name = models.CharField(max_length=100) adwords_name = models.CharField(max_length=100) bingads_name = models.CharField(max_length=100) def __str__(self): return self.date_name forms.py class DateRangeAdminForm(forms.ModelForm): class Meta: model = DateRange fields = '__all__' admin.py @admin.register(DateRange) class DateRangeAdmin(admin.ModelAdmin): form = DateRangeAdminForm list_display = ['date_name', 'adwords_name', 'bingads_name']
accepted answer: http://stackoverflow.com/a/48015291
answer count: 2

http://stackoverflow.com/q/48158824
downvote count: 4
has comment: http://stackoverflow.com/comment/83297266
has answer: http://stackoverflow.com/a/48158874
favorite count: 0
type: UnansweredQuestion
score: -3
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83297257
has comment: http://stackoverflow.com/comment/83297292
has answer: http://stackoverflow.com/a/48158910
has body: I am writing a code and want to make it as short as possible, is there any way i can? text = raw_input("Give me some text &gt; ") list1 = [] for char in text: num = ord(char) if num in range(48,57): print "ERROR 319: Number entered" quit() elif num in range(65,90) or num in range (97,122): upper = char.upper() list1.append(upper) num1 = 0 vowelCount = 0 conCount = 0 for x in range(len(list1)): if list1[num1] == "A" or list1[num1] == "E" or list1[num1] == "I" or list1[num1] == "O" or list1[num1] == "U": vowelCount = vowelCount + 1 else: conCount = conCount + 1 num1 = num1 + 1 print "Vowels: " +str(vowelCount) + " Consonants: " + str(conCount)
has comment: http://stackoverflow.com/comment/83297223
type: Question
answer count: 2
has title: How can I make this code shorter (less lines etc)
has comment: http://stackoverflow.com/comment/83299016
has comment: http://stackoverflow.com/comment/83297181
tagged with: python-2.7

http://stackoverflow.com/comment/83295316
has text: Try this: `pandas_df = df1.select([c for c in df1.columns if any([x in c for x in include_cols])])`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48157190

http://stackoverflow.com/a/48170325
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83321137
type: Answer
has body: You could do it with a for loop using enumerate(): list1=[["artur","1/1/2018","0.5"], ["paco","1/1/2018","2.11"], ["pepe","1/1/2018","11.2"], ["artur","2/1/2018","0.5"], ["paco","2/1/2018","2.11"], ["pepe","2/1/2018","11.2"]] list2=[["artur","1/1/2018","Estable"], ["paco","1/1/2018","Critico"], ["pepe","1/1/2018","Critico"], ["artur","2/1/2018","Estable"], ["paco","2/1/2018","Critico"], ["pepe","2/1/2018","Critico"]] for i, item in enumerate(list2): list1[i].append(item[-1]) &gt;&gt;&gt; pprint(list1) [['artur', '1/1/2018', '0.5', 'Estable'], ['paco', '1/1/2018', '2.11', 'Critico'], ['pepe', '1/1/2018', '11.2', 'Critico'], ['artur', '2/1/2018', '0.5', 'Estable'], ['paco', '2/1/2018', '2.11', 'Critico'], ['pepe', '2/1/2018', '11.2', 'Critico']] Edit: list1=[["artur,1/1/2018,0.5"], ["paco,1/1/2018,2.11"], ["pepe,1/1/2018,11.2"], ["artur,2/1/2018,0.5"], ["paco,2/1/2018,2.11"], ["pepe,2/1/2018,11.2"]] list2=[["artur,1/1/2018,Estable"], ["paco,1/1/2018,Critico"], ["pepe,1/1/2018,Critico"], ["artur,2/1/2018,Estable"], ["paco,2/1/2018,Critico"], ["pepe,2/1/2018,Critico"]] # slice assignment list1[:] = [''.join(item).split(',') for item in list1] list2[:] = [''.join(item).split(',') for item in list2] for i, item in enumerate(list2): list1[i].append(item[-1]) &gt;&gt;&gt; pprint(list1) [['artur', '1/1/2018', '0.5', 'Estable'], ['paco', '1/1/2018', '2.11', 'Critico'], ['pepe', '1/1/2018', '11.2', 'Critico'], ['artur', '2/1/2018', '0.5', 'Estable'], ['paco', '2/1/2018', '2.11', 'Critico'], ['pepe', '2/1/2018', '11.2', 'Critico']]
has comment: http://stackoverflow.com/comment/83321204
score: 1
has comment: http://stackoverflow.com/comment/83321084
answers question: http://stackoverflow.com/q/48170089

http://stackoverflow.com/q/48146412
score: 1
upvote count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/83271305
has comment: http://stackoverflow.com/comment/83284833
type: Question
has comment: http://stackoverflow.com/comment/83285654
answer count: 1
downvote count: 0
has body: Hi I must implement a cnn, I'm new with Keras and Tensorflow so I'm apologizing if I'm making a mistake. This is what I do: the dataset is an numpy array (23, 4800000), #number of audio tracks x #number of samples. So I splitted the dataset in train (10, 4800000), validation (7, 4800000) and test (6, 4800000) The convolution process along the columns, so I must reshape the input in: X = np.expand_dims(train, axis=2) Y = np.expand_dims(valid, axis=2) The code for first part cnn is: cnn = Sequential() cnn.add(Conv1D(40, 80, input_shape=(4800000, 10))) cnn.add(MaxPooling1D(pool_size=2)) cnn.add(Conv1D(40, 8000)) cnn.add(MaxPooling1D(pool_size=20)) cnn.add(Flatten()) cnn.summary() _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv1d_1 (Conv1D) (None, 4799921, 40) 32040 _________________________________________________________________ max_pooling1d_1 (MaxPooling1 (None, 2399960, 40) 0 _________________________________________________________________ conv1d_2 (Conv1D) (None, 2391961, 40) 12800040 _________________________________________________________________ max_pooling1d_2 (MaxPooling1 (None, 119598, 40) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 4783920) 0 ================================================================= Total params: 12,832,080 Trainable params: 12,832,080 Non-trainable params: 0 _______________________________ cnn.compile(loss='mean_squared_error', optimizer='adam') cnn.fit(X,Y) And the error is: ValueError: Error when checking input: expected conv1d_3_input to have shape (None, 4800000, 10) but got array with shape (4800000, 10, 1) I don't really understand what it means, please someone could help me? So during these days I tried to simplify my work. X_train, X_valid = (7,7500,1), 7 number of tracks, 7500 samples and 1 channel y_train, y_valid = (7,7500), for each one of 7 track…
tagged with: keras
favorite count: 0
linked to: http://stackoverflow.com/q/48140989
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48146591
has title: ValueError: Error when checking target: expected dropout_82 to have 3 dimensions, but got array with shape (7, 7500)
tagged with: python
has comment: http://stackoverflow.com/comment/83271381

http://stackoverflow.com/q/48107347
has title: Is it better to schedule a python script via Task Scheduler or with code to run when needed?
tagged with: windows-task-scheduler
type: Question
upvote count: 2
tagged with: batch-file
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/56958865
favorite count: 0
has comment: http://stackoverflow.com/comment/83190244
has answer: http://stackoverflow.com/a/48107629
has comment: http://stackoverflow.com/comment/83190408
tagged with: python
type: UnansweredQuestion
score: 1
has body: So this is something I have been wondering for a while, and while I don't know if there is a correct answer there is probably a better option. So which of the options below is best to schedule a python script to run at a specific time? Let me know what you prefer, or if you have an alternative. 1) Take a python file script.py, write a ".bat" file to run the code in command prompt, and then use windows native task scheduler to launch the file at a specific time each day. BAT Example: cd C:\Users\Administrator\Documents\Scripts python script.py This is some code for a BAT file that will run your python script. 2) Use python to create a timed task within your file like some of the examples below: import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job) while 1: schedule.run_pending() time.sleep(1) or from datetime import datetime from threading import Timer x=datetime.today() y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0) delta_t=y-x secs=delta_t.seconds+1 def hello_world(): print "hello world" #... t = Timer(secs, hello_world) t.start() or from datetime import date from apscheduler.scheduler import Scheduler # Start the scheduler sched = Scheduler() sched.start() # Define the function that is to be executed def my_job(text): print text # The job will be executed on November 6th, 2009 exec_date = date(2009, 11, 6) # Store the job in a variable in case we want to cancel it job = sched.add_date_job(my_job, exec_date, ['text']) # The job will be executed on November 6th, 2009 at 16:30:05 job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text']) When it comes to option 2 there are plenty of examples I could include but I just want to know whats better in your opinion. Does one of the options use more processing power? Is one of the options more reliable? etc.

http://stackoverflow.com/q/48049087
answer count: 1
tagged with: string
has comment: http://stackoverflow.com/comment/83071689
tagged with: pandas
downvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/47769818
favorite count: 0
score: 8
upvote count: 9
has comment: http://stackoverflow.com/comment/83071695
has answer: http://stackoverflow.com/a/48049425
accepted answer: http://stackoverflow.com/a/48049425
has comment: http://stackoverflow.com/comment/83071834
has comment: http://stackoverflow.com/comment/83071915
type: AnsweredQuestion
has title: NLTK-based text processing with pandas
has comment: http://stackoverflow.com/comment/83071876
tagged with: dataframe
has body: The punctuation and numerical,lowercase are not working while using nltk. My code stopwords=nltk.corpus.stopwords.words('english')+ list(string.punctuation) user_defined_stop_words=['st','rd','hong','kong'] new_stop_words=stopwords+user_defined_stop_words def preprocess(text): return [word for word in word_tokenize(text) if word.lower() not in new_stop_words and not word.isdigit()] miss_data['Clean_addr'] = miss_data['Adj_Addr'].apply(preprocess) Sample Input 23FLOOR 9 DES VOEUX RD WEST HONG KONG PAG CONSULTING FLAT 15 AIA CENTRAL 1 CONNAUGHT RD CENTRAL C/O CITY LOST STUDIOS AND FLAT 4F 13-15 HILLIER ST SHEUNG HONG KONG Expected Output floor des voeux west pag consulting flat aia central connaught central co city lost studios flat f hillier sheung
type: Question
tagged with: nltk

http://stackoverflow.com/comment/83238169
comment on: http://stackoverflow.com/a/48128964
has text: This is the error I get now: TypeError: 'tuple' object does not support item assignment
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48070666
score: 1
has body: My trail uses 3 filters, rot90, np.where, np.sum, and np.multiply. I am not sure which way to benchmark is more reasonable. If you do not take into account the time to create filters, it is roughly 4 times faster. # Each filter basically does what `op` tries to achieve in a loop filter1 = np.array([[0, 1 ,0, 0, 0], [1, -4, 1, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) /5. filter2 = np.array([[0, 0 ,1, 0, 0], [0, 1, -4, 1, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) /5. filter3 = np.array([[0, 0 ,0, 0, 0], [0, 0, 1, 0, 0], [0, 1, -4, 1, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]]) /5. # only loop over the center of the matrix, a center = np.array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]]) filter1 and filter2 can be rotated to represent 4 filters individually. filter1_90_rot = np.rot90(filter1, k=1) filter1_180_rot = np.rot90(filter1, k=2) filter1_270_rot = np.rot90(filter1, k=3) filter2_90_rot = np.rot90(filter2, k=1) filter2_180_rot = np.rot90(filter2, k=2) filter2_270_rot = np.rot90(filter2, k=3) # Based on different index from `a` return different filter filter_dict = { (1,1): filter1, (3,1): filter1_90_rot, (3,3): filter1_180_rot, (1,3): filter1_270_rot, (1,2): filter2, (2,1): filter2_90_rot, (3,2): filter2_180_rot, (2,3): filter2_270_rot, (2,2): filter3 } Main function def get_new_a(a): x, y = np.where(((a &gt; 3) * center) &gt; 0) # find pairs that match the condition return a + np.sum(np.multiply(filter_dict[i, j], a[i,j]) for (i, j) in zip(x,y)) Note: There seem to be some numerical errors such that np.equal() would mostly return False between my result and OP's while np.close() would return true. Timing results def op(): temp_a = np.copy(a) for i in range(1,a.shape[0]-1): for j in range(1,a.shape[1]-1): if a[i,j] &gt; 3: temp_a[i+1,j] += a[i,j] / 5. temp_a[i-1,j] += a[i,j] / 5. temp_a[i,j+1] += a[i,j] / 5. temp_a[i,j-1] += a[i,j] / 5. temp_a[i,j] -= a[i,j] * 4. / 5. a2 = np.copy(temp_a) %timei…
answers question: http://stackoverflow.com/q/48055971
has comment: http://stackoverflow.com/comment/83116065
downvote count: 0
has comment: http://stackoverflow.com/comment/83115303
has comment: http://stackoverflow.com/comment/83115426
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/83115980
has comment: http://stackoverflow.com/comment/83115363

http://stackoverflow.com/comment/83259114
type: Comment
comment on: http://stackoverflow.com/q/48140587
type: QuestionComment
has text: @IMCoins Good point. I forgot about this feature of Python.
score: 0

http://stackoverflow.com/comment/83334349
comment on: http://stackoverflow.com/a/48163229
type: Comment
has text: That did it! Thank you!
score: 0
type: AnswerComment

http://stackoverflow.com/q/48026322
has answer: http://stackoverflow.com/a/48026968
has comment: http://stackoverflow.com/comment/83022331
tagged with: javascript
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/48026968
tagged with: web
tagged with: angularjs
type: Question
tagged with: python
score: 0
has body: Here is the scenario: I have a search page, with some form elements providing multiple filter conditions (something like 'advanced search'), and probably a nested ListView to display the search results in-place. What I would like to achieve: Whenever the user changes some filter conditions, the result list below responds in-place (taking another request for this could be accepted); When the user changes the sorting option, the results change their ordering immediately, without sending another request, either synchronous or by ajax. From the server side it would be as simple as changing the order_by attribute of a QuerySet, but I would like it in a front-end way. So I wonder if it is possible to achieve that. It seems to me that the filtered QuerySet could be somehow kept at the client side. Is it possible by pure Django using some mechanism like session? Or will it have to take some front-end frameworks such as AngularJS or Vue.js? Or is it not even possible (If so, is there any approach taking the minimal extra network payload?)
has title: How to re-sort search results in-place without having to re-send a request in django?
tagged with: django

http://stackoverflow.com/a/48026367
score: 2
has body: You can use itertools.product to generate the pairs, and then use ''.join to make them into strings. from itertools import product a = [1, 2, 3, 'a'] [''.join(x) for x in product(map(str, a), repeat=2)] gives us ['11', '12', '13', '1a', '21', '22', '23', '2a', '31', '32', '33', '3a', 'a1', 'a2', 'a3', 'aa']
answers question: http://stackoverflow.com/q/48026203
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/83095844
has text: You need to show ClaimSerializer; it is the serializer that is responsible for determining what fields are present in the output. (Note also, you shouldn't be defining the `list` method itself; you should define `get_queryset` to return the queryset only.)
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48061510
type: Comment

http://stackoverflow.com/comment/83229781
type: Comment
has text: According to the problem the code is right, the only mistake is the condition.
score: 0
comment on: http://stackoverflow.com/a/48126341
type: AnswerComment

http://stackoverflow.com/a/48077148
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48076288
accepted answer of: http://stackoverflow.com/q/48076288
type: Answer
downvote count: 0
has body: Reading the source here: https://github.com/apache/incubator-airflow/blob/master/airflow/contrib/operators/gcs_to_bq.py Please remove these parameters from the default arguments: google_cloud_storage_connn_id = 'podioGCPConnection' project_id = 'podio-data', You need to create a connection in the Airflow dashboard.
score: 3
upvote count: 3

http://stackoverflow.com/comment/83205539
has text: This operation will be done several times, not really often and usually for 100 MB up to 1GB file. And one time for 70GB file. Sequence and accession will be often repeated in a new file so unique constraint should take care about non-redundancy.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48110779
score: 0

http://stackoverflow.com/comment/83218224
comment on: http://stackoverflow.com/q/48120556
score: 1
has text: What do you mean by "no success" and "nothing"? Do you literally mean that you get no errors or warnings, but the browser doesn't load the new page?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48129409
has body: Note that I'm voting to close this as this question has been answered here. Basically you need to use django's conditional expressions Case and When. Here is a quick example of how this could look: from django.db.models import Count, Case, When # ... Skill.objects.annotate( num_porjects=Count(Case( When(project__user_id=user.id, then=1), output_field=CharField(), )) )
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48129155
type: Answer
accepted answer of: http://stackoverflow.com/q/48129155

http://stackoverflow.com/comment/83027193
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48028536
has text: Try removing it first?
score: 0

http://stackoverflow.com/a/48052644
type: AcceptedAnswer
type: Answer
has body: In the first example, consumer_handler listens for the messages from a websocket connection. It then passes the messages to a consumer. In its simplest form, a consumer can look like this: async def consumer(message): # do something with the message In the second example, producer_handler receives a message from a producer and sends it to the websocket connection. A producer can look like this: async def producer(): message = "Hello, World!" await asyncio.sleep(5) # sleep for 5 seconds before returning message return message
upvote count: 2
downvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48052506
has comment: http://stackoverflow.com/comment/83077944
accepted answer of: http://stackoverflow.com/q/48052506

http://stackoverflow.com/a/48082199
has comment: http://stackoverflow.com/comment/83138950
score: 0
accepted answer of: http://stackoverflow.com/q/48082018
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48082018
has body: Try this: words = ['wan', 'floor', 'street'] similar = [[item[0] for item in model.most_similar(word)[:5]] for word in words] df = pd.DataFrame({'Word': words, 'Similar Words': similar})
type: Answer

http://stackoverflow.com/comment/83078875
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48053207
has text: The first line of your code is counter = True. You have to make sure that is outside of the loop, otherwise counter will be set to True every time through the loop.
score: 0

http://stackoverflow.com/a/48133124
upvote count: 24
accepted answer of: http://stackoverflow.com/q/48132786
has comment: http://stackoverflow.com/comment/116605298
has body: My guess would be the analytics that give this warning are not sharp enough. The value type for game_data = {'boats': [], 'width': None, 'height': None} can not be determined. The first "real" value you put in is an int: w = 12 game_data = {'boats': [], 'width': None, 'height': w} So PyCharm assumes that this is a dict(string-&gt;int). Then you add a inner dict as value to your empty list: game_data['boats'].append({'name': None}) So now it has a dict(string->int) that suddenly gets to be a mixed thing and warns you. Thats about the same as what What does this warning in PyCharm mean? is about: adding int into a list of strings using pycharm as IDE. As to how to get rid of the warning: Jetbrains Resharper is very configurable, I guess pycharm will be as well. This documentation https://www.jetbrains.com/help/pycharm/configuring-inspection-severities.html#severity might help you configure the severity down - if not I am sure the support of Jetbrains is eager to help you out - they were whenever I had problems using resharper.
type: Answer
downvote count: 0
score: 24
has comment: http://stackoverflow.com/comment/110024641
answers question: http://stackoverflow.com/q/48132786
type: AcceptedAnswer

http://stackoverflow.com/comment/83175999
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48097653
has text: I tried conda, gave the same error. I was able to go into the anaconda navigator and go to my environment and download it from there. I'll respond with that answer

http://stackoverflow.com/comment/83212528
type: Comment
type: QuestionComment
has text: after fixing indentions and adding `root.mainloop() (and changes with grid to see full treeview) I works for me without problems.
score: 0
comment on: http://stackoverflow.com/q/48117575

http://stackoverflow.com/comment/83146383
has text: _doesn't really work how I thought it would_ Please explain what you want it to do, and what it's doing instead. Don't just tell us "it isn't working".
type: Comment
comment on: http://stackoverflow.com/q/48085644
type: QuestionComment
score: 1

http://stackoverflow.com/comment/83069575
has text: Please check the answer and use it in python and let me know your feedback
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48048663

http://stackoverflow.com/comment/83196645
type: QuestionComment
has text: @Tomalak Thank you. Edited the question.
score: 0
comment on: http://stackoverflow.com/q/48109515
type: Comment

http://stackoverflow.com/a/48021955
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48021226
downvote count: 0
has body: I did it... import cv2 import numpy as np import os image = cv2.imread('box.png') path, filename = os.path.split('box.png') filename = (filename[:-4]) root_path = 'C:\\Users\\Link\\Desktop\\' h = image.shape[0] w = image.shape[1] mask_l = np.zeros(image.shape[:2], dtype="uint8") roi = cv2.rectangle(mask_l, (w//2, 0), (0, h), 255, -1) # LEFT MASK masked_l = cv2.bitwise_and(image, image, mask=mask_l) list = ['a', 'b'] for i in enumerate(masked_l): x, y, w, h = cv2.boundingRect(mask_l) roi_l = image[y:y + h, x:x + w] cv2.imwrite(root_path + str(filename) + '{}.png'.format(lista[0]), roi_l) cv2.imshow("Left", roi_l) cv2.waitKey(0) h2 = image.shape[0] w2 = image.shape[1] mask_r = np.zeros(image.shape[:2], dtype="uint8") cv2.rectangle(mask_r, (w2//2, 0), (w2, h2), 255, -1) # RIGHT MASK masked_r = cv2.bitwise_and(image, image, mask=mask_r) for i_i in enumerate(masked_r): x2, y2, w2, h2 = cv2.boundingRect(mask_r) roi_r = image[y2:y2 + h2, x2:x2 + w2] cv2.imwrite(root_path + str(filename) + '{}.png'.format(lista[1]), roi_r) cv2.imshow("Right", roi_r) cv2.waitKey(0)

http://stackoverflow.com/q/48127619
tagged with: python
has comment: http://stackoverflow.com/comment/83231876
type: Question
has comment: http://stackoverflow.com/comment/83231877
has body: So I am trying to create a python script to automate filling in forms My script is this : import mechanize import re br = mechanize.Browser() interletter = "https://www.w3schools.com/html/html_forms.asp" br.open(interletter) for link in br.links(): targel_url = "https://www.w3schools.com/html/html_forms.asp" if interletter == targel_url: print "Form found!" br.select_form(nr=0) br.select_form(name="FirstName")= "Josiah" br.select_form(name="LastName")= "Loh" result = br.submit() The website which I used to test is this: https://www.w3schools.com/html/html_forms.asp May I know why did the error pop up and how can I solve it?
has answer: http://stackoverflow.com/a/48128619
has title: Mechanize , SyntaxError: can't assign to function call
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/83301001
type: QuestionComment
has text: In that case: https://stackoverflow.com/questions/6832554/python-multiprocessing-how-do-i-share-a-dict-among-multiple-processes
comment on: http://stackoverflow.com/q/48160702
score: 0
type: Comment

http://stackoverflow.com/q/48060582
has body: I need to send a simple form to a remote server using POST method with python. This form is a bit strange... some fields name are repeated without using the [] but only passing the key=value pair (this is a requisite otherwise the process on server side doesn't work!). Below an example of the original form: &lt;form method="post" action="/remote/test.php"&gt; &lt;input type=hidden name="value01" value="7777" size="12" maxlength=20&gt; &lt;input type="text" name="value02" value="123456789"&gt; &lt;input type="text" name="value03" value="A1234"&gt; &lt;input type="text" name="value04" value="B5678"&gt; &lt;input type=submit value="value05 " class="button"&gt; &lt;input type="hidden" name="VALUE00" value="9999"&gt; &lt;input type=hidden name="VALUE99"value="09.01.2015 14:52:40"&gt; &lt;input type="hidden" name="LIST" value="D0000000033039"&gt; &lt;input type="hidden" name="LIST" value="D0000000033039"&gt; &lt;input type="hidden" name="LIST" value="C0000000032032"&gt; &lt;input type="hidden" name="LIST" value="X0000000031820"&gt; &lt;/form&gt; I use "Requests" and as per the documentation, i can pass a dictionary for sending post parameters. So i implement below code. The real data that fill the sourceDataList variable are read from a text file with a windows EOL (CR+LF), so to "emulate" the file for this example, i compile a list with some value similar to real values that are present in the file import re sourceDataList = [ '2017-12-20 08:59:17;Value01\r\n', '2017-12-20 08:59:18;Value02\r\n', '2017-12-20 08:59:20;Value03\r\n', '2017-12-20 08:59:21;Value04\r\n' ] dataList = []; for line in sourceDataList: dataList.append({'RESULT' , re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip())}); print dataList; The problem start here.. when I print the dataList I discover that the data are "mixed" in a strange way.. sometime there is a swap between key and value! as example, the code above produce below result: [ set(['Value01', 'RESULT']), set(['RESULT', 'Value02']), set([…
has comment: http://stackoverflow.com/comment/83093884
tagged with: forms
tagged with: post
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48060637
upvote count: 1
downvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/48060637
has comment: http://stackoverflow.com/comment/83094314
accepted answer: http://stackoverflow.com/a/48073070
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has title: python send http request with multiple parameters with same name
has answer: http://stackoverflow.com/a/48073070
tagged with: request
type: Question

http://stackoverflow.com/q/48053484
tagged with: matplotlib
tagged with: pyqt5
linked to: http://stackoverflow.com/q/12459811
type: Question
has body: I trying to make an GUI application that takes a video (video from a mechanical compression test), apply some image processing and gives in real time the plotting result and the value of a mechanical coefficient (poisson coefficient). I already manage to have the GUI in PYQT5 with upload and launch button, and the result of the video processing. What I'm now trying to do and didn't manage, is to plot simultaneously the result of a computation. My architecture code is as follow: Stylesheet.py Content colors, background, icon, and geometry uiQT.py Contents the definition of all Widgets and the setup of the UI. MainQT.py Main program, inits the GUI and all the functions. Above is my code uiQT and MainQT, if someone would be so kind to helps me. I've tried following several tutorials, (here,here, and here) but nothing seems to works. uiQT.py from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure import matplotlib.pyplot as plt from stylesheet import colors, dimension, ressources class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") Mainx=dimension["MainWinSize"][0] Mainy=dimension["MainWinSize"][1] left = (int(QtWidgets.QDesktopWidget().screenGeometry().width()) - Mainx) /2 top = (int(QtWidgets.QDesktopWidget().screenGeometry().height()) - Mainy) /2 MainWindow.setGeometry(left, top, Mainx, Mainy) #Main Centralwidget MainWindow.setStyleSheet(colors["MainBackGr"]) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setStyleSheet(colors["EmptyBackGr"]) self.centralwidget.setObjectName("centralwidget") #button to upload video self.browse_button = QtWidgets.QPushButton(self.centralwidget) self.browse_button.setIcon(QtGui.QIcon(ressources["UploadBtnNormal"])) self.browse_button.setIconSize(QtCore.QSize(dimension["UploadBtnSize"][0],dim…
has title: PYQT5 dynamic plot in main window
score: 0
linked to: http://stackoverflow.com/q/34622537
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83281826
tagged with: python
has comment: http://stackoverflow.com/comment/83099624

http://stackoverflow.com/q/48149135
has comment: http://stackoverflow.com/comment/83276895
has comment: http://stackoverflow.com/comment/83276533
has answer: http://stackoverflow.com/a/48149657
has body: I have a file that I can read like this: filein= open('/path/datasets.txt', 'r') print filein.read() "V1" "V2" "V3" "V4" "V5" "V6" "V7" "V8" "V9" "1" "ABCD" "ABCD" "Adam" "29" "591" "25" "54" "25" "NH" "2" "ABCD" "ABCD" "Alex" "481" "26" "75" "54" "25" "NH" Then use some formation from this file in my code: Import ……. res = data.read(29,591) # res = data.read(V4 [1],V5 [1]) fileout = open('filename_29_591.txt', 'w') # 'filename_V4 [1]_V5 [1].txt fileout.write(res.to_string()) fileout.close() What I need is to read first line in my filein then take V4 [1], V5 [1] values and use them in the code and then in output. Do the same for the second line (V4 [2], V5 [2]) and for all lines (make a loop). res = data.read(481,26) # res = data.read(V4 [2], V5 [2]) fileout = open('filename_481_26.txt', 'w') # 'filename_V4 [2]_V5 [2].txt fileout.write(res.to_string()) fileout.close() I am pretty new to Python so sorry if the question seems simple to do. my outputs (saved) are: filename_29_591.txt filename_481_26.txt
possible better answer: http://stackoverflow.com/a/48149367
has comment: http://stackoverflow.com/comment/83276715
has comment: http://stackoverflow.com/comment/83277209
has answer: http://stackoverflow.com/a/48149367
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48149657
type: Question
answer count: 2
upvote count: 1
tagged with: python
has title: How to take information from a file to python?
has comment: http://stackoverflow.com/comment/83276517

http://stackoverflow.com/q/48144684
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/48147274
score: 1
upvote count: 1
has title: Rounding down datetime column by the hour
type: Question
has answer: http://stackoverflow.com/a/48144775
has answer: http://stackoverflow.com/a/48148276
tagged with: dataframe
tagged with: date
has body: 11/22/2017 10:00 14.442473 11/22/2017 10:05 19.446146 11/22/2017 10:10 49.382300 11/22/2017 10:15 51.216980 11/22/2017 10:20 50.674092 11/22/2017 10:25 14.893244 11/22/2017 10:30 27.191617 11/22/2017 10:35 19.826802 11/22/2017 10:40 9.996578 11/22/2017 10:45 7.929272 11/22/2017 10:50 22.770500 11/22/2017 10:55 32.611105 Suppose i have data like above, my output for all the column A should be: 11/22/2017 10:00, roundup function won't work, as time after 10:30 are considered as 11:00, hence need help to ignore the minutes &amp; seconds to get my exact data ready for further analysis.
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48084451
has title: Creating new pandas columns with original value plus random number in error range
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
has body: I have a pandas dataframe which has a column 'INTENSITY' and a numpy array of same length containing the error for each intensity. I would like to generate columns with randomly generated numbers in the error range. So far I use two nested for loops to create the new columns but I feel like this is inefficient: theor_err = [ sqrt(abs(x)) for x in theor_df[str(INTENSITY)] ] theor_err = np.asarray(theor_err) for nr_sample in range(2): sample = np.zeros(len(theor_df[str(INTENSITY)])) for i, error in enumerate(theor_err): sample[i] = theor_df[str(INTENSITY)][i] + random.uniform(-error, error) theor_df['gen_{}'.format(nr_sample)] = Series(sample, index=theor_df.index) theor_df.head() Is there a more efficient way of approaching a problem like this?
has answer: http://stackoverflow.com/a/48084823
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/48084692
upvote count: 0
score: -1
tagged with: pandas

http://stackoverflow.com/a/48022364
score: 0
type: Answer
has body: Pandas supports timestamp to datetime out-of-the-box: import pandas as pd dataframename['datetime'] = pd.to_datetime(dataframename['columnname'], unit='ms') In case you have multiple columns: # processing the UNIX timestamps into readable dates (pandas datetime): ts_cols = dataframename.select_dtypes(['datetime']).columns for col in ts_cols: dataframename['%s' % col] = pd.to_datetime(dataframename['%s' % col], unit='ms') The performance gain for using the pandas' to_datetime over external date - it's 2x faster on small dataset, and it'd scale.
answers question: http://stackoverflow.com/q/48019561

http://stackoverflow.com/a/48074307
has body: You can do by overriding save from django.contrib.auth.hashers import make_password class RegisterForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email', 'password'] username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'placeholder': 'Username:'})) email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'placeholder': 'Email:'})) password = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'placeholder': 'Password:'})) def save(self, commit=True): instance = super(RegisterForm, self).save(commit=False) if instance.password: instance.password = make_password(instance.password) if commit: instance.save() return instance
has comment: http://stackoverflow.com/comment/83122239
score: 0
answers question: http://stackoverflow.com/q/48073923
type: Answer

http://stackoverflow.com/comment/83132221
has text: @SK If this solution helped you, you mind [accepting](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work?answertab=votes#tab-top) by checking this answer. Thank you.
comment on: http://stackoverflow.com/a/48071018
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83136499
comment on: http://stackoverflow.com/q/48076753
type: Comment
type: QuestionComment
has text: https://github.com/dask/dask/issues/2690 Looks like you have to use [dask.array.sqrt](http://dask.pydata.org/en/latest/array-api.html?highlight=sqrt#dask.array.sqrt) instead of `np.sqrt`
score: 2

http://stackoverflow.com/a/48135519
answers question: http://stackoverflow.com/q/48134966
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48134966
has body: Do you have the objects actually created in the DB? There's some info missing in the post (like the Form itself, etc), anyway: If you didn't set the related_name argument on the foreign key, the correct access to post's comments is via post.comment_set.all(), see: https://docs.djangoproject.com/en/2.0/topics/db/queries/#following-relationships-backward May I point out that you're doing a lot of work, that Django's generic views can do for you (guess it's OK if you're learning, otherwise, it's just more code to maintain). Things like CreateView, UpdateView, and DeleteView from django.views.generic.edit. For more info see: https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-editing/#model-forms
type: Answer

http://stackoverflow.com/a/48056152
type: AcceptedAnswer
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/48055704
has comment: http://stackoverflow.com/comment/83112847
answers question: http://stackoverflow.com/q/48055704
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/83105072
has body: A Keras Conv2d layer automatically has n input channels for its convolutional filters, where n is the depth / number of channels of the layer before it. This preceding layer feeds as input data into the Conv2d layer. Assumptions likes these make Keras easier to use for common use cases like chaining together Conv2ds in deep convolutional networks.

http://stackoverflow.com/comment/83129758
type: QuestionComment
has text: Can I politely ask what is the point of this question. As soon as completely acceptable and working answers are given, you modify the question and explain you do not actually want any of these answers, but something else instead.
comment on: http://stackoverflow.com/q/48077849
score: 0
type: Comment

http://stackoverflow.com/comment/83577910
type: Comment
comment on: http://stackoverflow.com/q/48143566
score: 0
has text: @JamesKent I am importing a class from `execute.py`. Should I just combine the two files into one then create the executable out of that?
type: QuestionComment

http://stackoverflow.com/comment/83147535
score: 2
comment on: http://stackoverflow.com/q/48086236
type: QuestionComment
type: Comment
has text: You're hardcoding what looks like variable names into the string, so when you do `"INSERT INTO... (Date)"` you're inserting the string `"Date"`, not the value of your `Date` variable. I think your `'''` have *gone too far* **:-)**

http://stackoverflow.com/comment/83275956
score: 0
has text: @TomášCerha thank's for your answer. I updated my question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48148619

http://stackoverflow.com/q/48015074
has answer: http://stackoverflow.com/a/48018151
has body: I have a site that makes an AJAX post to a Flask route. I know there are many similar questions (please don't mark as duplicate) that use the AJAX success method to handle the response. That would work in my simplified example, but the route in my actual code is pulling a bunch of data from a database that gets rendered to multiple tables. I'd prefer not to rewrite all the table data updates in JavaScript, so I really just need to re-render the template. python: from flask import Flask, render_template, request app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def hello_world(message=None): return render_template('test.html', message=message) app.run() html {{ message }} Click Me!
type: AnsweredQuestion
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/48015166
accepted answer: http://stackoverflow.com/a/48015166
tagged with: javascript
has title: flask render_template doesn't work on AJAX post
score: 5
answer count: 3
tagged with: jquery
tagged with: flask
possible better answer: http://stackoverflow.com/a/50798412
favorite count: 0
tagged with: ajax
has answer: http://stackoverflow.com/a/50798412
upvote count: 5
tagged with: python

http://stackoverflow.com/comment/83031482
type: QuestionComment
comment on: http://stackoverflow.com/q/48021091
type: Comment
has text: BTW: based on [image in documentation](https://doc.scrapy.org/en/latest/topics/architecture.html) you should have to replace "downloader" to use only Selenium - and this can be a problem.
score: 0

http://stackoverflow.com/comment/83221520
has text: It works. Issue was 'inplace' was not in the drop.
comment on: http://stackoverflow.com/q/48122105
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48057768
answers question: http://stackoverflow.com/q/48057694
has comment: http://stackoverflow.com/comment/83087932
has comment: http://stackoverflow.com/comment/83087852
type: Answer
has comment: http://stackoverflow.com/comment/83087902
upvote count: 5
has body: You could use a simple or ternary if-else: slc = a[:] if len(a) == 1 else a[:-1]
has comment: http://stackoverflow.com/comment/83087907
has comment: http://stackoverflow.com/comment/83087961
downvote count: 0
score: 5

http://stackoverflow.com/comment/83164629
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48094708
has text: @Lafexlos that is not the intended behviour for the final script, but it was a problem I was going to research and tackle next
score: 0

http://stackoverflow.com/comment/83106071
comment on: http://stackoverflow.com/a/48065031
type: AnswerComment
score: 0
has text: It works !! thank you ...it had reverse 'decimal' and 'sep'.
type: Comment

http://stackoverflow.com/comment/83210384
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48116496
has text: You are right, I'll edit the question to "binary" vectors. Thanks. Also @Divakar is right with the same appreciation.

http://stackoverflow.com/a/48097401
has body: I think it would be better for you to create small NodeJS/Express server just as a web server for your React app. It will live separately on your REST API for which you can keep Phyton. If I may recommend create-react-app is perfect for client side apps, but try to look into Next.js for server side rendered apps.
answers question: http://stackoverflow.com/q/48096177
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/48168100
has body: I don't see any error as such in your code block. But as you are using anaconda3 a simple solution would be to induce WebDriverWait for the Search Box on https://google.de to be clickable as follows : 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 browser = webdriver.Ie() browser.get('https://google.de') elem = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.NAME, "q")))
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48167037
answers question: http://stackoverflow.com/q/48167037
type: Answer

http://stackoverflow.com/a/48049961
answers question: http://stackoverflow.com/q/48049947
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48049947
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83071869
type: Answer
has comment: http://stackoverflow.com/comment/83071796
downvote count: 0
has comment: http://stackoverflow.com/comment/83071811
score: 6
has body: Lists are mutable in Python and passed by reference. Whenever you assign it or pass it as an argument, a reference to it is passed and not a copy. Hence the outcome you're seeing. If you really want to mutate it, you need to deepcopy it. import copy class test(): def __init__(self, data): self.data = copy.deepcopy(data) self.data2 = copy.deepcopy(data2) # if the list is going to be flat and just contain basic immutable types, # slicing (or shallow-copy) would do the job just as well. class test(): def __init__(self, data): self.data = data[::] # or data[:] for that matter as @Joe Iddon suggested self.data2 = data[::] Note: not all types of objects support "deep-copying".

http://stackoverflow.com/comment/126262979
has text: I don't think so unless you want to write your own interface to AWS. `boto3` is the defacto python SDK for AWS services and other libraries like `s3fs` just wrap it.
comment on: http://stackoverflow.com/a/69703393
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83264557
has text: no, tds isn't empty example: [ 200 , -1 , MC Gudan - Boca de Pêlo , 9 , 144 , , 350,693 , -2,742 , 3,455,285 ]
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48143126
score: 0

http://stackoverflow.com/q/48124984
tagged with: python
has body: Lets say I have 3 different dataframe which I am generating the dataframe in looping. So currently I am converting the data frame to excel file. I am able to convert only one data frame to excel. But I need to update all the 3 dataframes with different data should be appended one after the other in excel file. How can I achieve that? Is it possible to do? My Current code. I am converting different dataframe to different sheets of the excel file. Note: I need to append to only one excel sheet. for itr in range(0,3): df["users"] = UserArray for action in range(len(ColumnName)): Array = [] for user in range(int(usercount)): #calling Copylogs function to copy the required logs and actions in script into another file Array.append(CopyLogs(abs_read_path,itr+1,user+1,ColumnName[action])) Array1 = AverageStatistics(Array) df[ColumnName[action]] = Array1 print df print "\n" df.to_excel(writer,sheet_name="TimeStampsOfItr="+str(itr+1)) writer.save()
has title: How to update the same excel sheet with different dataframe without overwriting the previous data present in excel file using python2.7.14?
has comment: http://stackoverflow.com/comment/83281388
favorite count: 0
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: excel
has answer: http://stackoverflow.com/a/48125019
has comment: http://stackoverflow.com/comment/83289703
tagged with: dataframe
linked to: http://stackoverflow.com/q/36465746
type: Question
answer count: 1
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/83226899

http://stackoverflow.com/comment/83088941
type: QuestionComment
has text: So far, no, I have not been able to work this out. Hopefully somebody with expertise in TensorFlow will be able to provide some assistance.
score: 0
comment on: http://stackoverflow.com/q/48043459
type: Comment

http://stackoverflow.com/comment/83298548
type: Comment
type: QuestionComment
has text: So I just tested it and the change is not permanent.
score: 0
comment on: http://stackoverflow.com/q/48159413

http://stackoverflow.com/q/48023131
answer count: 1
has answer: http://stackoverflow.com/a/48023280
has title: Mail traffic between MailDev container and Django container delivers Errno 111] Connection refused
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48023280
tagged with: docker
type: Question
tagged with: python
has body: Mail traffic between MailDev container and Django container delivers [Errno 111] Connection refused Email traffic to console backend works, so the function should be correct. send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False ) After I switched to SMTP backend and started MailDev in Container, I got: [Errno 111] Connection refused in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' in Shell: sudo docker run -p 1080:80 -p 1025:25 --name maildev djfarrelly/maildev My Docker Containers are: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a46040dd1259 djfarrelly/maildev "bin/maildev --web..." 11 seconds ago Up 9 seconds 0.0.0.0:1025-&gt;25/tcp, 0.0.0.0:1080-&gt;80/tcp maildev 4fed036f92d4 exposee "/usr/src/start.sh" 42 minutes ago Up 42 minutes 0.0.0.0:8000-&gt;8000/tcp exposee 2c2cf7ce19e9 winauth "gunicorn -b 0.0.0..." 43 minutes ago Up 43 minutes 127.0.0.1:9876-&gt;9876/tcp winauth afe4a449aa01 postgres "docker-entrypoint..." 44 minutes ago Up 44 minutes 127.0.0.1:5432-&gt;5432/tcp postgres My Settings in settings.py are: EMAIL_HOST = CONFIG.get('EMAIL_HOST', '127.0.0.1') EMAIL_PORT = CONFIG.get('EMAIL_PORT', 1025) EMAIL_USE_TLS = CONFIG.get('EMAIL_USE_TLS', False) EMAIL_USE_SSL = CONFIG.get('EMAIL_USE_SSL', False) My Configuration in config.json is: "EMAIL_HOST": "127.0.0.1", "EMAIL_PORT": 1025, "EMAIL_USE_TLS": false, "EMAIL_USE_SSL": false
tagged with: django
upvote count: 1

http://stackoverflow.com/q/48088283
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83151445
has answer: http://stackoverflow.com/a/48724553
has title: TypeError: long() argument must be a string or a number, not 'NoneType'
has body: I've been following this tutorial that teaches you how to build a program that recognises objects in a video from your webcam using TensorFlow Object Recognition https://www.youtube.com/watch?v=MyAOtvwTkT0 My code throws this error: Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 Traceback (most recent call last): File "detecting_image_from_vids.py", line 135, in &lt;module&gt; feed_dict={image_tensor: image_np_expanded}) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 889, in run run_metadata_ptr) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1089, in _run np_val = np.asarray(subfeed_val, dtype=subfeed_dtype) File "/usr/local/lib/python2.7/dist-packages/numpy/core/numeric.py", line 531, in asarray return array(a, dtype, copy=False, order=order) TypeError: long() argument must be a string or a number, not 'NoneType' Question: Can anyone help me decipher it? This is the code that I'm trying to run: import numpy as np import os import six.moves.urllib as urllib import sys import tarfile import tensorflow as tf import zipfile from collections import defaultdict from io import StringIO from matplotlib import pyplot as plt from PIL import Image import cv2 cap = cv2.VideoCapture(1) # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # ## Object detection imports # Here are the imports from the object detection module. # In[3]: from utils import label_map_util from utils import visualization_utils as vis_util # # Model preparation # ## Variables # # Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file. # # By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/object_detection/g3doc/detection_model_zoo.md) for a list of oth…
tagged with: python
tagged with: object-detection
tagged with: command-line
type: UnansweredQuestion
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/83151457
type: Question
has answer: http://stackoverflow.com/a/53035201

http://stackoverflow.com/comment/83171421
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48067935
has text: @tripleee, thanks for your comment. It helped me find the solution
type: AnswerComment

http://stackoverflow.com/comment/83005103
type: QuestionComment
comment on: http://stackoverflow.com/q/48018081
has text: Try `images = ImageUploaded.objects.filter(offer__end_date__gt=date.today())`
score: 1
type: Comment

http://stackoverflow.com/a/48055508
has body: The behavior you're asking about ("How the template know which restaurant I want to show") is view behavior, not template behavior. The template renderer gets passed a restaurant value by the view. The view has no (explicit) return because it's a class-based view - a subclass of DetailView, in particular. DetailView itself inherits standard methods that this view does not override to accept a PK parameter and load a particular instance. You can read the source code for DetailView to get more of a sense of what's going on, if you like, eg https://github.com/django/django/blob/master/django/views/generic/detail.py - but class-based views are a bit of an advanced topic, and not every project will even use them. I'd focus on other areas first.
type: Answer
answers question: http://stackoverflow.com/q/48055255
upvote count: 1
downvote count: 0
score: 1

http://stackoverflow.com/q/48165235
has answer: http://stackoverflow.com/a/48266454
linked to: http://stackoverflow.com/q/48245128
has comment: http://stackoverflow.com/comment/83310733
has comment: http://stackoverflow.com/comment/83310390
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83309759
tagged with: recursion
has title: Recursion removing list elements Python
has comment: http://stackoverflow.com/comment/83475811
has comment: http://stackoverflow.com/comment/83311753
has comment: http://stackoverflow.com/comment/83309819
has comment: http://stackoverflow.com/comment/83310202
type: Question
has comment: http://stackoverflow.com/comment/83311147
has answer: http://stackoverflow.com/a/48165449
has comment: http://stackoverflow.com/comment/83310466
has body: need to write a recurive function to remove elements of list but keep the arrays in the result such as. def remove_words(listx): for element in listx: if isinstance(element, list): remove_words(element) else: listx.remove(element) return listx remove_words(["a", "b", ["c"]]) would return [[]] My code returns ["b",[]] for some reason it's missing an element.
score: 0
tagged with: tail-recursion
answer count: 2

http://stackoverflow.com/a/48088791
has body: use the apply method on the dataframe. # change this function according to your needs def dedup(row): return list(set(row.y)) df['deduped'] = df.apply(dedup, axis=1)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48088686

http://stackoverflow.com/comment/139098638
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/67953106
has text: Thanks for the heads up; `import sys` added to the answer

http://stackoverflow.com/comment/83115593
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48070963
score: 0
has text: Im not sure, they arnt in the real code, so it must be a typo.

http://stackoverflow.com/comment/83267946
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48144866
type: AnswerComment
has text: I am getting the below error when I use your code `ValueError: Bin labels must be one fewer than the number of bin edges`

http://stackoverflow.com/a/48051086
upvote count: 2
has body: Use get_dummies with prefix and prefix separator as empty strings i.e pd.get_dummies(df,prefix='',prefix_sep='').groupby(level=0, axis=1).max() # Thanks @ coldspeed Cat Chicken Dog Fish 0 1 1 0 0 1 0 1 0 1 2 1 0 0 1 3 1 1 0 0 4 1 0 1 0
has comment: http://stackoverflow.com/comment/83075129
downvote count: 0
answers question: http://stackoverflow.com/q/48050998
type: Answer
score: 2

http://stackoverflow.com/q/48105991
tagged with: ignore-case
has title: How to ignore case when filter value in database with python
answer count: 1
tagged with: flask-sqlalchemy
favorite count: 0
duplicate of: http://stackoverflow.com/q/16573095
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I've tried to find an answer of my question. And I find some answers but I don't know how to apply those to my question. I'm using flask sqlalchemy. This is my python code for getting product list. def get_products(cls, request): with gshop.session_scope() as session: products = session.query(Product.id, Product.product_name, Product.logo_img_id, Product.product_cat_id, Product.display_no, Product.brand_id) if 'query' in request: query = json.loads(request['query']) filters = query['filters'] for key, value in filters.items(): try: products = products.filter(getattr(Product, key).like("%" + str(value) + "%")) except AttributeError: pass 'request' parameter is the 'param' from http request of client. print(request) looks like this. { 'query': '{ "filters":{ "product_name":"aBcDeFgH" } } } When I tried to search product by name 'aBcDeFgH', I want to get all data which includes this keyword with ignoring case. How can I do this? If you have any link or idea, just throw that to me. Then I'll try a new way with referenced. Thanks in advance, and Happy New Year. :)
score: 1
linked to: http://stackoverflow.com/q/16573095
downvote count: 1
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/48107252
tagged with: database

http://stackoverflow.com/q/48085752
tagged with: memory
type: Question
has comment: http://stackoverflow.com/comment/83146750
tagged with: disk
has title: Python - size of object in memory vs. on disk
has answer: http://stackoverflow.com/a/48085790
accepted answer: http://stackoverflow.com/a/48085790
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/449560
tagged with: pickle
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has body: Here is my example: import numpy as np test = [np.random.choice(range(1, 1000), 1000000) for el in range(1,1000)] this object takes in memory: print(sys.getsizeof(test)/1024/1024/1024) 8.404254913330078e-06 something like 8 KB When I write it to disk import pickle file_path = './test.pickle' with open(file_path, 'wb') as f: pickle.dump(test, f) it take almost 8GB from ls -l command Could somebody clarify why it take so little space in memory and some much on disk? I am guessing in memory numbers are not accurate.
tagged with: file

http://stackoverflow.com/comment/83201678
score: 0
has text: It s not good. It means 1. some regex problem, because not escaped character in key of dictinary. 2. some value in column `Postal_Addr` with bad data. And not easy find it, because data related issue :(
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48112468

http://stackoverflow.com/q/48141324
has comment: http://stackoverflow.com/comment/83260682
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83260796
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48141761
downvote count: 0
has body: I'm trying to see whether or not a value entered in the Entry widget is stored inside the StringVar() object but when I print the length of the string value object, it says 0. class POS(tk.Tk): def __init__(self,*args,**kwargs): tk.Tk.__init__(self, *args, **kwargs) """ some code to build multiple frames here """ class MainPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) frame5 = Frame(self, bg = "pink") frame5.pack(fill = BOTH) frame5Label1 = tk.Label(frame5, text = "Product Bar Code", font = NORMAL_FONT) frame5Label1.grid(row = 0, column = 0, padx=5, pady=5, sticky = W) barCode = StringVar() frame5EntryBox = ttk.Entry(frame5, textvariable = barCode, width = 40) frame5EntryBox.grid(row = 0, column = 1, padx = 5, pady = 5) frame5Button = ttk.Button(frame5, text = "Add Item", command = lambda: updateCustomerList(barCode)) frame5Button.grid(row = 0, column = 2, padx = 130, pady = 10) def updateCustomerList(barCode): print(len(barCode.get())) app = POS() app.geometry("700x700") app.resizable(False,False) app.mainloop()
has comment: http://stackoverflow.com/comment/83260808
has comment: http://stackoverflow.com/comment/83261324
answer count: 1
tagged with: tkinter-entry
has title: Tkinter: Entry box value doesn't store into StringVar() object
accepted answer: http://stackoverflow.com/a/48141761
favorite count: 0
has comment: http://stackoverflow.com/comment/83261233
tagged with: python
has comment: http://stackoverflow.com/comment/83261840

http://stackoverflow.com/a/48145353
has comment: http://stackoverflow.com/comment/83293479
upvote count: 3
has comment: http://stackoverflow.com/comment/83268715
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83268861
type: Answer
has comment: http://stackoverflow.com/comment/83268771
score: 3
has body: Perhaps the problem is with the index_col paramter, why not set the index after reading the csv. i.e li = [pd.read_csv(f, dtype={d:object for d in sch_inx }).set_index(sch_inx) for f in files] main_df = reduce(lambda left,right: pd.DataFrame.combine_first(left,right),li) Lets take an example for preserving the leading zeroes i.e amount donorID recipientID year 0 0100 101 11 2014 1 0200 101 11 2014 2 0500 101 21 2014 3 0200 102 21 2014 # Copy the above dataframe sch_ind = ['amount','donorID'] df = pd.read_clipboard(dtype={d:object for d in sch_ind}).set_index(sch_ind) print(df) recipientID year amount donorID 0100 101 11 2014 0200 101 11 2014 0500 101 21 2014 0200 102 21 2014 If it works with clipboard it works with csv too.
has comment: http://stackoverflow.com/comment/83268793
has comment: http://stackoverflow.com/comment/83268837
has comment: http://stackoverflow.com/comment/83268701
answers question: http://stackoverflow.com/q/48145027
accepted answer of: http://stackoverflow.com/q/48145027

http://stackoverflow.com/comment/92430193
comment on: http://stackoverflow.com/q/48168235
score: 0
type: QuestionComment
has text: @RandallStevens Thanks for the comment. I'll check the thing with the '.dbf' file next time I come back to this problem.
type: Comment

http://stackoverflow.com/a/53789669
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48085005
has body: The selected answer was great but it ran for like more than a hour for me, so I created directory and set it as my working one in a step before this code and then added a 'break' after the last if statement in the above code. That did the trick! import cv2 import numpy as np import os def frame_capture(file): # Playing video from file: cap = cv2.VideoCapture(file) currentFrame = 0 while(True): # Capture frame by frame ret, frame = cap.read() # Only take the tenth frame if currentFrame == 5: name = './data/frame' + str(currentFrame) + '.jpg' print ('Creating...' + name) cv2.imwrite(name, frame) break # To stop duplicate images currentFrame += 1 cap.release() cv2.destroyAllWindows()
has comment: http://stackoverflow.com/comment/94434157

http://stackoverflow.com/comment/83011825
type: Comment
has text: It seems `df.words.apply` is not more efficient than what I mentioned in the question (and you added as a comment). About storing lists in a column, is there an alternative way?
comment on: http://stackoverflow.com/a/48021192
type: AnswerComment
score: 0

http://stackoverflow.com/q/48140977
has title: matplotlib heatmap with separated columns
type: Question
type: AnsweredQuestion
tagged with: matplotlib
score: 0
has answer: http://stackoverflow.com/a/48141254
answer count: 1
accepted answer: http://stackoverflow.com/a/48141254
has body: I have a heatmap plot with multiple columns, that looks like this: This is nearly exactly what I want. I used imshow to do it, the plotting code is very simple, with data as a 2D numpy array: plt.imshow(data, cmap="hot", vmin=0.0, vmax=1.0, aspect='auto', interpolation='nearest') plt.colorbar() plt.show() Ideally, though, the columns in this headmap should be grouped (or broken out), as they represent related things. Is there any easy way to create a version of this plot where I can, say, separate columns 0-4, 5-10, and 11-22 into separate blocks, without repeating the colorbar or the yaxis label, but with possible unique labels for each set of columns? Ideally I'd like a plot that looks like (in ascii art): 0 +---+ +-------+ +-------------+ +-+ 1.0 | | | | | | | | 500 | | | | | | | | | | | | | | | | 1000+---+ +-------+ +-------------+ +-+ 0.0 L1 Label2 Label3 Any ideas?
tagged with: python
tagged with: heatmap

http://stackoverflow.com/comment/83161862
has text: With your first regex `I will be there at 55:55 later today` will transform to `I will be there at 57:15 later today`
comment on: http://stackoverflow.com/a/48093108
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83134930
comment on: http://stackoverflow.com/a/48064885
type: AnswerComment
score: 0
has text: sorry for the big amount of questions but I did this with the viewercount aswell `[x['viewer_count'] for x in data['data'] if any(s in x.get('title', '').lower() for s in ['hey', 'rp'])]` but how would I blacklist people. like I want to get the viewer_counts but not from the person with user_id: 23308993
type: Comment

http://stackoverflow.com/comment/83178707
has text: From the OP: "I dont want to create a new file all together though". Also, this will delete your file completely if you try to set `newfile` and `oldfile` to the same file!
comment on: http://stackoverflow.com/a/48101748
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48053045
tagged with: qt5
type: Question
has title: Call Python method from Qt Quick WorkerScript
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48053463
tagged with: python
type: UnansweredQuestion
score: 1
tagged with: pyqt5
upvote count: 1
has body: How do I call a Python method from a Qt Quick WorkerScript? Preamble: I have managed to access my Python methods from my QML app by registering a subclass of QObject: class Foo(QtCore.QObject): @QtCore.pyqtSlot() def bar(self): pass # do stuff here app = QtGui.QGuiApplication([]) QtQml.qmlRegisterType(Foo, 'Foo', 1, 0, 'Foo') # more boilerplate Qt/Qt Quick So from within my QML application, I can successfully invoke Foo.bar(). And from what I understand, I should call any long-running functions from a WorkerScript. Problem: How can I run Foo.bar() in a background thread using WorkerThread? Per the docs, WorkerScripts can't use the import syntax, so I'm not sure how I can access Foo without the import. Update: I need the UI to be able to display progress from Foo.bar(), since the function takes a little while and does several things.
tagged with: qml
tagged with: qtquick2

http://stackoverflow.com/comment/83169387
type: Comment
comment on: http://stackoverflow.com/a/48095125
type: AnswerComment
has text: @Androbin see my comments (and Willem's answers) to the accepted answer; this is not tuple unpacking as the rhs above is a generator (not a tuple; I made the same mistake). Although `a, b, c = *([[] for e in range(6)] for _ in range(3)),` would be tuple unpacking, but possible with a wasteful middle step (generator to tuple? or true tuple comprehension?). For the latter, I can't say.
score: 1

http://stackoverflow.com/a/48036876
has comment: http://stackoverflow.com/comment/83043867
has body: You can cast the returned value to a set: print(list(set(permutations([0,1,1])))) Output: [(0, 1, 1), (1, 1, 0), (1, 0, 1)]
type: Answer
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/48036854
has comment: http://stackoverflow.com/comment/83043819
score: 0

qsqltablemodel
tags question: http://stackoverflow.com/q/48057922
type: Tag
tag name: qsqltablemodel

http://stackoverflow.com/comment/83314192
type: Comment
has text: yeah, i think MultiLabelBinarizer is the most idiomatic approach in this case. We could do it in one line: `df = df.join(pd.DataFrame(mlb.fit_transform(df.pop('c2')),columns=mlb.classes_, index=df.index))`
comment on: http://stackoverflow.com/a/48166981
type: AnswerComment
score: 0

http://stackoverflow.com/a/48079146
has comment: http://stackoverflow.com/comment/83132363
downvote count: 0
has comment: http://stackoverflow.com/comment/83133662
has body: Your function is missing the "return" keyword, which means it will return None instead. Try def rcpath(rel_path): return os.path.join(os.getcwd(), rel_path) root.iconbitmap('@' + rcpath('icons/pypad.ico')) Updated: including Bryan Oakley's comment about the @.
answers question: http://stackoverflow.com/q/48079105
type: Answer
has comment: http://stackoverflow.com/comment/83134163
has comment: http://stackoverflow.com/comment/83133296
score: 3
has comment: http://stackoverflow.com/comment/83136307
upvote count: 3
has comment: http://stackoverflow.com/comment/83134144
has comment: http://stackoverflow.com/comment/83136603

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/48072876
type: Tag

http://stackoverflow.com/a/48117192
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48115753
has body: Scanning the Sorted Set with an iterator does not guarantee any order. Use ZREVRANGEBYSCORE for that.
score: 6
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48115753
type: Answer

http://stackoverflow.com/comment/83110190
score: 2
has text: Add which major version of Python are you using to the question and `print(type(ciphertext))` to `decrypt` as well. I suspect that your data is not what you think it is. Also usually it's better to include the full traceback in the question, instead of just the string representation of the exception object.
comment on: http://stackoverflow.com/q/48068133
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83224661
type: Comment
score: 0
has text: @Wen Checking now. Thanks! I am calculating different things from yours. I think that's why the output is different.
comment on: http://stackoverflow.com/a/48123834
type: AnswerComment

http://stackoverflow.com/a/48043150
has comment: http://stackoverflow.com/comment/83059232
upvote count: 2
has comment: http://stackoverflow.com/comment/83059153
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48043009
has body: Assuming that your example should be the following: [1, 6, 3, 15, 54] [5, -3, 12, 39] [-8, 15, 27] [23, 12] [-11] Where in each step, the numbers are taken as a pair and the first number is substracted from the second. In that case, you can use the pairwise function from the itertools recipes: # original list l = [1, 6, 3, 15, 54] # copy it over to a new name which will be updated on each iteration lst = l # repeat until the list only contains a single element while len(lst) &gt; 1: # take all pairs from the list and substract the first from the second # collect the results in a list and assign that to `lst` lst = [y - x for x, y in pairwise(lst)] # finally, print the single element that’s left in the list print(lst[0])
has comment: http://stackoverflow.com/comment/83059271
accepted answer of: http://stackoverflow.com/q/48043009
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83058054

http://stackoverflow.com/comment/83274116
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48147835
score: 0
has text: The whole point of force killing is to take control away from the process. In other words you can't do what you want, force kill situation cannot be handled. So in order to solve that you have to assume at the program start that it was forcefully killed earlier **and** that it can be forcefully killed at any time. This obviously makes everything a lot more complicated (atomic complex operations with crash recovery are often hard to implement). The alternative would be to avoid shared state to begin with. Or delegate it to a well known software, e.g. a database.

http://stackoverflow.com/q/48168390
favorite count: 0
has comment: http://stackoverflow.com/comment/83316131
has comment: http://stackoverflow.com/comment/83352388
has body: First time making a question here. I am learning Python and I've encountered a problem with my last code. For reference, I'm using the 3.6 version and everything was installed in the last weeks, so should be updated. When I try to open an .xlsm file with Openpyxl I get the error pasted bellow. After removing the Conditional Formatting from the workbook, everything works as expected. It also worked when using Pandas. I have used the module with other files before without a problem. I've found a few similar questions but usually much older and supposedly corrected in older patches. The code snippet should just build the file path and worked with other files. Any lights on this? import openpyxl Ano = '-2018' arquivo = 'Controle de Produção v2 ' arquivo = arquivo + dataEx[3:]+ '-' + Ano[3:] wb = openpyxl.load_workbook("C:\\Users\\Desktop\\Dropbox\\Produção Equipes\\"+arquivo+".xlsx") Traceback (most recent call last): File "C:\Users\Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\openpyxl\descriptors\base.py", line 57, in _convert value = expected_type(value) ValueError: could not convert string to float: '$G$16-0.015' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Desktop\Documents\Hugo\Python\Projetos\Produtividade\Produtividade.py", line 33, in &lt;module&gt; wb = openpyxl.load_workbook("C:\\Users\\Desktop\\Dropbox\\Produção Equipes\\"+arquivo+".xlsx", False, True) #DEFINIR CAMINHO COMPLETO File "C:\Users\Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\openpyxl\reader\excel.py", line 245, in load_workbook ws_parser.parse() File "C:\Users\Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\openpyxl\reader\worksheet.py", line 127, in parse dispatcher[tag_name](element) File "C:\Users\Desktop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\openpyxl\reader\worksheet.py", line 286, in parser_conditional_formatting cf = ConditionalForma…
has comment: http://stackoverflow.com/comment/83318287
has comment: http://stackoverflow.com/comment/83319225
type: UnansweredQuestion
tagged with: openpyxl
tagged with: conditional-formatting
tagged with: python
tagged with: excel
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/83315885
type: Question
has answer: http://stackoverflow.com/a/48188998
has title: Openpyxl - Error loading workbook with conditional formatting
has comment: http://stackoverflow.com/comment/83319082
upvote count: 1
answer count: 1

http://stackoverflow.com/q/48121916
has comment: http://stackoverflow.com/comment/83222631
has answer: http://stackoverflow.com/a/58126156
has answer: http://stackoverflow.com/a/69157357
answer count: 10
tagged with: python
score: 202
has comment: http://stackoverflow.com/comment/83220633
has answer: http://stackoverflow.com/a/55264860
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83231991
accepted answer: http://stackoverflow.com/a/48121983
tagged with: scipy
has body: I would like to take an image and change the scale of the image, while it is a numpy array. For example I have this image of a coca-cola bottle: bottle-1 Which translates to a numpy array of shape (528, 203, 3) and I want to resize that to say the size of this second image: bottle-2 Which has a shape of (140, 54, 3). How do I change the size of the image to a certain shape while still maintaining the original image? Other answers suggest stripping every other or third row out, but what I want to do is basically shrink the image how you would via an image editor but in python code. Are there any libraries to do this in numpy/SciPy?
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83220677
has title: Numpy Resize/Rescale Image
has answer: http://stackoverflow.com/a/53687499
has answer: http://stackoverflow.com/a/66449961
tagged with: resize
has answer: http://stackoverflow.com/a/65118276
has answer: http://stackoverflow.com/a/58567022
tagged with: image
upvote count: 202
has answer: http://stackoverflow.com/a/56135413
possible better answer: http://stackoverflow.com/a/48121996
has answer: http://stackoverflow.com/a/48121996
downvote count: 0
linked to: http://stackoverflow.com/q/37872171
favorite count: 0
has answer: http://stackoverflow.com/a/48121983

http://stackoverflow.com/a/48103866
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83184728
answers question: http://stackoverflow.com/q/48103157
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48103157
has comment: http://stackoverflow.com/comment/83184212
score: 1
has body: Instead of getting each key one by one and calling the dictionary separately, you can do it at once. Say one of your text files contains this: hakuchita.mutikama mitiputu.mitanata luschi.rulu.pitana Get all keys at once: with open("sampleText.txt","r") as f: keys = f.read().splitlines() This is your dictionary in the OP: dictionary = { 'hakuchita.mutikama' : 3, 'mitiputu.mitanata' : 4, 'pulasika.rukayota' : 1, 'luschi.rulu.pitana' : 2 } Get all values now: values = [dictionary[e] for e in keys] Result: [3, 4, 2] Now, as @chepner brilliantly points out in his comment, if you do: dictionary = dict([(k+'\n',v) for k,v in dictionary.items()]) you can get rid of the .splitlines() in my above code, read the file using keys = f.readlines(), and save the time .splitlines() would take. You can optimize this whole procedure by parallel-processing, as @JuanAntonio mentions.

http://stackoverflow.com/comment/83180819
score: 0
has text: Hi @jezrael,sorry to disturb you again. After my first successful run,I have reloaded the data from my csv file again using the command pd.read_csv('student.csv') ,it's the same data which I used previously, then run the code & again got a long list of error message which I have added in my first post. Only thing I saw is that now year field is with data type int32. I also tried to convert it using `df_student['year']=df_student['year'].astype(np.int64)` but that doesn't work.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48093402

http://stackoverflow.com/comment/83322320
has text: I think you have to create two equations expliciting both variables X and Y
comment on: http://stackoverflow.com/q/48171334
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83185623
has text: *what I'd like to do is sum the values for all elements of b, irrespective of what a is*: I wrote an answer with that intention. Doesn't it work? If it doesn't leave a comment and we'll work through it **:-)**
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48104635

http://stackoverflow.com/comment/83078719
has text: A space is lower than all the other characters. Maybe try a *list* of ints instead?
score: 7
comment on: http://stackoverflow.com/q/48053227
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48167925
accepted answer of: http://stackoverflow.com/q/48167731
upvote count: 3
answers question: http://stackoverflow.com/q/48167731
type: AcceptedAnswer
has body: Yes, it is related to threading as you want to spawn a different thread to execute your function asynchronously - the parent process will wait 10 seconds irrespective of how long the thread takes to execute. This is a standard way to do this in python: import threading def print_some(): threading.Timer(10.0, print_some).start() print "Hello!" print_some() See more here: http://www.bogotobogo.com/python/Multithread/python_multithreading_subclassing_Timer_Object.php So in your case it would be: import threading import time def foo(): threading.Timer(10.0, foo).start() print("hello") if __name__ == '__main__': foo()
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/comment/83323473
comment on: http://stackoverflow.com/q/48171779
score: 0
type: Comment
type: QuestionComment
has text: Specifically, see https://stackoverflow.com/a/13681679/719547 in that question.

http://stackoverflow.com/comment/83113891
has text: It does run the python code quickly, I want the c version to compare them, I just expected it to be there. I am comparing a bunch of priority queue type data structures.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48069940

http://stackoverflow.com/a/48029909
has comment: http://stackoverflow.com/comment/83030269
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83030024
has comment: http://stackoverflow.com/comment/83030261
downvote count: 0
has comment: http://stackoverflow.com/comment/83030485
accepted answer of: http://stackoverflow.com/q/48029844
has comment: http://stackoverflow.com/comment/83030308
has comment: http://stackoverflow.com/comment/83030131
answers question: http://stackoverflow.com/q/48029844
has comment: http://stackoverflow.com/comment/83030078
has comment: http://stackoverflow.com/comment/83030175
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/83030337
upvote count: 6
has comment: http://stackoverflow.com/comment/83030113
has comment: http://stackoverflow.com/comment/83030472
has comment: http://stackoverflow.com/comment/83030072
has comment: http://stackoverflow.com/comment/83030086
has comment: http://stackoverflow.com/comment/83030036
has comment: http://stackoverflow.com/comment/83030352
has comment: http://stackoverflow.com/comment/83030448
has body: An alternative approach: cor = " ".join(res).split() Output: ['sans', 's', 'ans', 'sa', 'ns', 'san', 's'] Explanation " ".join(res) will join the individual strings in res with a space in between them. Then calling .split() will split this string on whitespace back into a list. EDIT: A second approach that doesn't involve the intermediate variable res, although this one isn't quite as easy on the eyes: cor = [var[:i/2+1] if i%2==1 else var[i/2:] for i in range(2*len(var)-1)] Basically you flip between building substrings from the front and the back.
has comment: http://stackoverflow.com/comment/83030425
has comment: http://stackoverflow.com/comment/83031289
has comment: http://stackoverflow.com/comment/83030512

http://stackoverflow.com/a/48124534
answers question: http://stackoverflow.com/q/48120431
accepted answer of: http://stackoverflow.com/q/48120431
type: Answer
score: 2
upvote count: 2
has body: How about something like this? # returns (count_of_uni_value_subtrees, value) # assumes nodes have a value other than None def f(root, val): if not root: return (0, val) (left_count, left_val) = f(root.left, root.val) (right_count, right_val) = f(root.right, root.val) if left_val == root.val == right_val: return (1 + left_count + right_count, root.val) else: return (left_count + right_count, None) """ f(5) / \ d(1) e(5) / \ \ a(5) b(5) c(5) """ (The empty) children of nodes a, b and c return (0, 5) each. a, b and c each return (1, 5). The left (empty) child of e returns (0, 5) d returns (2, None). e returns (2, 5). f returns (4, None).
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48051118
downvote count: 0
has comment: http://stackoverflow.com/comment/83074051
has title: NoReverseMatch for url in Django template
has answer: http://stackoverflow.com/a/48051314
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83074107
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/83073973
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48051314
score: 1
has comment: http://stackoverflow.com/comment/83074024
upvote count: 1
type: Question
has body: I'm getting this error: NoReverseMatch at /workoutcal/add/2017/11/1/ Reverse for 'add_workout' not found. 'add_workout' is not a valid view function or pattern name. Because of this template code: &lt;form action="{% url 'add_workout' date.year date.month date.day %}" method="post"&gt; From the urls.py: url(r'^add/(?P&lt;year&gt;[0-9]+)/(?P&lt;month&gt;[0-9]+)/(?P&lt;day&gt;[0-9]+)/$', views.AddWorkoutView.as_view(), name = 'add_workout'), I've followed the docs. Don't know why my URL name isn't found. Any ideas? EDIT: The entire urls.py from django.conf.urls import url from . import views app_name = 'workoutcal' urlpatterns = [ url(r'^$', views.redirect_to_calendar), url(r'^(?P&lt;year&gt;[0-9]+)/(?P&lt;month&gt;[1-9]|1[0-2])$', views.calendar, name='calendar'), url(r'^(?P&lt;id&gt;[0-9]+)/$', views.detail, name='detail'), #Detail of a workout. Shows lifts, duration, etc. All the attributes. url(r'^add/(?P&lt;year&gt;[0-9]+)/(?P&lt;month&gt;[0-9]+)/(?P&lt;day&gt;[0-9]+)/$', views.AddWorkoutView.as_view(), name = 'add_workout'), url(r'^edit/(?P&lt;id&gt;[0-9]+)/$', views.edit, name='edit'), #Editing an existing workout. id is id of workout object to edit. url(r'^name/$', views.get_contact_form, name='contact_form'), url(r'^get_lifts/$', views.get_lifts, name='get_lifts'), url(r'^add_lift/$', views.add_lift, name='add_lift'), url(r'^get_cardio/$', views.get_cardio, name='get_cardio'), url(r'^login/$', views.LoginView.as_view(), name='login'), url(r'^logout/$', views.logout_view, name='logout'), url(r'^register/$', views.UserFormView.as_view(), name='register'), url(r'^username/$', views.get_username, name='username'), ] The view that's rendering the template: class AddWorkoutView(View): def get(self, request, year=None, month=None, day=None): template_name = 'workoutcal/addworkout.html' template = loader.get_template(template_name) date = datetime(year=int(year), month=int(month), day=int(day)) context = { 'date':date, 'current_name':request.user.username, 'title':'A…

http://stackoverflow.com/comment/83317920
type: Comment
score: 1
has text: As indicated in the linked question, you cannot have mixed types in an array. You could use the `object` dtype, although that may complicate other things (e.g. arithmetic operations, etc.). Can't you use some "special" value to represent the X instead (like 0, like you said, or -1 or something)? Why does it need to be a string?
comment on: http://stackoverflow.com/q/48169184
type: QuestionComment

http://stackoverflow.com/a/70721318
answers question: http://stackoverflow.com/q/48046020
score: 0
has body: Regarding the above answer, it is correct but missing checking the cases where passing exceeds 1000000000. Also, I found a smarter and simple way to count the pairs of cars that could be passed where you just count all existing ones inside the array from the beginning and inside the loop when you find any zero, you say Ok we could possibly pair all the ones with this zero (so we increase the count) and as we are already looping through the whole array, if we find one then we can simply remove that one from ones since we will never need it again. It takes O(N) as a time complexity since you just need to loop once in the array. def solution(A): ones = A.count(1) c = 0 for i in range(0, len(A)): if A[i] == 0: c += ones else: ones -= 1 if c &gt; 1000000000: return -1 return c
type: Answer

http://stackoverflow.com/a/48115935
score: 2
has comment: http://stackoverflow.com/comment/83208631
has comment: http://stackoverflow.com/comment/83208583
has comment: http://stackoverflow.com/comment/83208211
has comment: http://stackoverflow.com/comment/83208719
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48115669
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48115669
has comment: http://stackoverflow.com/comment/83208647
type: Answer
has comment: http://stackoverflow.com/comment/83208370
has body: You are creating a list of 138259 * 9606834 items. That is too much for your memory. I propose to go with the generator which itertools.product() actually is (i. e. the elements aren't stored in memory but created on the fly during iterating): paramlist = itertools.product(LOAD_GEN_KEYS, ES_DATA_K) Since the pool.map(curate_results, paramlist) accepts an iterable, a generator should do as fine as the list.

http://stackoverflow.com/q/48046185
has body: I have a noobie question here regarding the plt.scatter. I am working on some machine learning tutorial where we are analyzing the petal length of two flowers. df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header = None) print(df.tail()) y = df.iloc[0:100,4].values #This is going to print out the 5th column of the dataset. y = np.where(y == 'Iris-setosa', -1, 1) #Where y has 'Iris-setosa' in there, it is going to yield a -1. Else it is going to yield a 1. X = df.iloc[0:100, [0,2]].values #1st and 3rd column of the Iris dataset online #printout the 1st and 3rd plt.scatter(X[:50,0], X[:50, 1], color = 'red', marker = 'o', label = 'setosa') plt.scatter(X[50:100, 0], X[50:100, 1], color = 'blue', marker = 'x', label = 'versicolor') I don't quite get why for each of the plt.scatter lines, there are two X[:50,0] and X[:50, 1]. What is the purpose of that?? I thought that plt.scatter is meant to show one type of item when doing a scatter plot. Like I thought that it would go something like. You know that from rows 0 to 50, you want to plt scatter a certain flower so its just X[:50,0] and so on... Thanks in advance for any input on this.. enter image description here
has comment: http://stackoverflow.com/comment/83064033
downvote count: 2
has comment: http://stackoverflow.com/comment/83063976
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/83064136
has title: plt.scatter(X[:50,0], X[:50, 1], color = 'red', marker = 'o', label = 'setosa')
tagged with: machine-learning
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83064111
has comment: http://stackoverflow.com/comment/83063789
score: -2
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48046408
accepted answer: http://stackoverflow.com/a/48046408
has comment: http://stackoverflow.com/comment/83064213

http://stackoverflow.com/comment/118993690
has text: more details: https://github.com/pandas-dev/pandas/issues/2801#issuecomment-17644076
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48030360

mininet
tag name: mininet
tags question: http://stackoverflow.com/q/48017220
type: Tag

http://stackoverflow.com/q/48131019
has comment: http://stackoverflow.com/comment/83240492
has comment: http://stackoverflow.com/comment/83239061
has comment: http://stackoverflow.com/comment/83240672
score: 0
has comment: http://stackoverflow.com/comment/83238910
has comment: http://stackoverflow.com/comment/83240469
answer count: 1
has title: How to Pythonically check for errors in JSON response?
has answer: http://stackoverflow.com/a/48132074
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83240513
tagged with: python
has body: I have a response from an API which I need to save to a database and 99% of responses all are valid with the following details which I am formatting to be neater. I've just had a 1% response break the code because there are no address['state'] so it returned a bool of False. I could do a try: except: for each line to catch it and if it's False but thought there must be a neater, more efficient way. What's best practice in this instance when each line could be False? order_id_newest = int(address['order_id']) address_line_1 = address['line1'].title() address_line_2 = address['line2'].title() address_city = address['city'].title() address_county = address['state'].title() address_postcode = address['zip'].upper()
tagged with: http://stackoverflow.com/tag/json
type: Question

http://stackoverflow.com/a/48314535
type: Answer
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48089942
upvote count: 3
has body: Its working for me to Compress and Upload Image. function readFile(evt) { var file = evt.target.files[0]; var reader = new FileReader(); output_format = "jpg"; reader.onload = function(event) { var i = document.getElementById("source_image"); i.src = event.target.result; i.onload = function(){ image_width=$(i).width(), image_height=$(i).height(); if(image_width > image_height){ i.style.width="320px"; }else{ i.style.height="300px"; } i.style.display = "block"; console.log("Image loaded"); } }; console.log("Filename:" + file.name); console.log("Filesize:" + (parseInt(file.size) / 1024) + " Kb"); console.log("Type:" + file.type); reader.readAsDataURL(file); return false; } $( "#upload" ).click(function() { var source_image = document.getElementById('source_image'); if (source_image.src == "") { alert("You must load an image first!"); return false; } var quality = 30; console.log("process start..."); var time_start = new Date().getTime(); output_format = "jpg"; console.log("process start compress ..."); source_image.src = jic.compress(source_image,quality,output_format).src; console.log('Compressed in: ' + new Date().getTime() - time_start + 'ms'); var successCallback= function(response){ console.log("image uploaded successfully! :)"); console.log(response); } var errorCallback= function(response){ console.log("image Filed to upload! :)"); console.log(response); } var time_start = new Date().getTime(); console.log("process start upload ..."); jic.upload(source_image, '/uploadimage', 'file', 'new.jpg',successCallback,errorCallback); console.log('uploaded in: ' + new Date().getTime() - time_start + 'ms'); }); document.getElementById('fileinput').addEventListener('change', readFile, false); Choose file Python Code def uploadimage(): print "In uploadimage() trying to upload" try: file = request.files['file'] print "File",file print "Name",file.filename except Exception as e: print "Failed",str(e)

http://stackoverflow.com/a/54612520
has comment: http://stackoverflow.com/comment/134607186
score: 36
type: Answer
has comment: http://stackoverflow.com/comment/134596242
answers question: http://stackoverflow.com/q/48160728
has comment: http://stackoverflow.com/comment/134580169
accepted answer of: http://stackoverflow.com/q/48160728
has body: Having the teardown logic in __del__ can make your program incorrect or harder to reason about, because there is no guarantee on when that method will get called, potentially leading to the warning you got. There are a couple of ways to address this: 1) Expose a method to close the session, and call it in the test tearDown unittest's tearDown method allows you to define some code that will be run after each test. Using this hook to close the session will work even if the test fails or has an exception, which is nice. app.py import requests class Service(object): def __init__(self): self.session = requests.Session() def get_info(self): uri = 'http://api.stackexchange.com/2.2/info?site=stackoverflow' response = self.session.get(uri) if response.status_code == 200: return response.json() else: response.raise_for_status() def close(self): self.session.close() if __name__ == '__main__': service = Service() print(service.get_info()) service.close() test.py import unittest import app class TestService(unittest.TestCase): def setUp(self): self.service = app.Service() super().setUp() def tearDown(self): self.service.close() def test_growing(self): res = self.service.get_info() self.assertTrue(res['items'][0]['new_active_users'] &gt; 1) if __name__ == '__main__': unittest.main() 2) Use a context manager A context manager is also a very useful way to explicitly define the scope of something. In the previous example, you have to make sure .close() is called correctly at every call site, otherwise your resources will leak. With a context manager, this is handled automatically even if there is an exception within the scope of the context manager. Building on top of solution 1), you can define extra magic methods (__enter__ and __exit__) so that your class works with the with statement. Note: The nice thing here is that this code also supports the usage in solution 1), with explicit .close(), which can be useful if a context manager was inconvenient for some reason. app.py import …
upvote count: 36
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48141186
type: UnansweredQuestion
type: Question
tagged with: com
has comment: http://stackoverflow.com/comment/83260529
has comment: http://stackoverflow.com/comment/83260643
tagged with: python
has comment: http://stackoverflow.com/comment/83261764
has comment: http://stackoverflow.com/comment/83261463
has body: I am registering a Python COM server so I can use it in VBScript. Whenever i register a server which does not use google api then I am able to instantiate the COM object in VBS. The code looks like this. ` import pythoncom, win32com.server.register class Python_For_VBS: _public_methods_ = ['Hello'] _reg_progid_ = "PythonForVBS.Utilities" _reg_clsid_ = pythoncom.CreateGuid() def Hello(self, item=None): import ctypes MessageBox = ctypes.windll.user32.MessageBoxW MessageBox(None, 'Hello', 'Window title', 0) msg = "Hello" return msg if __name__ == '__main__': win32com.server.register.UseCommandLine (Python_For_VBS) ` It gets registered fine and also am able to use it in VBS. but when i register this (this is the sample code from developers.google.com. ` from __future__ import print_function import httplib2 import os import pythoncom, win32com.server.register, ctypes from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'QTest' class GAPI: _public_methods_ = ['returnfiles'] _reg_progid_ = "GAPI.Utilities" _reg_clsid_ = '{FDB80AAF-D3AD-417C-ADBA-E93D7FF59E86}' def get_credentials(self, item=None): #import ctypes #MessageBox = ctypes.windll.user32.MessageBoxW #MessageBox(None, 'get_credentials', 'Window title', 0) store = Storage('Storage.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) return creds def returnfiles (self, item=None): #import ctypes MessageBox = ctypes.windll.user32.MessageBo…
score: 0
tagged with: vbscript
has comment: http://stackoverflow.com/comment/83261977
tagged with: server
has comment: http://stackoverflow.com/comment/83261580
has comment: http://stackoverflow.com/comment/83261926
answer count: 0
has title: Python COM Server for using Google API
has comment: http://stackoverflow.com/comment/83265449

http://stackoverflow.com/comment/83216164
score: 0
type: AnswerComment
has text: @emmi474: I've linked to the implementation used by `pip`. We have 5 more years before this would become a problem however.
type: Comment
comment on: http://stackoverflow.com/a/48119432

http://stackoverflow.com/comment/83279508
type: Comment
type: QuestionComment
score: 0
has text: You do not need a straight line, you do not need a polynomial, what do you need then?
comment on: http://stackoverflow.com/q/48149649

http://stackoverflow.com/a/48122878
accepted answer of: http://stackoverflow.com/q/48122796
answers question: http://stackoverflow.com/q/48122796
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You are successfully putting two frames inside of the MainPage frame. The problem is that you're putting a bunch of other widgets in there too, and you're putting some of them in the same row and column as the frames. For the widgets to be inside the frames, you need to provide the frame as the parent. For example: frame1.label = tk.Label(frame1, ...) frame1.EntryBox = ttk.Entry(frame1, ...) frame1.button = ttk.Button(frame1, ...) frame1.button1 = ttk.Button(frame1, ...) frame2.label = tk.Label(frame2, ...)
score: 1
has comment: http://stackoverflow.com/comment/83222600

http://stackoverflow.com/comment/83224261
has text: oh yeah, try to avoid most of the `plt` API. It's much better to operate on `Figure` and `Axes` objects directly
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48123231

http://stackoverflow.com/comment/105379213
has text: @Decker won't it affect the image when the swapping is done from RGB to BGR?
type: Comment
comment on: http://stackoverflow.com/a/48121983
type: AnswerComment
score: 0

http://stackoverflow.com/q/48034035
has comment: http://stackoverflow.com/comment/83046684
tagged with: one-hot-encoding
tagged with: python
has comment: http://stackoverflow.com/comment/83046672
score: 2
has answer: http://stackoverflow.com/a/48095698
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48095698
downvote count: 0
has comment: http://stackoverflow.com/comment/83039053
has comment: http://stackoverflow.com/comment/83038819
type: Question
has comment: http://stackoverflow.com/comment/83066479
has comment: http://stackoverflow.com/comment/83046644
has title: How to consistently hot encode dataframes with changing values?
upvote count: 2
has comment: http://stackoverflow.com/comment/83051911
has comment: http://stackoverflow.com/comment/83038732
has body: I'm getting a stream of content in the form of dataframes, each batch with different values in columns. For example one batch might look like: day1_data = {'state': ['MS', 'OK', 'VA', 'NJ', 'NM'], 'city': ['C', 'B', 'G', 'Z', 'F'], 'age': [27, 19, 63, 40, 93]} and another one like: day2_data = {'state': ['AL', 'WY', 'VA'], 'city': ['A', 'B', 'E'], 'age': [42, 52, 73]} how can the columns be hot encoded in a way that returns a consistent number of columns? If I use pandas's get_dummies() on each of the batches, it returns a different number of columns: df1 = pd.get_dummies(pd.DataFrame(day1_data)) df2 = pd.get_dummies(pd.DataFrame(day2_data)) len(df1.columns) == len(df2.columns) I can get all the possible values for each column, the question is even with that information what's the simplest way to generate the one hot encoding for each daily batch so the number of columns will be consistent?
tagged with: pandas
answer count: 1
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/comment/83041800
type: AnswerComment
has text: sorry mate, it does not. I'm not asking about modifying the python interpreter. I wish to use features exposed to the python language.
type: Comment
comment on: http://stackoverflow.com/a/48035674
score: 0

http://stackoverflow.com/comment/83098537
type: Comment
has text: Sorry in no case did I want to pressure you after all the help you gave me! Just thought that my comment was lost in your notifications.
comment on: http://stackoverflow.com/a/48062326
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83180761
has text: @ZF007 Thank you for answering and the advice, i should've added some short explanation in the beggining indeed. I know that the model is loaded properly(see 4.) but i'm not sure about how exactly it is used in the training process (i thought it's going to start from the accuracy it was saved with).
type: Comment
comment on: http://stackoverflow.com/q/48102364
type: QuestionComment
score: 0

http://stackoverflow.com/a/48027798
upvote count: 1
has body: So, it seems like you have a dataframe looking like this - df AQPSD ASD CO ECARS ED EO ISD MSCD OIS RD TTD 0 6 8 2 3 6 4 4 5 1 2 4 If you want these values as a single list, you can call .values and convert to a list - df.values.ravel().tolist() Or, df.values.flatten().tolist() [6, 8, 2, 3, 6, 4, 4, 5, 1, 2, 4]
has comment: http://stackoverflow.com/comment/83025953
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83025968
has comment: http://stackoverflow.com/comment/83025819
type: Answer
has comment: http://stackoverflow.com/comment/83025636
accepted answer of: http://stackoverflow.com/q/48026525
score: 1
has comment: http://stackoverflow.com/comment/83025559
has comment: http://stackoverflow.com/comment/83025846
answers question: http://stackoverflow.com/q/48026525
has comment: http://stackoverflow.com/comment/83025652
has comment: http://stackoverflow.com/comment/83025549
has comment: http://stackoverflow.com/comment/83025529
has comment: http://stackoverflow.com/comment/83025902
has comment: http://stackoverflow.com/comment/83025604

http://stackoverflow.com/comment/83144038
has text: "ValueError: too many values to unpack (expected 2)" when I try your code above
score: 0
comment on: http://stackoverflow.com/q/48084547
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48128995
type: Question
tagged with: audio-fingerprinting
tagged with: max
tagged with: spectrogram
upvote count: 2
score: 0
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/83242217
linked to: http://stackoverflow.com/q/3684484
favorite count: 0
has comment: http://stackoverflow.com/comment/83237174
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/3684484
tagged with: python
has answer: http://stackoverflow.com/a/48129161
has title: How to find peaks in a spectrogram Python
has body: Introduction I am trying to find peaks in amplitude within a spectrogram I have produced that plots frequency against time and amplitude as the third axis. I have looked through and attempted to code a solution using scipy.signal.find_peaks_cwt however the official reference guide did not explain what was meant by the widths parameter. Question: When finding peaks using scipy.signal.find_peaks_cwt will it return the frequency-time coordinates? If not is there another library or method to use to return the coordinates of local maxima? What is the widths parameter within scipy.signal.find_peaks_cwt? As the scipy.signal.find_peaks_cwt deals with arrays why do you still need to plot a spectrogram in order to find local maxima? Here is the code i have been using to create the spectrogram: import numpy as np import matplotlib.pyplot as plt import scipy.io.wavfile from scipy import signal def create_spectrogram(audio): rate, data = scipy.io.wavfile.read(audio) data_1D = data.flatten() plt.specgram(data_1D, NFFT = 64, Fs = 64, noverlap=32) plt.savefig("melody") plt.show() if __name__ == '__main__': audio = "melody.WAV" create_spectrogram(audio) Here is the outputted Spectrogram: Links: scipy.signal.find_peaks_cwt reference guide: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.find_peaks_cwt.html

http://stackoverflow.com/comment/83186398
score: 0
type: AnswerComment
type: Comment
has text: Then I don't understand the OP's requirements. Deleting.
comment on: http://stackoverflow.com/a/48105353

flask-restplus
tag name: flask-restplus
tags question: http://stackoverflow.com/q/48158628
type: Tag

http://stackoverflow.com/comment/83295608
type: QuestionComment
comment on: http://stackoverflow.com/q/48158027
score: 0
has text: So you want to write it to a different kind of file?
type: Comment

http://stackoverflow.com/a/48071458
type: AcceptedAnswer
score: 0
type: Answer
has body: You can use the logging module in python for this. This helps you to log the timestamp along with the log message. import logging LOG_FILENAME = 'exception.log' logging.basicConfig(filename=LOG_FILENAME,level=logging.ERROR) logging.error('This message should go to the log file')
has comment: http://stackoverflow.com/comment/83117170
accepted answer of: http://stackoverflow.com/q/48071239
answers question: http://stackoverflow.com/q/48071239
has comment: http://stackoverflow.com/comment/83117364

http://stackoverflow.com/q/48148619
has comment: http://stackoverflow.com/comment/83282866
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83314634
has comment: http://stackoverflow.com/comment/83275956
type: Question
has comment: http://stackoverflow.com/comment/83275537
has comment: http://stackoverflow.com/comment/83297406
has title: My daemon die directly after starting
has answer: http://stackoverflow.com/a/48149010
accepted answer: http://stackoverflow.com/a/48149010
possible better answer: http://stackoverflow.com/a/48149098
score: 0
tagged with: bash
answer count: 2
has comment: http://stackoverflow.com/comment/83344130
has answer: http://stackoverflow.com/a/48149098
tagged with: service
tagged with: daemon
has comment: http://stackoverflow.com/comment/83275796
has comment: http://stackoverflow.com/comment/83283240
has comment: http://stackoverflow.com/comment/83275477
tagged with: linux
linked to: http://stackoverflow.com/q/473620
has body: I have to develop a program with Python3 which executes automatically programs at specific times. I must use a daemon and I can't use external libraries. That's why I create an install program which configure the daemon (I followed this tutorial https://openclassrooms.com/courses/faire-un-demon-sous-linux). The file gobatch is the program which executes automatically programs. #! /usr/bin/python3 # -*- coding: utf8 -*- import os import sys import time import shutil # Check if script is start with root rights if os.geteuid() != 0: exit('You need to have root privileges to run this script. Use \'sudo ./install.py\'.') # Title print('----- ProcessManager install ----- \n') time.sleep(1) # Get path of gobatch file gobatchPath = input("Please enter the path (absolute) where the ProcessManager gobatch program is located: ") # Check if file exists try: with open(gobatchPath): pass except IOError: exit('Error : file does not exists.') # Copy gobatch file into /usr/bin/ shutil.copy(gobatchPath, '/usr/bin/gobatch') # Create and fill the automatic launch program description = 'Deamon that allows you to run cyclicaly at a date or a specific time a program' fileContent = '#### BEGIN INIT INFO \n' \ '# Provides: chillispot et freeradius dans le chroot \n' \ '# Required-Start: $local_fs $network \n' \ '# Required-Stop: $local_fs $remote_fs _\n' \ '# Default-Start: 2 3 4 5 \n' \ '# Default-Stop: 0 1 6 \n' \ '# Short-Description: Wireless &amp; LAN Access Point Controller \n' \ '# Description: ChilliSpot is an open source captive portal \n' \ '# or wireless LAN access point controller. \n' \ '### END INIT INFO \n\n\n' \ 'DESC="' + description + '"\n' \ 'DEAMON=/usr/bin/gobatch' file = open('/etc/init.d/gobatch', 'w') file.write(fileContent) file.close() # Give the rights os.chmod('/etc/init.d/gobatch', 0o755) # Save gobatch file to be active os.system('update-rc.d gobatch defaults') However, when I start the service with : /etc/init.d/gobatch start and displaying the status with ser…
tagged with: python

http://stackoverflow.com/comment/83223631
type: AnswerComment
has text: Hi @Matthias, it is now working :) Thank you. Before closing the question, I would like to update your comment by highlighting in green the paragraph 1, 2 and the last one(after **UPDATE**) but unfortunately I'm not very confident to do it myself.. To resolve the issue, I basically centralized the creation and use of the queues & processes into `core.py` and pass the queues as `args` of `Process` and now it works fine.
comment on: http://stackoverflow.com/a/48091419
type: Comment
score: 0

http://stackoverflow.com/comment/83332179
comment on: http://stackoverflow.com/a/48172508
score: 0
type: AnswerComment
has text: `enemy = pygame.sprite.Group()` is not of class `Enemy` you need to call the `shootEnemy` method on a member of the group `enemy`
type: Comment

http://stackoverflow.com/comment/83026015
comment on: http://stackoverflow.com/q/48027076
type: Comment
has text: @martineau looking at that library, I assume it was a personal throw-away script that was supposed to be called in isolation and the OP just stumbled upon it. I now think it's probably more hassle than it's worth to try import this code instead of making your own :)
score: 0
type: QuestionComment

http://stackoverflow.com/comment/83323445
type: AnswerComment
has text: @CrunchyCruncha, aha, you are getting closer... So now you can narrow down your problematic data and fix it...
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48155178

http://stackoverflow.com/q/48045712
type: Question
possible better answer: http://stackoverflow.com/a/48045769
has answer: http://stackoverflow.com/a/48045769
has answer: http://stackoverflow.com/a/48045741
answer count: 2
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48045741
has body: I am designing an incremental/clicker game in pygame, and I want to change the $ counter by 1 every click. However, I can hold the button down, and I can't find a way to limit this. My button class is below: class Button(object): def __init__(self,x,y,width,height,color): self.rect=(x,y,width,height) self.image=pygame.draw.rect(screen, color,(self.rect),) self.x=x self.y=y self.width=width self.height=height def check(self): mouse=pygame.mouse.get_pos() if self.x+self.width &gt;mouse[0] &gt; self.x and self.y+self.height &gt;mouse[1] &gt; self.y: if pygame.mouse.get_pressed()[0]==True: return True Is there a way to stop the button from being held down? All help is appreciated! Full code: import pygame, sys from pygame.locals import * pygame.init() light_gray=(211,211,211) black=(0,0,0) white=(255,255,255) def terminate(): pygame.quit() sys.exit() def drawText(text, font, screen, x, y,color): textobj = font.render(text,True, color) textrect = textobj.get_rect(center=(x,y)) screen.blit(textobj, textrect) class Button(object): def __init__(self,x,y,width,height,color): self.rect=(x,y,width,height) self.image=pygame.draw.rect(screen, color,(self.rect),) self.x=x self.y=y self.width=width self.height=height def check(self): mouse=pygame.mouse.get_pos() if self.x+self.width &gt;mouse[0] &gt; self.x and self.y+self.height &gt;mouse[1] &gt; self.y: if pygame.mouse.get_pressed()[0]==True: return True clock=pygame.time.Clock() font=pygame.font.SysFont(None,50) screen_width=1300 screen_height=700 screen=pygame.display.set_mode([screen_width,screen_height]) pygame.display.set_caption('Clicker') done=False money=0 sprites=pygame.sprite.Group() button=Button(25,screen_height-125,500,100,light_gray) while not done: for event in pygame.event.get(): if event.type==QUIT: terminate() if button.check()==True: money+=1 screen.fill(light_gray) sprites.draw(screen) pygame.draw.rect(screen,black,button.rect, 3) text_width, text_height=font.size('Click!') drawText('Click!', font,screen,butt…
tagged with: python
tagged with: pygame
score: 2
type: AnsweredQuestion
has title: Pygame mouse hold
upvote count: 2

http://stackoverflow.com/comment/129672481
type: AnswerComment
comment on: http://stackoverflow.com/a/48066323
has text: I tried to use this for Windows and a conda environment today got this error: Error running 'flake8' Cannot run program "C:\Users\Steve\anaconda3\envs\lmageProcessing\Lib\site-packages\flake8\__main__.py" (in directory "C:\Users\Steve\PycharmProjects\lmageProcessing\src"): CreateProcess error=193, %1 is not a valid Win32 application
score: 0
type: Comment

http://stackoverflow.com/a/53367228
downvote count: 3
has comment: http://stackoverflow.com/comment/136619335
answers question: http://stackoverflow.com/q/48152674
has body: From the official site's get started page, you can check if the GPU is available for PyTorch like so: import torch torch.cuda.is_available() Reference: PyTorch | Get Started
type: Answer
score: 29
upvote count: 32

http://stackoverflow.com/q/48118711
upvote count: 2
tagged with: django
has body: I wanted to make wallets for BTC and LTC coins in my models. But since most of the code will be same apart from the coin_name and tx_fees. So, I thought of making a helper class like this : Wallet class ( snippet ) class Wallet(models.Model): name = models.CharField(max_length=80, editable=False) trading_amt = models.FloatField(default=0, validators=[MinValueValidator(0.0), ]) wallet_amt = models.FloatField(default=0, validators=[MinValueValidator(0.0), ]) wallet_address = models.CharField(default='', blank=True, max_length=100) coin_name = '' &lt;-- will it serve the purpose ? tx_fee = 0 &lt;-- and this ? def __init__(self, coin_name, tx_fee): self.coin_name = coin_name self.tx_fee = tx_fee @transaction.atomic def moveToTrading(self, amount): if amount &gt; self.wallet_amt: return "Insufficient balance" else: self.trading_amt += amount self.wallet_amt -= amount return True @transaction.atomic def withdraw(self, amount, withdrawal_wallet_addr): if amount &gt; self.wallet_amt: return "Insufficient balance" else: # First check if withdrawal address entered by user is # correct, using wallet daemon , if not return error if check_wallet(withdrawal_wallet_addr, "btc"): # initiate checkout return initiate_checkout(withdrawal_wallet_addr, self.coin_name, self.tx_fee) else: return "Incorrect Wallet address" def save(self, *args, **kwargs): self.name = gen_random_string('btc_wallet') super(Wallet, self).save(*args, **kwargs) def deposit(self, amount): self.wallet_amt += amount def __unicode__(self): return self.name def __str__(self): return self.name The use of coin_name is only while creating wallet address name like this : _btc_wallet_&lt;64 char random string>_ And tx_fee is stored as a constant in helpers.py for each coin. So, saving these in the database doesn't makes sense. Problem 1 : I am a little noob in OOP programming ( I know what these are , but haven't coded much ) so am confused as to what would be it's correct usage : Usage 1 : class BtcWallet(Wallet): def _…
has answer: http://stackoverflow.com/a/48125513
type: Question
tagged with: oop
has title: django Inheriting from helper class
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2

http://stackoverflow.com/comment/83059583
has text: This is a horrible question: random & inconsistent indentation (1-5 space indent. for blocks), and inconsistent whitespace, strings b4 def/class instead of docstrings -- it makes the code painful to read, and you've basically just dumped your code and told us "please finish my project for me". Add to that a seemingly complete lack of understanding of Unicode (hint: why can you not decode a 1-byte utf-8 string). ..also, please name the encoding to use whenever you call encode/decode. Fixing text/byte issues does not involve adding `bytes()/.encode()/.decode()` willy-nilly through your code.
score: 0
comment on: http://stackoverflow.com/q/48043848
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83705483
comment on: http://stackoverflow.com/a/48350323
type: Comment
has text: Oh, think I misunderstood you - are you talking about specific tests for the utils that shouldn't be released with the _real_ tests? So to say, _tests for the tests_? Put them wherever you are putting the usual tests, `project/tests` is a good choice indeed.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/83323642
has text: Not a problem, you'd be surprised just how many don't figure out that the tick is actually a button.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48141837
type: Comment

http://stackoverflow.com/comment/83022194
type: QuestionComment
has text: Thank you for the effort, but it's no good, I guess I'll just find a workaround, or solve it a later date.
comment on: http://stackoverflow.com/q/48023433
score: 0
type: Comment

http://stackoverflow.com/a/48058137
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/83596929
has comment: http://stackoverflow.com/comment/83596847
has body: You can have a second scatter plot, red coloured and with a higher zorder, and update its points: import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import random plt.ion() def update(time, red_plotted_points, points, N): indexes = set([random.choice(range(N)) for i in range(int(N/2))]) # for instance! new_points = [points[i] for i in indexes] red_plotted_points.set_offsets(new_points) def animate(N): x = [random.random() for val in range(N)] y = [random.random() for val in range(N)] points = [[x[i], y[i]]for i in range(N)] fig = plt.figure() ax = fig.add_subplot(111) plotted_points = ax.scatter(x, y, color='gray', zorder=1) red_plotted_points = ax.scatter([], [], color='red', zorder=2) # starts empty fargs = (red_plotted_points, points, N) ani = FuncAnimation(fig, update, frames=range(100), fargs=fargs, interval=200, repeat=True) ani._start() fig.show() return fig, ani if __name__ == '__main__': fig, ani = animate(100) (python 2.7.14, matplotlib 2.1.1) Edit: Updated to also run on Python 3.6.3, matpotlib 2.1.0 I'm not sure why, but it seems that if a reference is not kept to the FuncAnimation it does not work on Python 3.6. Thanks to Joel (comments) for noticing.
has comment: http://stackoverflow.com/comment/83569818
downvote count: 0
answers question: http://stackoverflow.com/q/48055581
type: Answer

http://stackoverflow.com/comment/83059366
comment on: http://stackoverflow.com/a/48043157
type: AnswerComment
score: 0
type: Comment
has text: @poke I knew that stuff already. And I'm not repeating the call thousand times, I call only once. The function *is* correct (as far as I can tell), so I don't know why you're talking about that. Anyway... yes, timeit is better in general and I use it a lot, but do you really think it's needed when I'm showing that my function is orders of magnitude faster? Who cares whether it's 50 times or 100 times? That's not the point. Oh well, here's a timeit way (and I increased the data size): https://ideone.com/nuZKEZ

http://stackoverflow.com/q/48048780
has title: Is there a difference between storing the Selenium functions into a variable and not storing it?
score: 1
type: Question
has answer: http://stackoverflow.com/a/48048866
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48049433
answer count: 3
tagged with: python
has body: I've been playing around with Selenium and Python lately, and one thing that came up through using Selenium were the functions calls, such as .find_element_by_name. You can either store call into a variable or not. I'm wondering... Are there any differences and benefits to storing the functions or using the functions, like so? This... elem = driver.find_element_by_name('Hello') elem.click() or... driver.find_element_by_name('Hello').click()
type: UnansweredQuestion
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/48052343

django-rest-framework
tags question: http://stackoverflow.com/q/48048066
tags question: http://stackoverflow.com/q/48116081
tags question: http://stackoverflow.com/q/48118743
tags question: http://stackoverflow.com/q/48131440
tags question: http://stackoverflow.com/q/48070027
tags question: http://stackoverflow.com/q/48159489
tags question: http://stackoverflow.com/q/48153585
tags question: http://stackoverflow.com/q/48161312
tags question: http://stackoverflow.com/q/48037755
tags question: http://stackoverflow.com/q/48095529
tags question: http://stackoverflow.com/q/48061510
type: Tag
tags question: http://stackoverflow.com/q/48018081
tags question: http://stackoverflow.com/q/48163020
tags question: http://stackoverflow.com/q/48158309
tags question: http://stackoverflow.com/q/48094617
tags question: http://stackoverflow.com/q/48087416
tags question: http://stackoverflow.com/q/48161525
tags question: http://stackoverflow.com/q/48125311
tags question: http://stackoverflow.com/q/48036832
tags question: http://stackoverflow.com/q/48061834
tags question: http://stackoverflow.com/q/48162727
tags question: http://stackoverflow.com/q/48152574
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/48054019
tags question: http://stackoverflow.com/q/48110659
tags question: http://stackoverflow.com/q/48043895
tags question: http://stackoverflow.com/q/48067955
tags question: http://stackoverflow.com/q/48148711
tags question: http://stackoverflow.com/q/48016376
tags question: http://stackoverflow.com/q/48082819
tags question: http://stackoverflow.com/q/48098140

http://stackoverflow.com/q/48123861
has answer: http://stackoverflow.com/a/48124297
has body: I tried using python library for spell-check,correcting and replacing. For some complex spelling correction, I need to have a second opinion and to see replaced word underlined or strike through. Even if the file output is in rtf format, it is ok. How to solve it? Efforts so far. import enchant from enchant.checker import SpellChecker chkr = SpellChecker("en_UK","en_US") spacedfile = "This is a setence. It has speeelinng mistake." chkr.set_text(spacedfile) for err in chkr: sug = err.suggest()[0] err.replace(sug) Spellchecked = chkr.get_text() print Spellchecked Output: This is a sentence. It has spelling mistake. Expected outcome: This is a **sntence** sentence. It has **speeelinng** spelling mistake."
tagged with: python
tagged with: rtf
type: AnsweredQuestion
score: 3
has title: Spelling mistakes - Pyenchant
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/48124297
tagged with: pyenchant
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/83032360
comment on: http://stackoverflow.com/q/48031020
has text: I don't think that's true. The version of the problem statement I just found says something different. Please show a link to the version you're reading.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83279212
type: QuestionComment
score: 2
has text: The same way you would do it by hand. Calculate the next number from the prvious two. No recursion needed. No storing of more than the prvious 2 values needed.
comment on: http://stackoverflow.com/q/48150328
type: Comment

http://stackoverflow.com/comment/83064078
comment on: http://stackoverflow.com/q/48045799
has text: can't you get all in one query ? And you should do this in separated function (with parameter) which you could execute many times to get different questions. In `__init__` you shpuld put only empty labels.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83189427
type: QuestionComment
has text: @LutzL Thanks. It works. do you want to post that as an answer so that I'll accept it?
comment on: http://stackoverflow.com/q/48088890
score: 0
type: Comment

http://stackoverflow.com/comment/83275911
type: AnswerComment
comment on: http://stackoverflow.com/a/48148414
has text: Yes, for multiindex in index need `df2[df2.columns.get_level_values(0).isin(indicators_list)])`
type: Comment
score: 0

http://stackoverflow.com/comment/83185391
has text: Made changes to your validators, it should work now.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48104746

http://stackoverflow.com/q/48129944
has body: This command i got from perforce manual: p4 group -o group_name | grep -v user_name | p4 group -i How can i use this command in my script using method p4.run()
score: -1
answer count: 1
downvote count: 1
tagged with: perforce
type: UnansweredQuestion
tagged with: p4python
has title: I want to delete user from perforce group through my python script
upvote count: 0
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48130214

http://stackoverflow.com/a/68532516
downvote count: 0
type: Answer
has body: #where x is a series x = x.str.lstrip('0')
answers question: http://stackoverflow.com/q/48139274
score: 1
upvote count: 1

http://stackoverflow.com/comment/83280072
has text: Use super() https://docs.python.org/3/library/functions.html#super
type: QuestionComment
comment on: http://stackoverflow.com/q/48150871
score: 2
type: Comment

retry-logic
type: Tag
tags question: http://stackoverflow.com/q/48081129
tag name: retry-logic

http://stackoverflow.com/comment/83303673
has text: This is absolutely a duplicated question but I forget which question it is duplicated with ... Could someone help to flag as duplicated?
score: 0
comment on: http://stackoverflow.com/q/48162069
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83180209
type: AnswerComment
comment on: http://stackoverflow.com/a/48102182
type: Comment
has text: Thanks a lot Sir, your response was really informative and helpful. Would be testing Galen and as you mentioned checking the rendering or the overal layout of html in an automated fashion is something very challenging,as the results I am getting by methods still required manual touch points. Thanks a lot again :-)
score: 0

http://stackoverflow.com/comment/83265072
type: QuestionComment
has text: I'm not quite getting what you want, can you provide a simple mock up image of what you want to achieve?
score: 0
comment on: http://stackoverflow.com/q/48143233
type: Comment

http://stackoverflow.com/q/48107204
tagged with: python
has title: What causes the discrepancy from HMAC functions in R vs Python when using .digest()?
has comment: http://stackoverflow.com/comment/83190281
answer count: 0
tagged with: ibm-cloud-storage
has comment: http://stackoverflow.com/comment/83190077
has comment: http://stackoverflow.com/comment/83189978
type: Question
tagged with: amazon-web-services
tagged with: hmac
has comment: http://stackoverflow.com/comment/83190433
has body: I am trying to write some functions to connect to IBM Cloud Object Storage using AWS Version 4 signing protocols. There's some boilerplate code for doing this that works in Python over here, but when I try to convert the code to R I find myself in a conundrum. When using HMAC functions in R &amp; Python the .hexdigest() method yields identical outputs for the same string in both languages: # Python import hmac import hashlib &gt;&gt;&gt; hmac.new("key", "message".encode('utf-8'), hashlib.sha256).hexdigest() '6e9ef29b75fffc5b7abae527d58fdadb2fe42e7219011976917343065f58ed4a # R library(digest) &gt; hmac("key", enc2utf8("message"), "sha256") [1] "6e9ef29b75fffc5b7abae527d58fdadb2fe42e7219011976917343065f58ed4a" If you use the .digest() method in Python from the crypto library - which the code from AWS/IBM suggests - then you get ASCII output. I am able to approximate this ASCII output in R by changing the hmac() output to raw and then converting to character. Below you can see it is not exactly the same - though it is close. # Python &gt;&gt;&gt; hmac.new("key", "message".encode('utf-8'), hashlib.sha256).digest() "n\x9e\xf2\x9bu\xff\xfc[z\xba\xe5'\xd5\x8f\xda\xdb/\xe4.r\x19\x01\x19v\x91sC\x06_X\xedJ" # R &gt; rawToChar(hmac("key", "message", "sha256", raw = T)) [1] "n\x9e\xf2\x9bu\xff\xfc[z\xba\xe5'Տ\xda\xdb/\xe4.r\031\001\031v\x91sC\006_X\xedJ" What is causing the discrepancy here? The source code and docs for .digest() says that it returns a string of 8-bit data that may contain non-ASCII bytes. How can I replicate this output in R? Ultimately I believe this is what is causing my signatures to fail when trying to authenticate with IBM Cloud Object Storage. Any help or alternative suggestions for HMAC libraries in Python/R would be greatly appreciated!
tagged with: http://stackoverflow.com/tag/r
score: 0
has comment: http://stackoverflow.com/comment/83190160
has comment: http://stackoverflow.com/comment/83190369
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83190189

http://stackoverflow.com/q/48150242
type: UnansweredQuestion
tagged with: facebook-ads-api
tagged with: facebook-marketing-api
tagged with: python
type: Question
has title: "Invalid OAuth access token" on Marketing API in Python
has answer: http://stackoverflow.com/a/49708318
has body: I'm trying to access Facebook Marketing Api in Python, but I encounter some issues with the access token. I run the following code: def get_app_access_token(app_id, app_secret): args = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret} f = urllib2.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args)) resp = json.loads(f.read()) ### resp gives me {"access_token":"xxxxxx|yyyyyy", "token_type":"bearer"} ### so I extract yyyyyy as my access_token result = resp["access_token"].split('|')[1] access_token = get_app_access_token(APP_ID, SECRET_KEY) api = FacebookAdsApi.init(APP_ID, SECRET_KEY, access_token) account = AdAccount(AD_ACCOUNT) adsets = account.get_ad_sets(fields=[AdSet.Field.name]) And I get the error "Invalid OAuth access token" on the last line. Do you know what I did wrong? Thank you!
score: 0
answer count: 1
tagged with: oauth
tagged with: access-token

http://stackoverflow.com/comment/83113901
has text: @furas cool, thanks. ill take a look. will it natively support the depth-nested list like ive presented in the output above?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48068596

http://stackoverflow.com/a/48038993
upvote count: 6
has comment: http://stackoverflow.com/comment/83048371
score: 6
has comment: http://stackoverflow.com/comment/83048794
has comment: http://stackoverflow.com/comment/83048359
answers question: http://stackoverflow.com/q/48038958
has comment: http://stackoverflow.com/comment/83048541
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48038958
has comment: http://stackoverflow.com/comment/104435866
type: Answer
has body: Ok this got a bit more complicated. Normally I'd try something with transform but I'd be glad if someone had something better than the following: Use groupby and send df to func where df.loc is used, lastly use pd.concat to glue the dataframe together again: import pandas as pd data = {'matchID': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 2, 9: 2, 10: 2, 11: 2, 12: 2, 13: 2, 14: 2, 15: 2}, 'court': {0: 'A', 1: 'D', 2: 'D', 3: 'A', 4: 'A', 5: 'A', 6: 'D', 7: 'D', 8: 'A', 9: 'D', 10: 'D', 11: 'A', 12: 'A', 13: 'A', 14: 'D', 15: 'D'}, 'speed': {0: 100, 1: 200, 2: 300, 3: 100, 4: 120, 5: 250, 6: 110, 7: 100, 8: 100, 9: 200, 10: 300, 11: 100, 12: 120, 13: 250, 14: 110, 15: 100}, 'server': {0: 1, 1: 2, 2: 3, 3: 4, 4: 1, 5: 2, 6: 3, 7: 4, 8: 1, 9: 2, 10: 3, 11: 4, 12: 1, 13: 2, 14: 3, 15: 4}} df = pd.DataFrame(data) def func(dfx): dfx['meanSpeedCourtA13'],dfx['meanSpeedCourtD13'] = \ (dfx.loc[(dfx.server.isin((1,3))) &amp; (dfx.court == 'A'),'speed'].mean(), dfx.loc[(dfx.server.isin((1,3))) &amp; (dfx.court == 'D'),'speed'].mean()) return dfx newdf = pd.concat(func(dfx) for _, dfx in df.groupby('matchID')) print(newdf) Returns court matchID server speed meanSpeedCourtA13 meanSpeedCourtD13 0 A 1 1 100 110.00 205.00 1 D 1 2 200 110.00 205.00 2 D 1 3 300 110.00 205.00 3 A 1 4 100 110.00 205.00 4 A 1 1 120 110.00 205.00 5 A 1 2 250 110.00 205.00 6 D 1 3 110 110.00 205.00 7 D 1 4 100 110.00 205.00 8 A 2 1 100 110.00 205.00 9 D 2 2 200 110.00 205.00 10 D 2 3 300 110.00 205.00 11 A 2 4 100 110.00 205.00 12 A 2 1 120 110.00 205.00 13 A 2 2 250 110.00 205.00 14 D 2 3 110 110.00 205.00 15 D 2 4 100 110.00 205.00

http://stackoverflow.com/comment/83032400
type: QuestionComment
comment on: http://stackoverflow.com/q/48031020
has text: Your application of `Decimal` was wrong. You did the division *before* you converted to decimal.
score: 4
type: Comment

http://stackoverflow.com/q/48063266
type: AnsweredQuestion
tagged with: anaconda
score: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48065679
downvote count: 0
has comment: http://stackoverflow.com/comment/83102162
tagged with: scikit-learn
has title: "from sklearn.preprocessing import LabelEncoder, OneHotEncoder" fails after update of packages in Anaconda
possible better answer: http://stackoverflow.com/a/49595449
has answer: http://stackoverflow.com/a/49595449
has comment: http://stackoverflow.com/comment/83099996
has body: recently I updated packages in anaconda in order to install keras, and tensorflow. Now my program fails on the next line: from sklearn.preprocessing import LabelEncoder, OneHotEncoder. Traceback (most recent call last): File "&lt;ipython-input-1-83540d56f55d&gt;", line 1, in &lt;module&gt; from sklearn.preprocessing import LabelEncoder, OneHotEncoder File "/Users/teologov/anaconda/lib/python3.6/site-packages/sklearn/__init__.py", line 134, in &lt;module&gt; from .base import clone File "/Users/teologov/anaconda/lib/python3.6/site-packages/sklearn/base.py", line 13, in &lt;module&gt; from .utils.fixes import signature File "/Users/teologov/anaconda/lib/python3.6/site-packages/sklearn/utils/__init__.py", line 11, in &lt;module&gt; from .validation import (as_float_array, File "/Users/teologov/anaconda/lib/python3.6/site-packages/sklearn/utils/validation.py", line 18, in &lt;module&gt; from ..utils.fixes import signature File "/Users/teologov/anaconda/lib/python3.6/site-packages/sklearn/utils/fixes.py", line 144, in &lt;module&gt; from scipy.sparse.linalg import lsqr as sparse_lsqr # noqa File "/Users/teologov/anaconda/lib/python3.6/site-packages/scipy/sparse/linalg/__init__.py", line 114, in &lt;module&gt; from .isolve import * File "/Users/teologov/anaconda/lib/python3.6/site-packages/scipy/sparse/linalg/isolve/__init__.py", line 6, in &lt;module&gt; from .iterative import * File "/Users/teologov/anaconda/lib/python3.6/site-packages/scipy/sparse/linalg/isolve/iterative.py", line 7, in &lt;module&gt; from . import _iterative ImportError: dlopen(/Users/teologov/anaconda/lib/python3.6/site-packages/scipy/sparse/linalg/isolve/_iterative.cpython-36m-darwin.so, 2): Library not loaded: @rpath/libgfortran.3.dylib Referenced from: /Users/teologov/anaconda/lib/python3.6/site-packages/scipy/sparse/linalg/isolve/_iterative.cpython-36m-darwin.so Reason: image not found Could you please help me to fix it.
favorite count: 0
has comment: http://stackoverflow.com/comment/83103805
accepted answer: http://stackoverflow.com/a/48065679
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/83259404
type: Comment
type: QuestionComment
has text: if your account is list of file paths as string, you need to do `for filepath in accounts: with open(filepath) as f`
comment on: http://stackoverflow.com/q/48140773
score: 0

http://stackoverflow.com/q/48058761
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/83090621
has answer: http://stackoverflow.com/a/48062144
type: Question
tagged with: django
tagged with: python
has title: Django project does not recognize installed packages
tagged with: permissions
tagged with: pycharm
score: 0
answer count: 1
has body: I made two projects using Pycharm (1st one is Python project and 2nd is Django project) and below are the screenshots for the installed packages I don't understand why Django project does not recognize my packages but Python project does recognize. Python version is also same i.e. Python3.5. I also checked the permission issues but you can see below there are similar permissions. user@user3 PycharmProjects]$ ls -l total 0 drwxr-xr-x. 8 user users 208 Dec 14 12:52 RMUE-APP drwxr-xr-x. 6 user users 80 Jan 2 10:51 RmueWeb Please guide me know what should I do to make it work ?
has comment: http://stackoverflow.com/comment/83091146
type: UnansweredQuestion

http://stackoverflow.com/comment/83071043
type: QuestionComment
comment on: http://stackoverflow.com/q/48049557
has text: That library doesn't care about loops, so yes, probably
score: 0
type: Comment

http://stackoverflow.com/comment/99583383
type: AnswerComment
has text: Sure but I know how to deal with the acquisition of images via PySpin and passing it to cv2 via a conversion. (cat and mice still on board ;-) This answer is specifically intended to help people avoid making that mistake and break their teeth on it. Hence the "NOT working" warning ;0
score: 0
type: Comment
comment on: http://stackoverflow.com/a/56496750

http://stackoverflow.com/comment/83301154
has text: I was thinking similar to #1, except each view would pass a parameter like "Question 3" that is rendered on the HTML page but hidden. There'd be a javscript/jquery function that grabs the node (eg with class="hidden") and render dynamic images / animations based on that question (eg if p = 'question 3'). Howevcer the images/animations would be stored externally so they wouldn't have to load on the page and it would be easier to maintain. Oh reason I don't store questions in database is because the questions are dynamically generated -- well, the value of the numbers used in them.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48160815
type: Comment

http://stackoverflow.com/a/51355271
type: Answer
has comment: http://stackoverflow.com/comment/111527191
answers question: http://stackoverflow.com/q/48160535
downvote count: 0
score: 1
has body: You can use async worker-class and then you won't need to set the timeout to 20 minutes. The default worker class is sync. Docs regarding the workers here. Use the eventlet async worker (gevent not recommended if using google client libraries) pip install eventlet Then in your gunicorn instantiation set the worker-class = 'eventlet' and set number of workers to [number of cores] x 2 +1 (that's just a recommendation in google docs). For example: CMD exec gunicorn --worker-class eventlet --workers 3 -b :$PORT main:app Gunicorn Worker Configuration Alternatively, use implementation described here using pubsub and workers.
upvote count: 1
has comment: http://stackoverflow.com/comment/125902414

http://stackoverflow.com/q/48171953
has answer: http://stackoverflow.com/a/48172999
accepted answer: http://stackoverflow.com/a/48172999
answer count: 2
has comment: http://stackoverflow.com/comment/83323966
tagged with: concatenation
downvote count: 0
tagged with: string
favorite count: 0
has body: My main problem is this: I have a set of files, and I am concatenating them this way in python: sys.stdout=open("out.dat","w") filenames = ['bla.txt', 'bla.txt', 'bla.txt'] with open('out.dat', 'w') as outfile: for fname in filenames: with open(fname) as infile: outfile.write(infile.read()) with open('out.dat') as f: print "".join(line.strip() for line in f) sys.stdout.close() The bla.txt file looks like aaa and the intention is to make it look like aaaaaaaaa (3 times the same string, not on a new line each time...) for some reason what I do produces an output that looks like aaaaaa a I am not sure why this is happening and if there is a simpler/more elegant solution. More second problem is that eventually, my plan is to have a number of different files (letter triplets for example) that I could concatenate in all possible combinations: aaabbbccc,aaacccbbb, ...,etc Any guidance appreciated! Thank you!
has title: python file concatenation and combining files
has comment: http://stackoverflow.com/comment/83323698
tagged with: python
possible better answer: http://stackoverflow.com/a/48172372
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48172372
has comment: http://stackoverflow.com/comment/83323891
type: Question
has comment: http://stackoverflow.com/comment/83323578
linked to: http://stackoverflow.com/q/18028504

http://stackoverflow.com/comment/83217618
type: Comment
has text: InvalidArgumentError: logits and labels must be same size: logits_size=[1,100] labels_size=[100,100] [[Node: train/SoftmaxCrossEntropyWithLogits = SoftmaxCrossEntropyWithLogits[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](train/Reshape, train/Reshape_1)]] .....after changing it to int(val[:, -1, :].get_shape()[1]) -1, almost getting there, now if I can only figure out the difference in shapes.
comment on: http://stackoverflow.com/a/48116463
score: 0
type: AnswerComment

http://stackoverflow.com/a/48061850
downvote count: 0
has comment: http://stackoverflow.com/comment/83096989
has body: The slicing method work's fine, but you need to create a valid image, mask_face need to be a rgb image: mask_face = np.zeros(RGB_img.shape[:2] + (3,), np.uint8) Then you can use slicing method or just draw a rectangle like Maxime Guinin answer UPDATE to improve answer. RGB images are multidimensional arrays with 3 dimensions (height, width and color channels), so, when you created mask_face you missed color channels, then + (3,) to add this. This is like blank rgb_image is created, the first arg can be a list or a tuple: blank_image = np.zeros((height, width, 3), np.uint8)
type: Answer
has comment: http://stackoverflow.com/comment/83096305
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48061623
has comment: http://stackoverflow.com/comment/83097211

http://stackoverflow.com/a/53104620
score: 1
upvote count: 1
has body: you could also use if message.content.lower().startswith('command'): doesnt necessarily have to be startswith
type: Answer
answers question: http://stackoverflow.com/q/48120312
downvote count: 0

http://stackoverflow.com/q/48148840
has answer: http://stackoverflow.com/a/48151391
score: 0
answer count: 2
tagged with: apache-spark
accepted answer: http://stackoverflow.com/a/48151391
possible better answer: http://stackoverflow.com/a/48149814
has answer: http://stackoverflow.com/a/48149814
has body: I'm trying to distribute some text extraction from PDFs between multiple servers using Spark. This is using a custom Python module I made and is an implementation of this question. The 'extractTextFromPdf' function takes 2 arguments: a string representing the path to the file, and a configuration file used to determine various extraction constraints. In this case the config file is just a simple YAML file sitting in the same folder as the Python script running the extraction and the files are just duplicated between Spark servers. The main issue I have is being able to call my extract function using the filename as the first argument, rather than the file's content. This is the basic script I have as of now, running it on 2 PDFs in the files folder: #!/usr/bin/env python3 import ScannedTextExtractor.STE as STE from pyspark import SparkContext sc = SparkContext("local", "STE") input = sc.binaryFiles("/home/ubuntu/files") processed = input.map(lambda filename, content: (STE.extractTextFromPdf(filename,'ste-config.yaml'), content)) print("Results:") print(processed.take(2)) This creates the lambda error Missing 1 position argument: 'content'. I don't really care about using the PDFs raw content and since the argument to my extraction function is just the path to the PDF, not the actual PDF content itself, I tried to just give 1 argument to the lambda function. e.g. processed = input.map(lambda filename: STE.extractTextFromPdf(filename,'ste-config.yaml')) But then I get issues because with this setup Spark sets the PDF content (as a byte stream) as this singular argument, but my module expects a string with the path to the PDF as the first arg, not the whole byte content of the PDF. I printed the RDD of the binary file loading by the SparkContext and I can see that in there is both the filename and the file content (a byte stream of the PDF) in the RDD. But how do I use it with my custom Python module that expects the following snytax: STE.extractTextFromPDF('/path/to/p…
tagged with: python
tagged with: rdd
tagged with: lambda
type: AnsweredQuestion
has title: Spark - missing 1 required position argument (lambda function)
type: Question
linked to: http://stackoverflow.com/q/48142859
tagged with: pyspark

http://stackoverflow.com/a/48046922
answers question: http://stackoverflow.com/q/48040685
type: Answer
accepted answer of: http://stackoverflow.com/q/48040685
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/88726452
has body: Worked it out! After digging through a lot of examples (most were in higher level frameworks such as Keras which is a pain) I discovered that you have to create a mask! Seems simple in retrospect. Here's the code to create a mask of 1's and 0's and then element-wise multiply it against the matrix (which would be the cost values) x = tf.placeholder(tf.float32) seq = tf.placeholder(tf.int32) def mask_by_length(input_matrix, length): ''' Input matrix is a 2d tensor [batch_size, time_steps] length is a 1d tensor length refers to the length of input matrix axis 1 ''' length_transposed = tf.expand_dims(length, 1) # Create range in order to compare length to range = tf.range(tf.shape(input_matrix)[1]) range_row = tf.expand_dims(range, 0) # Use the logical operations to create a mask mask = tf.less(range_row, length_transposed) # cast boolean to int to finalize mask mask_result = tf.cast(mask, dtype=tf.float32) # Element-wise multiplication to cancel out values in the mask result = tf.multiply(mask_result, input_matrix) return result mask_values = mask_by_length(x, seq) input vals (time-major) [time_steps, batch_size] [[ 0.71, 0.22, 1.42, -0.28, 0.99] [ 0.41, 2.24, 0.09, 0.74, 0.65]] sequence vals [batch_size] [2, 3] output (time-major) [time_steps, batch_size] [[ 0.71, 0.22, 0, 0, 0, ] [ 0.41, 2.24, 0.09, 0, 0, ]]
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48096985
has comment: http://stackoverflow.com/comment/83169385
upvote count: 2
has comment: http://stackoverflow.com/comment/83211335
has comment: http://stackoverflow.com/comment/83212864
score: 2
accepted answer of: http://stackoverflow.com/q/48096935
answers question: http://stackoverflow.com/q/48096935
has comment: http://stackoverflow.com/comment/83213354
has comment: http://stackoverflow.com/comment/83211141
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83212491
has comment: http://stackoverflow.com/comment/83211768
type: Answer
has comment: http://stackoverflow.com/comment/83175842
has body: That's not a corresponding ASCII string, it's a UTF-8 string. ASCII, definitionally, cannot represent the whole of the Unicode range; UTF-8 can. To perform the conversion, use the .encode method of unicode objects: u'S\xe9parateur'.encode('utf-8') produces 'S\xc3\xa9parateur'.

http://stackoverflow.com/q/48032532
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48037456
has body: First of all there might be more mistakes in my code than I know, the fact that I am new I do not understand everything at all. I am trying to index my table like the following picture: I am reading columns a and b incrementally and appending them together, in total I read 500 files with each 15000 rows. Now I need to MultiIndex them like in the following picture but I couldn't find a way to do that within a loop, with pandas hierarchical index and MultIndex. Is there a way to do it with a loop for all of the datapoints and numbers? all_data = pd.DataFrame() for f in glob.glob("path_in_dir"): df = pd.read_table(f, delim_whitespace=True, names=('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'), dtype={'A': np.float32, 'B': np.float32, 'C': np.float32, 'D': np.float32,'E': np.float32, 'F': np.float32, 'G': np.float32,'H': np.float32}) all_data = all_data.append(df,ignore_index=True) all_data.index.names = ['numbers'] show all data print(all_data) I am using append but I read somewhere that is also not efficient like pd.concat which would be important to increase the speed and reduce memory usage. When I try it in this way: all_data = pd.concat(df,ignore_index=True) I get the error: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame" At the moment I only get the d columns but counting from 0 to the end of the rows, so for 2 files till 30000. So i am not splitting the counting to each files datapoint. When I extend the index to: `all_data.index.names =[datapoints, numbers] get the message ValueError: Length of new names must be 1, got 2
has comment: http://stackoverflow.com/comment/83088980
has title: Hierarchical MultIndex table with loop with Python
tagged with: indexing
has comment: http://stackoverflow.com/comment/83069536
type: Question
score: 0
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/83047119
tagged with: tabular
has comment: http://stackoverflow.com/comment/83101063
has comment: http://stackoverflow.com/comment/83100510
tagged with: python
has comment: http://stackoverflow.com/comment/83062527
has comment: http://stackoverflow.com/comment/83048170
has comment: http://stackoverflow.com/comment/83038771
has comment: http://stackoverflow.com/comment/83045476

http://stackoverflow.com/comment/83199221
type: Comment
score: 0
type: AnswerComment
has text: You should elaborate, not just fix his code. Explain what is going wrong.
comment on: http://stackoverflow.com/a/48109436

http://stackoverflow.com/comment/83032393
type: Comment
has text: Very helpful. My understanding is that if I want to run my app on another computer, I would only need to send over my 'client_secret.json' file, as that file alone would allow me to generate a new 'sheets.googleapis.com-python-quickstart.JSON' file on a new computer that doesn't have that file already. Is that correct?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48031053

http://stackoverflow.com/a/48125762
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48125674
has body: The general strategy is to read, store, and plot all the data, only calling plt.show() after everything has been plotted. As a simple example, consider plt.plot(range(10)) plt.plot(range(0, 20, 2)) plt.show() Here is the result:

http://stackoverflow.com/a/48163549
answers question: http://stackoverflow.com/q/48162876
has body: Maybe a list comprehension is enough? difficulty = input("Choose an option between easy/medium/hard: ") with open('quiz_scores.txt', 'r') as f: lines = sorted(list(filter(lambda line: line.split(',')[2] == difficulty, f.readlines()))) lines = reversed(lines) # python 3 for line in lines: print(line) If you are using Python 2, sort lines with lines = sorted(list(filter(lambda line: line.split(',')[2] == difficulty, f.readlines())), reversed=True)
score: 0
has comment: http://stackoverflow.com/comment/83423220
has comment: http://stackoverflow.com/comment/83760262
type: Answer
has comment: http://stackoverflow.com/comment/83776862

http://stackoverflow.com/comment/83142715
has text: @WillemVanOnsem `type(models.TextField)` >>> `type`. What is a `type`?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48083629

http://stackoverflow.com/a/77165731
has body: The accepted answer did not work for me, so I made my own, similar one. Replace result with Data. Remember to add row_factory, so when doing SELECT * tables, so you can use headers, and insert them as top row of the table. That is what first 3 rows do. The rest of the code: Create list of column lengths, initially fill them with 0 * number of first row items (which is also header). For each cell in row, if width of a cell is less than maximum width of that column, set maximum to current cell width. Print cell in each row, replacing None with spaces, and adding offset. cursor.row_factory = sqlite3.Row result=cursor.execute( 'select rowlong as info,games,roms,disks,samples,roms_disks_samples as all_files from stats' ).fetchall() result.insert( 0, (result[0].keys()) )#insert column names as first row (position 0); 'cursor.row_factory = sqlite3.Row' must be used before int_offset = 2 ls_int_max_column_length = [0] * len( result[0] ) for row in result: for i in range(len(row)): int_cell_space = len( str( row[i] ) ) if ls_int_max_column_length[i] < int_cell_space: ls_int_max_column_length[i] = int_cell_space #print(ls_int_max_column_length) print("") for row in result: for i in range(len(row)): print ( str(row[i]).ljust( ls_int_max_column_length[i] + int_offset ).replace('None',' ') , end = " ") #print ( str(row[i]) , end = " ") print("") print("") cursor.row_factory = None #set it back to None You could do it manually, but it is not recommended, what if the length changes: print("") for row in result: print ( str(row[0]).ljust(38), str(row[1]).ljust(25).replace('None',' '), str(row[2]).ljust(21).replace('None',' '), str(row[3]).ljust(16).replace('None',' '), str(row[4]).ljust(8).replace('None',' '), str(row[5]).ljust(9).replace('None',' ')) print("")
type: Answer
answers question: http://stackoverflow.com/q/48138015
score: 0

http://stackoverflow.com/a/48125756
score: 0
has body: If you're interested, why it's computed this way, it's the backpropagation through cross-entropy loss: probs is the vector of class probabilities (computed in a forward pass via softmax). delta3 is the error signal from the loss function. y holds the ground truth classes for the mini-batch. Everything else is just a math, which is well explained in this post and they end up with the same numpy expression.
type: Answer
answers question: http://stackoverflow.com/q/48125575

http://stackoverflow.com/q/48067824
answer count: 1
tagged with: convolution
type: UnansweredQuestion
tagged with: python
has body: I've got two tensors, x = shape(batchsize, 29, 64), y = shape(batchsize, 29, 29, 64) I want to iterate row-wise over y, perform an elementwise multiplication with x, sum_reduce the result, and stack those results to a new tensor. The result should be of a shape (batchsize, 29, 64). It's quite similar to a convolution. How I would program it sequentially: for batchnr in range(x.shape[0]): for n in range(y.shape[1]): temp = tf.multiply(x[batchnr][n], y[batchnr]) #shape(29,64) prod = tf.reduce_sum(temp) # shape(1,64) res[batchnr][n] = prod I've created that explanation figure: Since reduce_sum is done for each row, the result is a tensor of shape (batchsize, 29, 64) again. I can't figure out how to do it right and efficient. Thank you.
has answer: http://stackoverflow.com/a/48116904
tagged with: tensorflow
has title: Tensorflow: Iterate row-wise, elementwise multiplication, reduce-sum. Custom convolution
tagged with: matrix-multiplication
type: Question
score: 0
tagged with: deep-learning

http://stackoverflow.com/a/48161671
answers question: http://stackoverflow.com/q/48161405
has body: A dictionary is an unordered associative table. This means that you cannot rely on the order of the key-value pairs when you iterate through it with a for-each loop. It's not an error on your part, it's the designed behaviour for dictionaries. You can have a list of keys, that will keep the order you like for outputs: subjects = ['Je', 'Tu', 'Il ou Elle', 'Nous', 'Vous', 'Ils ou Elles'] terminaisons = ['e', 'es', 'e', 'ons', 'ez', 'ent'] for subject, terminaison in zip(subjects, terminaisons): print(subject, terminaison) This doesn't make use of a dictionary though. If you want to play and test a dictionary, you can write the following: conjugaisonTable = {subject: terminaison for subject, terminaison in zip(subjects, terminaisons)} for subject in subjects: print(subject, conjugaisonTable[subject])
has comment: http://stackoverflow.com/comment/83326173
score: 0
type: Answer

http://stackoverflow.com/comment/83321096
type: Comment
comment on: http://stackoverflow.com/a/48156548
has text: This worked perfectly! Would yo be able to explain why you needed to convert the row object to a dict?
score: 0
type: AnswerComment

http://stackoverflow.com/q/48081690
tagged with: math
has body: How do I find a user defined amount of points on a circumference of a circle. Then when it has been found, place it in a 2 dimensional array for later use. For a slightly better view of it: Thanks for all the help :)
type: Question
has comment: http://stackoverflow.com/comment/83163215
accepted answer: http://stackoverflow.com/a/48085289
has answer: http://stackoverflow.com/a/48081884
upvote count: 3
answer count: 3
has comment: http://stackoverflow.com/comment/83137763
downvote count: 0
has answer: http://stackoverflow.com/a/48085289
favorite count: 0
possible better answer: http://stackoverflow.com/a/48081885
has comment: http://stackoverflow.com/comment/83144054
has title: How to find points on a circumference
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/48081885
type: AnsweredQuestion
score: 3

attributeerror
tags question: http://stackoverflow.com/q/48050714
type: Tag
tags question: http://stackoverflow.com/q/48020987
tags question: http://stackoverflow.com/q/48052125
tag name: attributeerror
tags question: http://stackoverflow.com/q/48066371
tags question: http://stackoverflow.com/q/48040794

http://stackoverflow.com/q/48052848
score: -1
has title: create lattice in tkinter
tagged with: tkinter-canvas
has body: I would like to make a grid/lattice of particles on my tinter canvas. I would then like these particles to move using the canvas.move function reading the coordinates from a text file. I tried to make the lattice in a loop. from Tkinter import * import random import time import csv tk = Tk() N = 100 T = 500 canvas = Canvas(tk, width=100, height=100) tk.title("Test") canvas.pack() n = 5 t = 10 step1 = [] step2 = [] textFile1 = open('/Users/francislempp/Desktop/major project/C++ programs/Molecular Dynamics 2D/Molecular_Dynamics_2D- gupnvjunowwmjcfiyoursdhzytow/Build/Products/Debug/motionX', 'r') lines = textFile1.readlines() for line in lines: step1.append(line.split(" ")) textFile2 = open('/Users/francislempp/Desktop/major project/C++ programs/Molecular Dynamics 2D/Molecular_Dynamics_2D-gupnvjunowwmjcfiyoursdhzytow/Build/Products/Debug/motionY', 'r') lines = textFile2.readlines() for line in lines: step2.append(line.split(" ")) class Ball: def __init__(self, color, size, x, y): self.shape = canvas.create_oval(10,10,size,size, fill = color) self.x = x self.y = y def move(self): canvas.move(self.shape, self.x, self.y) pos = canvas.coords(self.shape) if pos[3] &gt;= 100 or pos[1] &lt;= 0: self.y = -self.y if pos[2] &gt; 100 or pos[0] &lt;= 0: self.x = -self.x def delete(self): canvas.delete(self.shape) balls = [] for i in range(99): for j in range(99): xcoord = i*(100/10) + 4 ycoord = j*(100/10) + 4 canvas.create_oval(xcoord,ycoord,2,2, fill = "red") tk.update() tk.mainloop() when i run my code it make ovals which run down the screen and overlap each other. I would like the for loop to place 100 particles inside the canvas with equal spacing.
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83082332
has comment: http://stackoverflow.com/comment/83174307
has comment: http://stackoverflow.com/comment/83084301
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83084320
tagged with: canvas
upvote count: 0
has comment: http://stackoverflow.com/comment/83174355
answer count: 1
has answer: http://stackoverflow.com/a/48056131

http://stackoverflow.com/comment/118877509
type: AnswerComment
type: Comment
has text: For the curios people on how to use the advanced technique of meld the widgets together: see [`toplevel -use`](https://www.tcl.tk/man/tcl8.6/TkCmd/toplevel.htm#M13) and [`toplevel -container`](https://www.tcl.tk/man/tcl8.6/TkCmd/toplevel.htm#M9).
comment on: http://stackoverflow.com/a/48045508
score: 0

http://stackoverflow.com/a/48126239
answers question: http://stackoverflow.com/q/48126043
type: Answer
has body: You were close. Try this: with open('numbers.txt', 'r') as fl: text = fl.read() numbers = [int(n) for n in text.split()] answer = sum(numbers) for n in numbers: print(n) print(answer) this produces: 52 57 63 69 71 78 82 84 95 96 747
score: 0

http://stackoverflow.com/comment/83179047
score: 0
type: Comment
type: QuestionComment
has text: Does my answer satisfy your needs?
comment on: http://stackoverflow.com/q/48099843

http://stackoverflow.com/q/48046028
tagged with: oop
score: 1
has comment: http://stackoverflow.com/comment/83063540
type: Question
accepted answer: http://stackoverflow.com/a/48046043
tagged with: arrays
answer count: 1
downvote count: 0
favorite count: 0
has body: I started object-oriented programming in python and in my program, I decided to store class instances in array, but I don't know how to access class variables now. class apixel(object): def __init__(self): self.posx = random.randint(0, 300) self.posy = random.randint(0, 200) def do_i_exist(): print("Yes i do!") p = [apixel] * 10 for obj in p: obj.do_i_exist() #that works print(obj.posx) #but that does not work
has title: How to access class variables when class instances are stored in array
has answer: http://stackoverflow.com/a/48046043
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/131557619
type: Comment
has text: `right_sum = s - left_sum` `difference = right_sum - left_sum` so `difference = s - left_sum - left_sum` or `difference = s - 2 * left_sum`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/52839149

http://stackoverflow.com/q/48044595
has comment: http://stackoverflow.com/comment/83076504
tagged with: machine-learning
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48874517
score: 1
has answer: http://stackoverflow.com/a/70943369
tagged with: mxnet
linked to: http://stackoverflow.com/q/47427500
has body: I am training a neural network in mxnet that does classification, and I would like to put more weight on some of the classes. So besically, I would like to use a weighted version of mxnet.symbol.SoftmaxOutput. As a toy example, I used a simplified version of this mnist code. Here is the code that defines the network import mxnet as mx mnist = mx.test_utils.get_mnist() batch_size = 100 train_iter = mx.io.NDArrayIter(mnist['train_data'], mnist['train_label'], batch_size, shuffle=True) val_iter = mx.io.NDArrayIter(mnist['test_data'], mnist['test_label'], batch_size) data = mx.sym.var('data') data = mx.sym.flatten(data=data) fc1 = mx.sym.FullyConnected(data=data, num_hidden=15) act1 = mx.sym.Activation(data=fc1, act_type="relu") # MNIST has 10 classes fc2 = mx.sym.FullyConnected(data=act1, num_hidden=10) # Softmax with cross entropy loss mlp = mx.sym.SoftmaxOutput(data=fc2, name='softmax') And here is the code that trains the network: import logging logging.getLogger().setLevel(logging.DEBUG) # logging to stdout # create a trainable module on CPU mlp_model = mx.mod.Module(symbol=mlp, context=mx.cpu()) mlp_model.fit(train_iter, # train data eval_data=val_iter, # validation data optimizer='sgd', # use SGD to train optimizer_params={'learning_rate':0.1}, # use fixed learning rate eval_metric='acc', # report accuracy during training batch_end_callback = mx.callback.Speedometer(batch_size, 100), # output progress for each 100 data batches num_epoch=1) # train for at most 10 dataset passes Now let's say that I want to put more weight on the digit 0. I added the following lines right below the definition of mlp: weight=[[5,1,1,1,1,1,1,1,1,1]] weight_sym = mx.symbol.Variable(name="weight", init=mx.init.Constant(weight), attr={}, shape=(1,10)) mlp=mx.sym.broadcast_mul(mlp,weight_sym) Then when I tried to train, I got the error: TypeError: NDArray does not support assignment with [[5, 1, 1, 1, 1, 1, 1, 1, 1, 1]] of type What would be the proper way to do that?
answer count: 2
tagged with: deep-learning
tagged with: neural-network
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: A weighted version of SoftmaxOutput in mxnet

http://stackoverflow.com/comment/83321968
has text: Is it because you have `z = ... != genes[20000]) & ...` where you meant `z = ... == genes[20000]) & ...`?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48170811
type: QuestionComment

http://stackoverflow.com/a/48080979
type: Answer
has body: I resolved my issue by changing line 20 in the sample code from hexhash = binascii.hexlify(resource.data.bodyHash) to hexhash = resource.data.bodyHash which makes it work. I don't know what the hexlify() was intended for here. I will ask the Evernote guys. The parameter in the error message in my original post was the "hexlified" hash. Btw: in order to determine the bodyHash I'm using the way described here.
score: 0
answers question: http://stackoverflow.com/q/48060263

http://stackoverflow.com/comment/83160290
type: QuestionComment
score: 0
has text: you have no return statement in your function. You are returning from somewhere else with the last line, or the indentation is broken. But if it is an indentation error, you would have an infinite recursion.
type: Comment
comment on: http://stackoverflow.com/q/48088562

http://stackoverflow.com/a/48119925
type: Answer
has comment: http://stackoverflow.com/comment/83217851
has body: I use Atom for python. The best terminal plugin I have found is Platformio. I have a plugin named script that allows me to run python scripts from the editor window. The command also has a shortcut to speed up the process. Load script and it will appear under the packages menu. It also defines the shortcut for 'run script' as the command-I keys. Lately I've been running python script using the Hydrogen plugin. This allows in-line plotting along with running your script. Answers and plots appear in the editor pane. Its very nice if you have to plot.
score: 0
answers question: http://stackoverflow.com/q/48119447

http://stackoverflow.com/a/48037331
answers question: http://stackoverflow.com/q/48037242
upvote count: 1
has body: You can check the length of tr2 (or any other list) and then iterate over all the elements based on the lists length... Or access any specific index in the list if index &lt; length. idx = 1 tab2trs = table2.findAll('tr') tr2 = None if idx &lt; len(tab2trs): tr2 = tab2trs[idx] Or you can add a try except... try: tr2=table2.findAll('tr')[1] except IndexError: pass
downvote count: 0
has comment: http://stackoverflow.com/comment/83045054
type: Answer
has comment: http://stackoverflow.com/comment/83044901
score: 1

http://stackoverflow.com/q/48037755
has comment: http://stackoverflow.com/comment/83075132
has body: I'm using Django 2.0 and DRF 3.7.7(novice with both) and trying to add URL patterns in app_config/urls.py: router = routers.DefaultRouter() router.register(r'^submit_free_account', SubmitFreeAccount, 'SubmitFreeAccount') app_name = 'app_config' #the weird code urlpatterns = [ path('getSourcesNodes', GetSourcesNodes.post, name='GetSourcesNodes'), path('getAppsNodes', GetAppsNodes.post, name='GetAppsNodes'), ] urlpatterns += router.urls And in main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('config/', include('app_config.urls', namespace='app_config')), ] So when I trying to request config/submit_free_account I have 404 errors with strange URL patterns tried by Django: config/ ^$ [name='api-root'] config/ ^\.(?P&lt;format&gt;[a-z0-9]+)/?$ [name='api-root'] How to add router URL patterns correctly in Django 2.0?
score: 3
has comment: http://stackoverflow.com/comment/83053654
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/49005264
downvote count: 0
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/83054008
upvote count: 3
has comment: http://stackoverflow.com/comment/83074957
favorite count: 0
has answer: http://stackoverflow.com/a/48038760
has title: Django 2.0 and DRF 3.7.7 routers
has comment: http://stackoverflow.com/comment/83098983
has answer: http://stackoverflow.com/a/51592574
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: url-routing
has comment: http://stackoverflow.com/comment/83046308

http://stackoverflow.com/comment/83032906
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48030692
has text: @MadPhysicist: Your order is incorrect. `B` must occur before `Z` in the MRO.
score: 0

http://stackoverflow.com/q/48068546
possible better answer: http://stackoverflow.com/a/48068633
tagged with: list
has answer: http://stackoverflow.com/a/48068633
has comment: http://stackoverflow.com/comment/83114300
score: 2
accepted answer: http://stackoverflow.com/a/48068576
downvote count: 0
has body: Let us say I have a text document with lists of numbers in rows. How would I write a function that reads this document and returns a dictonary where the keys represent the row and the values of a key represent the numbers in a certain row, always starting with the smallest number while retaining the order of the others. For example, reading the document: 3 4 1 8 7 6 4 5 2 3 6 should return a dictionary with values: {1: [3], 2: [4], 3: [1, 8, 7, 6, 4], 4: [2, 3, 6, 5]} You see that with the fourth key, the n. 2 took the first place, since it is the smallest one when looking at the 4th row in the document, and so the order was reversed a bit, while it was left untouched for the 3rd, 2nd and 1st row. I started with this already: def to_dictionary(filename): dict1 = {} with open (filename) as file: I am now lacking the knowledge to write up the code that will let me transform the document to the desired dictionary.
has comment: http://stackoverflow.com/comment/83110769
type: AnsweredQuestion
tagged with: python
tagged with: dictionary
favorite count: 0
type: Question
upvote count: 2
has title: How to transform text document to dictionary of keys and values?
answer count: 2
has answer: http://stackoverflow.com/a/48068576

http://stackoverflow.com/comment/83108658
type: QuestionComment
has text: Your algorithm has a "big-O notation" of O(n^2) which means bigger input will be exponentially slower. If this is a beginning programming course, that's probably the point they're trying to teach you. Look for a different approach to the problem that doesn't involve doubly nested for loops.
comment on: http://stackoverflow.com/q/48066606
score: 0
type: Comment

http://stackoverflow.com/comment/83166648
comment on: http://stackoverflow.com/q/48095890
type: Comment
type: QuestionComment
score: 1
has text: `long` (`Int64`) is a primitive; I would *expect* python to map that to its own closest primitive... ?

http://stackoverflow.com/comment/83284145
has text: prefetch related does it, 6 queries in 29ms in stead of 100 in 150ms now :)
comment on: http://stackoverflow.com/a/48151448
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48095999
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/83167091
upvote count: 2
answers question: http://stackoverflow.com/q/48095643
downvote count: 0
has comment: http://stackoverflow.com/comment/83167073
has comment: http://stackoverflow.com/comment/83167898
has body: Maybe your code has incorrect indentation: for name in A: if name in B: match=name a_index = A.index(match) c_element = C[a_index] b_index = B.index(match) e_element = E[b_index] f_element = F[b_index] if c_element == e_element: print([match, c_element, f_element])

http://stackoverflow.com/comment/83080691
comment on: http://stackoverflow.com/a/48053564
has text: I've updated the answer based on the new information. Please let me know if this works now.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48019249
upvote count: 1
tagged with: python
tagged with: anaconda
score: 1
linked to: http://stackoverflow.com/q/45487013
type: Question
has comment: http://stackoverflow.com/comment/83008599
tagged with: smtplib
tagged with: encoding
has title: 'utf-8' codec can't decode byte 0xf4 in position 1: invalid continuation byte
has comment: http://stackoverflow.com/comment/83007576
has body: I try to send email thanks to a python script and it's not working. I tried different mail adresses (Hotmail and Gmail), different ports, etc. none is working and I always have the same adress even if I just write two lines of code. I also try Latin-1 or utf-8 encoding...nothing change! I am working with anaconda and python 3.6 on windows10. Code : import smtplib serveur = smtplib.SMTP('smtp.gmail.com',587) And the error : runfile('C:/Users/Come/AppData/Roaming/Microsoft/Windows/Network Shortcuts/sanstitre3.py', wdir='C:/Users/Come/AppData/Roaming/Microsoft/Windows/Network Shortcuts') Traceback (most recent call last): File "&lt;ipython-input-1-a733f02e7871&gt;", line 1, in &lt;module&gt; runfile('C:/Users/Come/AppData/Roaming/Microsoft/Windows/Network Shortcuts/sanstitre3.py', wdir='C:/Users/Come/AppData/Roaming/Microsoft/Windows/Network Shortcuts') File "D:\Anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "D:\Anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Come/AppData/Roaming/Microsoft/Windows/Network Shortcuts/sanstitre3.py", line 9, in &lt;module&gt; serveur = smtplib.SMTP('smtp.gmail.com',587) File "D:\Anaconda\lib\smtplib.py", line 261, in __init__ fqdn = socket.getfqdn() File "D:\Anaconda\lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf4 in position 1: invalid continuation byte EDIT : So far I tried differnt things but Nothing worked : no my code begin like : # -*- coding:Latin-1 -*- import smtplib import socket hostname, aliases, ipaddrs = socket.gethostbyaddr('smtp.gmail.com') socket.getfqdn() socket.gethostname() serveur = smtplib.SMTP("smtp.gmail.com",587) serveur.ehlo() I also ping smtp.gmail.com, here is the result, all seem in order... but it's still not working (I also checked if any s…
has answer: http://stackoverflow.com/a/48025826
has answer: http://stackoverflow.com/a/48019266
has comment: http://stackoverflow.com/comment/83016024
answer count: 3
downvote count: 0
tagged with: windows-10
favorite count: 0
has answer: http://stackoverflow.com/a/48019664
linked to: http://stackoverflow.com/q/41880854
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83007728

http://stackoverflow.com/a/49830846
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48152382
answers question: http://stackoverflow.com/q/48152382
type: Answer
has body: Late solution: It was a bug in VSC causing it to incorrectly read the PYTHONPATH variable. The workaround was to create an empty .env at the root of the workspace save folder. I think this workaround may be obsolete now.
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/83263411
has text: This would surprise you, but most users aren't as receptive to downvotes or feedback as you would think. Providing feedback links you to downvotes and would just encourage revenge voting.
type: Comment
comment on: http://stackoverflow.com/a/48142564
type: AnswerComment
score: 3

http://stackoverflow.com/a/48095928
answers question: http://stackoverflow.com/q/48093754
score: 0
type: Answer
has body: The problem is that you are calling instance methods as class methods. For example, you cannot call A.myfunction1('3') However you can call, inst = A() inst.myfunction1('3') When this is translated into the getattr syntax, your code becomes method_to_call = getattr(Pal1, func[0])

http://stackoverflow.com/a/48093195
score: 1
type: Answer
has body: You can use: #convert column to datetime and create index df = df.set_index(pd.to_datetime(df['date_time'])) #shift by 1 day and reindex for same indices, subtract from right by rsub df['change24h'] = df['value'].shift(freq='1D').reindex(df.index).rsub(df['value']) #same as #df['change24h'] = df['value'].sub(df['value'].shift(freq='1D').reindex(df.index)) #remove datetime index df = df.reset_index(drop=True) print (df) date_time value change24h 0 1/10/2016 0:00:00 28.4 NaN 1 1/10/2016 0:05:00 28.4 NaN 2 1/10/2016 0:10:00 28.4 NaN 3 1/11/2016 0:00:00 27.4 -1.0 4 1/11/2016 0:05:00 29.4 1.0 5 1/11/2016 0:10:00 28.4 0.0
upvote count: 1
has comment: http://stackoverflow.com/comment/83162993
downvote count: 0
answers question: http://stackoverflow.com/q/48093083

http://stackoverflow.com/a/48139708
has comment: http://stackoverflow.com/comment/83257390
type: Answer
accepted answer of: http://stackoverflow.com/q/48139676
has body: Try the following code: span_element = driver.find_element_by_css_selector(".ocenaCzastkowa.masterTooltip") span_element.text # This will return "5". PS: You can also use span_element.get_attribute("value").
answers question: http://stackoverflow.com/q/48139676
upvote count: 36
has comment: http://stackoverflow.com/comment/83257200
has comment: http://stackoverflow.com/comment/83257164
has comment: http://stackoverflow.com/comment/83257229
downvote count: 0
score: 36
has comment: http://stackoverflow.com/comment/83257267
has comment: http://stackoverflow.com/comment/96320826
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/96320256
has comment: http://stackoverflow.com/comment/83257487

http://stackoverflow.com/comment/83322505
has text: So what you are looking for is a [centroid of a polygon](https://en.wikipedia.org/wiki/Centroid#Centroid_of_a_polygon)? Even if it means in the case of a C like shape that it lies outside the polygon?
score: 0
comment on: http://stackoverflow.com/q/48168880
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83052519
has text: @JonClements yeah, my first one wasn't really good. It was more of a coder script than a programmer script which is one of the reasons I made a v2.
comment on: http://stackoverflow.com/q/48040985
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83229986
has text: Because pickle is more bloated, and because sometimes the output stream has to follow a specific protocol.
comment on: http://stackoverflow.com/q/48126663
type: Comment
type: QuestionComment
score: 4

http://stackoverflow.com/a/63976047
answers question: http://stackoverflow.com/q/48163641
downvote count: 0
type: Answer
score: 3
has body: Just import inside ready() method: def ready(self): print('Sent From ready') from django.db.models.signals import post_save from yourapp.api.signals import post_save_user_receiver post_save.connect(post_save_user_receiver, sender=settings.AUTH_USER_MODEL)
upvote count: 3

http://stackoverflow.com/comment/83065966
type: Comment
has text: @CraigHamilton I think that's distinct enough for a new question.
comment on: http://stackoverflow.com/a/48039734
score: 0
type: AnswerComment

http://stackoverflow.com/q/48141036
has comment: http://stackoverflow.com/comment/138891634
score: 3
answer count: 0
downvote count: 0
favorite count: 0
has title: Python Coverage Warning - Module 'module_name' was not imported by the covered tests
type: Question
has body: I am getting an error promoting [WARN] Module 'module_name' was not imported by the covered tests in pybuild python coverage plugin. I can't see my scripts in coverage report and build got success with high coverage rate showing 100% coverage in __init__.py scripts. I have written some unit tests to some of my modules and executed in pyunit. But the coverage report does not contain that information. When I disable unittesting report is generated for all the scripts. what is the problem with this.
tagged with: python
tagged with: pybuilder
has comment: http://stackoverflow.com/comment/86545789
upvote count: 3
tagged with: coverage.py
type: UnansweredQuestion

http://stackoverflow.com/a/48060047
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48058861
answers question: http://stackoverflow.com/q/48058861
upvote count: 2
has comment: http://stackoverflow.com/comment/83093683
type: AcceptedAnswer
has body: If I understand your question properly, you would like to, for each example in a batch, do the multiplication of 29 matrices of shape (29, 64) in y[batchnr], element-wise, then with x, also element-wise. If that is correct, then I think you can use tf.reduce_prod(). For example, # x = shape(batchsize, 29, 64), # y = shape(batchsize, 29, 29, 64) # ... z = tf.reduce_prod(y, axis=1) # shape(batchsize, 29, 64), product of 29 matrices element-wise r = tf.multiply(x, z) # shape(batchsize, 29, 64)
type: Answer

http://stackoverflow.com/q/48140989
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48141688
accepted answer: http://stackoverflow.com/a/48141688
has comment: http://stackoverflow.com/comment/83260305
has comment: http://stackoverflow.com/comment/83260219
tagged with: tensorflow
type: Question
has body: I was trying to train a LSTM model using keras but I think I got something wrong here. I got an error of ValueError: Error when checking input: expected lstm_17_input to have 3 dimensions, but got array with shape (10000, 0, 20) while my code looks like model = Sequential() model.add(LSTM(256, activation="relu", dropout=0.25, recurrent_dropout=0.25, input_shape=(None, 20, 64))) model.add(Dense(1, activation="sigmoid")) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=batch_size, epochs=10) where X_train has a shape of (10000, 20) and the first few data points are like array([[ 0, 0, 0, ..., 40, 40, 9], [ 0, 0, 0, ..., 33, 20, 51], [ 0, 0, 0, ..., 54, 54, 50], ... and y_train has a shape of (10000, ), which is a binary (0/1) label array. Could someone point out where I was wrong here?
score: 20
upvote count: 20
downvote count: 0
has comment: http://stackoverflow.com/comment/83260162
has title: Keras LSTM input dimension setting
tagged with: keras
tagged with: lstm
tagged with: deep-learning
answer count: 1
has comment: http://stackoverflow.com/comment/83260380
favorite count: 0

http://stackoverflow.com/comment/83151756
comment on: http://stackoverflow.com/q/48088558
type: QuestionComment
type: Comment
has text: What you want can be achieved by `s.split()`. Can you describe a more complex example or how you want to split by regex?
score: 0

http://stackoverflow.com/comment/83006856
score: 1
type: AnswerComment
type: Comment
has text: this is wrong answer, you are not answering OP, you are just breaking the loop! if you want not to be downvoted correct your answer
comment on: http://stackoverflow.com/a/48018958

http://stackoverflow.com/comment/83184353
score: 0
type: Comment
type: QuestionComment
has text: Both the `fun_cpp` and `fun_python` give the same output when given the same arguments. The problem is that when I use `least_squares(fun_python, x0, args=(t_train, y_train)` I get the expected result (the orange line) but when I use `least_squares(fun_cpp, x0, args=(t_train, y_train)` it gives me the green line whereas I would expect it to give me the orange line (as both functions are similar).
comment on: http://stackoverflow.com/q/48102255

http://stackoverflow.com/comment/83420461
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48068306
has text: what did you mean by shebang?
score: 0

choregraphe
tags question: http://stackoverflow.com/q/48098359
tag name: choregraphe
type: Tag
tags question: http://stackoverflow.com/q/48151172

http://stackoverflow.com/q/48125161
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48125391
has title: Include keyword in url.py not working without app_name(Django 2.0)
tagged with: django
upvote count: 1
type: Question
score: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48125391
tagged with: python
has body: When I try to use the include keyword in url.py to reverse match url in model.py reverse("products:detail", kwargs={"slug": self.slug} it says: Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. I see that in Django 2.0, you have to provide app_name with namespace. As I have created my app with python manage.py startapp products, I thing my app name is products. My url.py: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from .views import hello_world, home_page, about_page, contact_page, login_page, register_page urlpatterns = [ url(r'^hello/$', hello_world), url(r'^$', home_page), url(r'^admin/', admin.site.urls), url(r'^about/$', about_page), url(r'^contact/$', contact_page), url(r'^login/$', login_page), url(r'^register/$', register_page), url(r'^products/', include(products, namespace='products')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` And my products/model.py: import random import os from django.db import models from django.db.models.signals import pre_save, post_save from django.urls import reverse from .utils import unique_slug_generator def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(filepath) return name, ext def upload_image_path(instance, filename): new_filename = random.randint(0, 3000) name, ext = get_filename_ext(filename) final_filename = f'{new_filename}{ext}'#.format(new_filename=new_filename, ext=ext) print(new_filename, final_filename, ext) return f"products/{new_filen…

http://stackoverflow.com/comment/83028253
score: 0
has text: Depending on the version of the IE driver you’re using, the capabilities you’re sending across the wire will not work for the driver for ignoring Protected Mode settings. What happens if you use the `selenium.webdriver.ie.Options` class instead of hand-crafting your capabilities?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48020561

http://stackoverflow.com/q/48023615
linked to: http://stackoverflow.com/q/43804993
answer count: 1
favorite count: 0
tagged with: pyzmq
tagged with: python-asyncio
tagged with: python
accepted answer: http://stackoverflow.com/a/48024088
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48024088
has body: The following code snippet has two coroutines each for server and client. The client coroutine has a logic to break the while loop after 10 seconds and server should stop after 15 seconds. When I run the script this doesn't stop, ideally, it should stop after 15 seconds but this is not happening. import asyncio import time import zmq import zmq.asyncio zmq.asyncio.install() ctx = zmq.asyncio.Context() server_socket = ctx.socket(zmq.REP) client_socket = ctx.socket(zmq.REQ) server_socket.bind("tcp://127.0.0.1:8899") client_socket.connect("tcp://127.0.0.1:8899") t0 = time.time() @asyncio.coroutine def server_coroutine(): while True: msg = yield from server_socket.recv_string() print(msg) msg = "Server:: {}".format(msg) yield from server_socket.send_string(msg) t1 = time.time() elapsed_time = t1 - t0 # print('elapsed time is {}'.format(elapsed_time)) if elapsed_time &gt; 15: print("Breaking Server loop") break @asyncio.coroutine def client_coroutine(): counter = 0 while True: yield from asyncio.sleep(2) msg = 'Message: {}'.format(counter) yield from client_socket.send_string(msg) res = yield from client_socket.recv_string() print(res) t1 = time.time() elapsed_time = t1 - t0 print('elapsed time is {}'.format(elapsed_time)) if elapsed_time &gt; 10: print("Breaking Client loop") break counter += 1 if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather( asyncio.ensure_future(server_coroutine()), asyncio.ensure_future(client_coroutine()) ))
tagged with: coroutine
type: Question
score: 0
has title: Why doesn't this async code stop?
upvote count: 1

http://stackoverflow.com/q/48159074
tagged with: sikuli-script
score: 0
has title: Facing barriers when running skl script from excel VBA
tagged with: vba
has comment: http://stackoverflow.com/comment/83339030
answer count: 0
type: UnansweredQuestion
has body: I am using below VB to launch script of sikuliX 1.1.2 from excel but it takes around 30 seconds to just execute the script and then script takes itself another seconds to fulfill the instruction. So is there any way to make this process very fast ? VB Code: Private Sub() Dim dblRetVal As String dblRetVal = Shell("java -jar E:\SikuliX1.1.2\sikulix.jar -r D:\ProjectKiosk\Scripts\test2.sikuli —a1 a2 a3", vbHide) End Sub() Sikuli Script: try: click("1514219960059.png") except: # Your action where there is some problem. doubleClick("1514219980851.png")
tagged with: python
has comment: http://stackoverflow.com/comment/83300305
tagged with: excel
has comment: http://stackoverflow.com/comment/83329322
type: Question
tagged with: jython

http://stackoverflow.com/comment/83247093
comment on: http://stackoverflow.com/a/48134056
type: AnswerComment
has text: I need the last character in the string for the loop to detect the direction of latitude or longitude. That is smart but it wouldn't help. The string is also 'nnn nn.nnn L'. It would error because of the space between the "nnn nn.nnn"
score: 0
type: Comment

http://stackoverflow.com/comment/83144770
comment on: http://stackoverflow.com/q/48082629
score: 0
type: QuestionComment
has text: Oh, so use 4 spaces then text with spaces for formatting? thanks
type: Comment

http://stackoverflow.com/comment/83225474
type: Comment
has text: You might want to look into the `Manager` object in the [multiprocessing](https://docs.python.org/2/library/multiprocessing.html#managers) module
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48124257

http://stackoverflow.com/comment/83043029
comment on: http://stackoverflow.com/q/48036069
type: QuestionComment
has text: That is not correct in PyQt, it usually happens many times due to efficiency issues. You can show a picture of what you get in addition to the connection to your database. Also you have not answered my question. What database do you use: sqlite, mysql, ...?
score: 0
type: Comment

scipy
tags question: http://stackoverflow.com/q/48070143
tags question: http://stackoverflow.com/q/48016569
tags question: http://stackoverflow.com/q/48038562
tags question: http://stackoverflow.com/q/48043004
tags question: http://stackoverflow.com/q/48048750
tags question: http://stackoverflow.com/q/48158746
tags question: http://stackoverflow.com/q/48153251
tags question: http://stackoverflow.com/q/48143177
tags question: http://stackoverflow.com/q/48014712
tags question: http://stackoverflow.com/q/48158042
tags question: http://stackoverflow.com/q/48062522
tags question: http://stackoverflow.com/q/48121916
type: Tag
tags question: http://stackoverflow.com/q/48159461
tags question: http://stackoverflow.com/q/48099026
tags question: http://stackoverflow.com/q/48144381
tags question: http://stackoverflow.com/q/48088890
tag name: scipy
tags question: http://stackoverflow.com/q/48080703
tags question: http://stackoverflow.com/q/48055971
tags question: http://stackoverflow.com/q/48077286
tags question: http://stackoverflow.com/q/48115464
tags question: http://stackoverflow.com/q/48043725
tags question: http://stackoverflow.com/q/48096655
tags question: http://stackoverflow.com/q/48100657
tags question: http://stackoverflow.com/q/48030494
tags question: http://stackoverflow.com/q/48166212
tags question: http://stackoverflow.com/q/48131064
tags question: http://stackoverflow.com/q/48054194
tags question: http://stackoverflow.com/q/48170804
tags question: http://stackoverflow.com/q/48118436
tags question: http://stackoverflow.com/q/48100810
tags question: http://stackoverflow.com/q/48133358
tags question: http://stackoverflow.com/q/48120143
tags question: http://stackoverflow.com/q/48102255
tags question: http://stackoverflow.com/q/48052426
tags question: http://stackoverflow.com/q/48099546
tags question: http://stackoverflow.com/q/48099075
tags question: http://stackoverflow.com/q/48088516
tags question: http://stackoverflow.com/q/48103754
tags question: http://stackoverflow.com/q/48170703
tags question: http://stackoverflow.com/q/48121389
tags question: http://stackoverflow.com/q/48101564
tags question: http://stackoverflow.com/q/48104401
tags question: http://stackoverflow.com/q/48116496
tags question: http://stackoverflow.com/q/48070610
tags question: http://stackoverflow.com/q/48118739
tags question: http://stackoverflow.com/q/48037418
tags question: http://stackoverflow.com/q/48017962
tags question: http://stackoverflow.com/q/48028766

http://stackoverflow.com/comment/83275319
type: Comment
has text: Well, if you agree with my "answer", show your code so we can understand your problem. :)
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48148531

http://stackoverflow.com/comment/83200642
type: QuestionComment
comment on: http://stackoverflow.com/q/48112468
score: 0
type: Comment
has text: Yes, there was typo, now it should working.

http://stackoverflow.com/comment/83284242
has text: hi, this is the tutorial i used: https://www.hackster.io/Salmanfarisvp/googlepi-google-assistant-on-raspberry-pi-9f3677 I did the newest version.
comment on: http://stackoverflow.com/q/48149903
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83130494
comment on: http://stackoverflow.com/q/48078324
has text: There are an infinite amount of distributions that fit that criterion. How would you pick one here?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48138122
score: 1
has comment: http://stackoverflow.com/comment/83253764
downvote count: 0
has body: About subprocess.call, the documentation says: Run the command described by args. Wait for command to complete, then return the returncode attribute. All you need to do is to modify your run_hook function and return the exit code: def run_hook(cmd): # ... return subprocess.call(cmd, shell=True) This will simply your test code. def test_run_hook_systemexit_not_0(): python_exec = sys.executable args = [python_exec, "-c", "'exit(1)'"] assert run_hook(args) == 1 My advice: use subprocess.run instead Edit If you want to check the exit code of subprocess.call you need to patch it with your own version, like this: import subprocess _original_call = subprocess.call def assert_call(*args, **kwargs): assert _original_call(*args, **kwargs) == 0 Then, you use assert_call as a side effect function for your patch: from unittest.mock import patch @patch('subprocess.call', side_effect=assert_call) def test(call): python_exec = sys.executable args = [python_exec, "-c", "'exit(1)'"] run_hook(args)
type: Answer
has comment: http://stackoverflow.com/comment/83253546
answers question: http://stackoverflow.com/q/48137522
has comment: http://stackoverflow.com/comment/83253614
upvote count: 1

http://stackoverflow.com/q/48164539
downvote count: 1
has comment: http://stackoverflow.com/comment/83308327
answer count: 1
has comment: http://stackoverflow.com/comment/83308693
tagged with: variables
tagged with: parsing
tagged with: operators
favorite count: 0
has comment: http://stackoverflow.com/comment/83309423
has answer: http://stackoverflow.com/a/48165545
type: UnansweredQuestion
tagged with: python
has body: in the following code, i have a variable "split_data[i]", i am comparing each element of this variable to a file in "text variable: i = 0 while i < len(split_data): print(split_data[i]) if split_data[i] in text: #string in present in the text file print("Matched" ) else: print("not matched" ) i += 1 the value of split_data[4] is '03:31' which is present in the text but still the output is "not matched" whereas if my code is like this: i = 0 while i < len(split_data): print(split_data[i]) if '03:31' in text: #string in present in the text file print("Matched" ) else: print("not matched" ) i += 1 the output is matched. or else we can say: if '03:31' in split_data[4]: print("true") else: print('false') is true but if '03:31' == split_data[4]: print("true") else: print('false') is false this is my whole code : import mysql.connector import numpy as np conn=mysql.connector.connect(user="root", password="", host="localhost", database="videojs") # prepare a cursor object using cursor() method def read_from_db(): cursor = conn.cursor() cursor.execute("select time_arr from info where id ='53'") data=cursor.fetchone() print(data) the_new_list = [x.split(',') for x in data] print(the_new_list) str_data = ''.join(map(str, the_new_list)) print(len(str_data)) split_data=str_data.strip('[]').split(',') print(split_data) print(len(split_data)) i = 0 while i please guide me how to resolve this i am a beginner this is the data in text: 1 00:00 --> 00:06 welcome to your very first tutorial on 2 00:02 --> 00:08 beginning HTML HTML is the bedrock of 3 00:06 --> 00:10 the world wide web and if you're going 4 00:08 --> 03:31 to do anything even in other languages
tagged with: analysis
type: Question
has title: value of variable is not equal to value in this code
score: 0
upvote count: 1

http://stackoverflow.com/a/48102441
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48102372
has body: Your ip_split function returns a 6-tuple. If you use the [3:] slice operator, you will obtain everything from index 3 and further, so that will be a 3-tuple. But your formatting string '%s/%s' has only two %ss, so Python gets confused. You can (probably) fix it with slicing from index four, so [4:]. A second problem is that % takes precedence over indexing, so it sees the expression as ('%s/%s' % ip_split('10.10.128.1/18'))[3:], whereas I think you want to first get the last two items of the tuple. The fact that you uses spaces here does not makes a difference (yes, for scoping, Python takes spaces into account, but not for operator precedence). Alternatively, you can use [-2:], which is closer to "the last two items". So: n_sub = "%s/%s" % (ip_split('10.10.128.1/18')[-2:])
answers question: http://stackoverflow.com/q/48102372

http://stackoverflow.com/a/48020684
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83011540
has body: To open InternetExplorer you need to implement the following Configurations : On IE 7 or higher on Windows Vista or Windows 7, you must set the Protected Mode settings for each zone to be the same value. The value can be on or off, as long as it is the same for every zone. To set the Protected Mode settings, choose "Internet Options..." from the Tools menu, and click on the Security tab. For each zone, there will be a check box at the bottom of the tab labeled "Enable Protected Mode". Additionally, Enhanced Protected Mode must be disabled for IE 10 and higher. This option is found in the Advanced tab of the Internet Options dialog. The browser zoom level must be set to 100% so that the native mouse events can be set to the correct coordinates. For Windows 10, you also need to set Change the size of text, apps, and other items to 100% in display settings. For IE 11 only, you will need to set a registry entry on the target computer so that the driver can maintain a connection to the instance of Internet Explorer it creates. For 32-bit Windows installations, the key you must examine in the registry editor is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE. For 64-bit Windows installations, the key is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE. Please note that the FEATURE_BFCACHE subkey may or may not be present, and should be created if it is not present. Important: Inside this key, create a DWORD value named iexplore.exe with the value of 0. Now, you have to setup the IEDriverServer binary with the following settings through DesiredCapabilities : from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities cap = DesiredCapabilities().INTERNETEXPLORER cap['ignoreProtectedModeSettings'] = True cap['IntroduceInstabilityByIgnoringProtectedModeSettings'] = True cap['nativeEvents'] = True cap['ignoreZoomSetting'] = True c…
downvote count: 0
answers question: http://stackoverflow.com/q/48020561
has comment: http://stackoverflow.com/comment/83011783
type: Answer

http://stackoverflow.com/comment/83100689
has text: What if the data is arbitrary nested?
comment on: http://stackoverflow.com/q/48063772
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/83044585
type: QuestionComment
has text: Instead of working with dictionaries, if you do data science, pandas is usually a good package. It combines numpy and database-like processing of data.
comment on: http://stackoverflow.com/q/48037224
score: 0
type: Comment

http://stackoverflow.com/q/48055255
has comment: http://stackoverflow.com/comment/83082912
downvote count: 0
answer count: 1
tagged with: url
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83082856
has title: About Django pk in urlpattern
type: UnansweredQuestion
has body: I am new to Django, and I am reading one app on github: https://github.com/rogargon/myrecommendations/blob/web2-html/myrestaurants/urls.py#L18 There is one urlpattern like url(r'^restaurants/(?P<pk>\d+)/$', RestaurantDetail.as_view(), name='restaurant_detail') It revoke RestaurantDetail view, here: https://github.com/rogargon/myrecommendations/blob/master/myrestaurants/views.py#L36 class RestaurantDetail(DetailView): model = Restaurant template_name = 'myrestaurants/restaurant_detail.html' def get_context_data(self, **kwargs): context = super(RestaurantDetail, self).get_context_data(**kwargs) context['RATING_CHOICES'] = RestaurantReview.RATING_CHOICES return context Here I know pk is set to one number indicating the id of restaurant, but in the html model, https://github.com/rogargon/myrecommendations/blob/master/myrestaurants/templates/myrestaurants/restaurant_detail.html, I didn't see any where using pk, but the page shows only the one restaurant. Could you how does pk work in this process? How the template know which restaurant I want to show? And why there is no return in this view? {% extends "myrestaurants/base.html" %} {% block title %}MyRestaurants - {{ restaurant.name }}{% endblock %} {% block content %} {{ restaurant.name }} {% if user == restaurant.user %} (edit) {% endif %} Address: {{ restaurant.street }}, {{ restaurant.number }} {{ restaurant.zipcode }} {{ restaurant.city }} {{ restaurant.stateOrProvince }} ({{ restaurant.country }}) Dishes {% if user.is_authenticated %} (add) {% endif %} {% for dish in restaurant.dishes.all %} {{ dish.name }} {% empty %} Sorry, no dishes for this restaurant yet. {% endfor %} Reviews {% if restaurant.restaurantreview_set.all|length > 0 %} Average rating {% with restaurant.restaurantreview_set.all|length as reviewCount %} from {{ reviewCount }} review {% endwith %} {% for review in restaurant.restaurantreview_set.all %} {{ review.rating }} star…
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/48055508
type: Question
has comment: http://stackoverflow.com/comment/83082884
score: 1

http://stackoverflow.com/a/48134418
type: Answer
has body: That's because cells with negative values have a num class, not nump. You can handle both: //td[@class="nump" or @class="num"]/text() Or: //td[starts-with(@class, "num")]/text() And, to avoid having extra newlines in the output, use .text_content(): [cell.text_content().strip() for cell in tree.xpath('//td[@class="nump" or @class="num"]')]
accepted answer of: http://stackoverflow.com/q/48134390
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48134390
score: 0

http://stackoverflow.com/q/48148563
tagged with: python
has comment: http://stackoverflow.com/comment/83283434
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/83276077
has body: I need to get the logins of the active users (max 30) and the number of their commits in a given period of time in a particular branch of the repository using github API v3 (https://developer.github.com/v3/) and the standard python libraries. I studied general api documentation, and https://developer.github.com/v3/repos/ and https://developer.github.com/v3/search/ articles in particular, but I couldn't find how to do that. It's possible to find commits through GET /search/commits (by specifying the repository via the repo parameter: https://api.github.com/search/commits?q=repo:octocat/Spoon-Knife), but there will be neither time period nor the repository branch specified. As a result, I was able to get the logins and contributions, but only for the whole time: https://api.github.com/repos/octocat/Spoon-Knife/contributors Also, in order to make search commits work, it's neccesary to provide a custom media type in the Accept header: application/vnd.github.cloak-preview I've reworked an example from the documentation of how the urlib library works, but it returns HTTP error 422: import urllib.request API_URL = "https://api.github.com/" q = urllib.request.Request('API_URL' + "search/commits?q=repo:octocat/Spoon-Knife") https://api.github.com/search/commits?q=repo:fastlane/fastlane q.add_header('application/vnd.github.cloak-preview', 'Accept') print(q) a = urllib.request.urlopen(q) a = a.read() print(a)
has comment: http://stackoverflow.com/comment/83275434
score: 0
tagged with: github-api
has title: How can I get the list of the active users and their commits in the repository in the given time period via github API?
tagged with: github
type: UnansweredQuestion

http://stackoverflow.com/a/48028481
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48028248
upvote count: 1
answers question: http://stackoverflow.com/q/48028248
has body: I solved the issue by installing django using pip3. But since I didn't have pip3 package installed on my OS, first I had to install it using: sudo apt-get update sudo apt-get -y install python3-pip Then I successfully installed Django 2.0 using: pip3 install Django --upgrade

http://stackoverflow.com/comment/83030585
score: 0
comment on: http://stackoverflow.com/q/48030198
type: Comment
type: QuestionComment
has text: Yes, it does...

http://stackoverflow.com/comment/83388965
comment on: http://stackoverflow.com/a/48178830
type: AnswerComment
score: 1
type: Comment
has text: @vib: You'd do well to store the complete pattern in a variable (the value of which you can inspect for debugging) rather than passing directly to `re.match()`. If you encounter problems, you can then copy/paste the complete pattern into something like https://regex101.com/ to visualise exactly what's going on.

http://stackoverflow.com/a/48033397
has body: Let's say possible, Odoo official development done with ubuntu operating system. For odoo 11.0 Most suggest subline or gedit with plugins most great tool for development. Visula studio in ubuntu https://www.youtube.com/watch?v=aY4Rhmv5P_Q We had build lot odoo code since 2011 till date on gedit with ubuntu. Also atom https://atom.io/ is good tool for edting contents. My special concern with gedit, it take very less memory and give speed. In case you had large RAM, yes. this visual studio works great.
type: Answer
upvote count: 0
score: -2
answers question: http://stackoverflow.com/q/48033323
downvote count: 2

http://stackoverflow.com/q/48105203
has answer: http://stackoverflow.com/a/48105262
answer count: 1
has title: gaierror-2,Name or service name not known) when using requests.post in python
has comment: http://stackoverflow.com/comment/83186183
tagged with: linux
downvote count: 0
has comment: http://stackoverflow.com/comment/83187213
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83186213
tagged with: python
tagged with: python-requests
score: 2
has comment: http://stackoverflow.com/comment/83187059
has body: I am trying to send web request to my php code via linux running on raspberry pi. I am using putty to access the OS. When I am running the code, I am getting gai error-2. Below is my code: import requests values = {'"firstname":' "abc ", '"lastname":' "xyz"} r = requests.post('http://rts.msmq.site/security.php', data=values) I am unable to figure out the problem. Can someone let me know what could be the issue? I am using linux. Error message: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/dist-packages/requests/api.py", line 94, in post return request('post', url, data=data, json=json, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/api.py", line 49, in request return session.request(method=method, url=url, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 457, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 569, in send r = adapter.send(request, **kwargs) File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 407, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', gaierror(-2, 'Name or service not known'))
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/83187137

http://stackoverflow.com/q/48116282
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
has title: List issue with verifying index
score: 1
has answer: http://stackoverflow.com/a/48116761
type: Question
upvote count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48116735
has answer: http://stackoverflow.com/a/48116437
has answer: http://stackoverflow.com/a/48116540
has answer: http://stackoverflow.com/a/48116628
answer count: 5
has body: Need to make a program that will receive 20 numbers (1 to 10) from the user and put them in a list. Afterwards the user types in a number; it should print how many times the number the user typed appears and the index of such numbers. I have tried but can't find a solution. x = [] for i in range(0, 21): x.append(int(input("Introduza numeros: "))) y = int(input("Escreva um numero: ")) r = x.index(y) if r == True: print(r) else: print("Não ha esse numero")

http://stackoverflow.com/comment/83004442
type: QuestionComment
has text: can you post the full stacktrace?? as with just 2 lines its not clear what the error is, so please post the full trace
score: 0
comment on: http://stackoverflow.com/q/48017570
type: Comment

http://stackoverflow.com/q/48152379
accepted answer: http://stackoverflow.com/a/48156282
has title: Django IntegrityError while updating a record
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I have a model with double columns as primary key. I do a filter on it and get the records I want, change a field and save it. As I know save will update the record and does not create a new instance of the model in db. so It should be all okay but I'm stuck with an integrityError Duplicate entry '10-2' for key 'PRIMARY' when I try to save the record Here is the code snippet: analysis = AnalysisResult.objects.filter(request=req.request_id) for anal in analysis: anal.analysisresult_path = some_string anal.save() #this line is where the error occurs And here is my model: class AnalysisResult(models.Model): analysisresult_path = models.CharField(db_column='analysisResult_path', max_length=255, blank=True, null=True) # Field name made lowercase. detectionresult_path = models.CharField(db_column='detectionResult_path', max_length=255, blank=True, null=True) # Field name made lowercase. targetcode = models.ForeignKey('TagetCode', models.DO_NOTHING, db_column='targetCode_id') # Field name made lowercase. request = models.ForeignKey('Request', models.DO_NOTHING, primary_key=True) class Meta: managed = False db_table = 'analysis_result' unique_together = (('request', 'targetcode'),)
tagged with: python
linked to: http://stackoverflow.com/q/16800375
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48156282
upvote count: 2
has comment: http://stackoverflow.com/comment/83287277
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/83285398
tagged with: django-models

http://stackoverflow.com/a/48148210
type: AcceptedAnswer
downvote count: 1
type: Answer
has body: There are several solutions to this using regular expressions. My favorite is this: re.sub('(..)', r'\x\1', 'f70307d600017010') Another could be: ''.join(r'\x' + x for x in re.findall('..', 'f70307d600017010')) These will create a string of escaped bytes (based on the assumption that the tag "escaping" was meaning this). If you instead want to create a string of unescaped bytes: re.sub('(..)', lambda m: chr(int(m.group(), 16)), 'f70307d600017010') EDIT: I now prefer the answer of @juanpa-arrivillaga using the binascii module: binascii.unhexlify('f70307d600017010')
has comment: http://stackoverflow.com/comment/83274957
accepted answer of: http://stackoverflow.com/q/48147975
score: 0
answers question: http://stackoverflow.com/q/48147975
upvote count: 1

http://stackoverflow.com/q/48052478
has answer: http://stackoverflow.com/a/48052529
type: Question
has comment: http://stackoverflow.com/comment/83077057
score: 2
downvote count: 0
has body: I just got a book on kids coding in Python for Christmas. I was really excited to use it and downloaded the app immediately. The book said to use this code to import Turtle: &gt;&gt;&gt; import turtle Then it said this to create a canvas: &gt;&gt;&gt; t = turtle.Pen () This error message appeared. Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 1, in &lt;module&gt; t = turtle.Pen () AttributeError: module 'turtle' has no attribute 'Pen' What does this mean? How do I get Turtle's canvas up?
accepted answer: http://stackoverflow.com/a/48052495
answer count: 3
has comment: http://stackoverflow.com/comment/83081112
has comment: http://stackoverflow.com/comment/83099913
favorite count: 0
tagged with: turtle-graphics
has comment: http://stackoverflow.com/comment/83077164
upvote count: 2
has answer: http://stackoverflow.com/a/48054378
tagged with: python
has comment: http://stackoverflow.com/comment/83077405
type: AnsweredQuestion
has title: Python Having Problems Getting Turtle's Canvas Up
has answer: http://stackoverflow.com/a/48052495
possible better answer: http://stackoverflow.com/a/48052529

http://stackoverflow.com/a/48022892
has comment: http://stackoverflow.com/comment/83015033
has comment: http://stackoverflow.com/comment/83015274
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/83015153
has body: Have you visualized the data? The given values for x_axis and y_axis look like this: If you use the given x_axis values and your Excel solver values for mu=0.1536 and sigma=3.1915 and then visualize the pdf you get this: So I wonder what result you want to get? Actually the data in the first picture does not really look like a Log-normal pdf, does it?
has comment: http://stackoverflow.com/comment/83015194
has comment: http://stackoverflow.com/comment/83015236
upvote count: 2
answers question: http://stackoverflow.com/q/48022520
has comment: http://stackoverflow.com/comment/83015104
type: Answer

http://stackoverflow.com/a/48024660
has body: Ok, solved : Avast email agent needs to be disconnected.
type: Answer
has comment: http://stackoverflow.com/comment/92429582
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/48024441

http://stackoverflow.com/comment/83138282
type: AnswerComment
comment on: http://stackoverflow.com/a/48071485
has text: @dharmendramishra Add this info in the question. Comment section ain't pretty.
score: 0
type: Comment

http://stackoverflow.com/comment/83187359
type: Comment
has text: Thks for the answer. What I don't get is that with these solution, random numbers are drawn in every frame. I would like the random numbers to be drawn only once at the beginning, and then to select a different size of sample from the same random numbers originally drawn.
type: AnswerComment
comment on: http://stackoverflow.com/a/48104963
score: 0

http://stackoverflow.com/a/49277025
score: 1
answers question: http://stackoverflow.com/q/48123418
accepted answer of: http://stackoverflow.com/q/48123418
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85557259
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88933221
has comment: http://stackoverflow.com/comment/88884081
has body: Had the same problem: import xmltodict with open('LEIStuff.xml',encoding="utf8") as datafile: doc = xmltodict.parse(datafile.read()) for row in doc['LEIData']['LEIRecords']['LEIRecord']: try: #Lei Number print(row['LEI'],'-----------------------------') except Exception: pass try: #LegalNumber print(row['Entity']['LegalName']['#text']) print('===[LegalName]===') except Exception: pass [...] and all the fields you would like to use: from this website https://www.gleif.org/en/about-lei/common-data-file-format/lei-cdf-format/lei-cdf-format-version-2-1 EDIT: AttributeError: no such child - the LEI XML data it is not always the same - the structure of each record is s bit different - sometimes it as and extra field or missing field - I have sorted it out using "TRY:" in python but it has to be done per field not per row (I think). EDIT ver2: When you are trying to get the data from the concatenated LEI file the structure is different than in the small fies.. you have then to use: for row in doc['lei:LEIData']['lei:LEIRecords']['lei:LEIRecord']: but when you trying to access the fields with #text then: LegalName = row['lei:Entity']['lei:LegalName']['#text'] rest of the fields will be like that: Legal_PostalCode = row['lei:Entity']['lei:LegalAddress']['lei:PostalCode'] hope that's help.
downvote count: 0

http://stackoverflow.com/q/48142780
has comment: http://stackoverflow.com/comment/83264022
tagged with: python
favorite count: 0
tagged with: python-3.x
has body: I was looking for a command that I could use to delete a specific element in an array. So I decided to use the built-in help() function. help([1,2,3,4,5,6,7,8,9]) The result of this was that I was able to find the remove() function but nowhere did it mention the del keyword, which turned out to be useful. Are there any similar functions like help() that would also output keywords like del?
has title: Why doesn't the built-in python help function display all the possible commands?
accepted answer: http://stackoverflow.com/a/48143284
upvote count: 2
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/83263750
has comment: http://stackoverflow.com/comment/83263744
tagged with: list
has answer: http://stackoverflow.com/a/48143284
tagged with: arrays
score: 1
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/83055203
has text: @Elmex80s I appreciate for your help, I want the same response
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48042187

http://stackoverflow.com/comment/83005006
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48017614
has text: `s = e.get()` assigns the entries current value to `s`. Which is initially nothing.
score: 0

http://stackoverflow.com/a/48085592
score: 1
accepted answer of: http://stackoverflow.com/q/48085512
upvote count: 1
answers question: http://stackoverflow.com/q/48085512
type: AcceptedAnswer
type: Answer
has body: You could define your own function and use .pop to remove the second element: def merge(myList, a, b): myList[a] = myList[a] + myList.pop(b) return myList &gt;&gt;&gt; merge(['h', 'e', "'", 'l', 'l', 'o'], 1, 2) ['h', "e'", 'l', 'l', 'o']
downvote count: 0

docker
tags question: http://stackoverflow.com/q/48091774
tags question: http://stackoverflow.com/q/48066217
tags question: http://stackoverflow.com/q/48023131
type: Tag
tags question: http://stackoverflow.com/q/48132279
tags question: http://stackoverflow.com/q/48048623
tags question: http://stackoverflow.com/q/48036153
tags question: http://stackoverflow.com/q/48076616
tags question: http://stackoverflow.com/q/48019769
tag name: docker
tags question: http://stackoverflow.com/q/48068691
tags question: http://stackoverflow.com/q/48139939
tags question: http://stackoverflow.com/q/48084417
tags question: http://stackoverflow.com/q/48096294
tags question: http://stackoverflow.com/q/48069045
tags question: http://stackoverflow.com/q/48121048

http://stackoverflow.com/a/48145157
has body: Ok, i figured out a fix. Not sure exactly why it works, but when I pass it to a pd.Series it works...--- both return a datetime64[ns, UTC] type, and although they look similiar they behave differently...still strange: fix: df['local_time']=pd.to_datetime(pd.Series(df.ts),utc=True)
type: Answer
answers question: http://stackoverflow.com/q/48143307
score: 0

http://stackoverflow.com/comment/83246499
type: QuestionComment
comment on: http://stackoverflow.com/q/48134612
has text: Also you'd potentially hit an `IndexError` since you call `list.remove()` while iterating over it.
score: 2
type: Comment

http://stackoverflow.com/q/48133488
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/35623057
type: Question
tagged with: apache-kafka
has body: I've been looking for a while but I can't find a way to create a batch consumer with kafka-python. I found a guide for Java but it isn't exactly what I am trying to achieve. Indeed, my goal is just to consume a fixed number of records let's say and process them (perform some transformations) and after that, store them into a Database.
has comment: http://stackoverflow.com/comment/84857084
tagged with: kafka-consumer-api
has title: How can I make a batch consumer with kafka-python?
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48133853
favorite count: 0

http://stackoverflow.com/q/48135848
has title: Getting Error while writing a Large datarame of 60K rows into csv in Pandas
score: 1
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48135997
type: Question
answer count: 1
downvote count: 0
tagged with: scikit-learn
has body: I am trying to build an prediction model. I am trying to do that in 2 parts Preprocesing of the data in python file(.ipynb) and saving this preprocesed data into a csv file Calling this preprocessed file in the Step 1 Model Prediction (.ipynb) file. Preprocessing File #saving preproccesed dataframe to csv train.to_csv('C:/Users/Documents/Tesfile_Preprocessed.csv') Error ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\sparse\array.py in __getitem__(self, key) 417 return self._get_val_at(key) 418 elif isinstance(key, tuple): --&gt; 419 data_slice = self.values[key] 420 else: 421 if isinstance(key, SparseArray): IndexError: too many indices for array Prediction Model File X_test=pd.read_csv('C:/Users/Documents/Tesfile_Preprocessed.csv') predicted_dtree = fit_decision.predict(X_test) How can I Solve This isue
tagged with: pandas
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48135997
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/a/68635573
answers question: http://stackoverflow.com/q/48135624
upvote count: 8
type: Answer
score: 8
has body: VS Code's terminal using a different python interpreter than the one you've selected By default, it doesn't know about your interpreter, and will initialize using the default .bashrc or equivalent in the OS. I found two relevant settings from an issue in Feb 2021. Checking the second option Python > Terminal: Activate Environment enables automatic activation of virtual environment: In settings.json it is called "python.terminal.activateEnvironment": true. Update (8 Aug 2021): Today when I opened the terminal from VS Code on Windows, it automatically inserted a line of code & C:/Users/[UserName]/[venv]/Scripts/Activate.ps1 to activate the appropriate environment associated with the selected python interpreter! It appears the aforementioned settings is now the default behavior. While there are changes to Terminal behavior in the release notes of July 2021 (version 1.59), I don't see virtual environment activation being explicitly mentioned. The new behavior is documented here, in "Environments and Terminal windows". "python.pythonPath" has been deprecated Therefore most previous answers are outdated. Use "python.defaultInterpreterPath" instead: 2021.6.0 (16 June 2021) 5. Added python.defaultInterpreterPath setting at workspace level when in pythonDeprecatePythonPath experiment. (#16485) 8. Show python.pythonPath deprecation prompt when in pythonDeprecatePythonPath experiment. (#16485) 2020.7.0 (16 July 2020) 9. Prompt users that we have deleted pythonPath from their workspace settings when in Deprecate PythonPath experiment. (#12533) 2020.5.0 (12 May 2020) 6. Do a one-off transfer of existing values for python.pythonPath setting to new Interpreter storage if in DeprecatePythonPath experiment. (#11052) 8. Added prompt asking users to delete python.pythonPath key from their workspace settings when in Deprecate PythonPath experiment. (#11108) 12. Rename string ${config:python.pythonPath} which is used in launch.json to refer to interpreter path set in settings, to ${conf…
downvote count: 0

http://stackoverflow.com/a/48125588
downvote count: 0
has comment: http://stackoverflow.com/comment/83227951
has comment: http://stackoverflow.com/comment/83227902
has comment: http://stackoverflow.com/comment/83228026
has comment: http://stackoverflow.com/comment/83227982
has comment: http://stackoverflow.com/comment/83227953
type: Answer
answers question: http://stackoverflow.com/q/48125438
has comment: http://stackoverflow.com/comment/83228001
has comment: http://stackoverflow.com/comment/83227888
accepted answer of: http://stackoverflow.com/q/48125438
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83227917
has body: I believe you need skip all rows by positions defined in list, row 10 is not in list, because data for Andorra. Data (row 1-8) before position defined in header (9) are excluded by default . Also parse_cols was replaced by usecols, because warning: FutureWarning: the 'parse_cols' keyword is deprecated, use 'usecols' instead parse_cols = "C:F" df=pd.read_excel('Energy Indicators.xls', sheet_name='Energy', skiprows=[10,12,13,14,15,16,17], skipfooter=38, header=9, usecols=[2,3,4,5] #parse_cols = "C:F" ) print (df.head()) Country Energy Supply Energy Supply per capita \ 0 Andorra 9 121 1 Afghanistan 321 10 2 Albania 102 35 3 Algeria 1959 51 4 American Samoa ... ... Renewable Electricity Production 0 88.695650 1 78.669280 2 100.000000 3 0.551010 4 0.641026
type: AcceptedAnswer

http://stackoverflow.com/a/48493514
has body: Your notebook exceeded size, not your code. Your last line, lista_de_contato, it is outputting data to your notebook. THAT makes the notebook big, not your code. As a suggestion, I would try to limit the display. For instance, if you store the data in a pandas dataframe, the display will be limited automatically for you. I always try to organize data from scraping in pandas dataframes because they are really easy to export and to fiddle around. Also, if you need, I'm brazilian as well and may help (I'm assuming you're brazilian as well, because you're scraping a brazilian advertising website)
score: 1
has comment: http://stackoverflow.com/comment/84633294
has comment: http://stackoverflow.com/comment/84672174
upvote count: 1
answers question: http://stackoverflow.com/q/48036369
type: Answer
downvote count: 0

http://stackoverflow.com/comment/83255444
score: 0
type: QuestionComment
type: Comment
has text: @Galik I edited question with compilation lines
comment on: http://stackoverflow.com/q/48138966

http://stackoverflow.com/q/48078566
accepted answer: http://stackoverflow.com/a/48078663
downvote count: 1
has comment: http://stackoverflow.com/comment/83131265
has body: I have made a snakes game in Python which was referred from someplace, but am getting error. The program snakes.py is given below: import random import curses s= curses.initscr() curses.curs_set(0) sh, sw = s.getmaxyx() w = curses.newwin(sh, sw, 0, 0) w.keypad(1) w.timeout(100) snk_x = sw/4 snk_y = sh/2 snake = [ [snk_y, snk_x], [snk_y, snk_x-1], [snk_y, snk_x-2] ] food = [sh/2, sw/2] w.addch(food[0], food[1], curses.ACS_PI) key = curses.KEY_RIGHT while True: next_key = w.getch() key = key if next_key == -1 else next_key if snake[0][0] in [0,sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]: curses.endwin() quit() new_head = [snake[0][0], snake[0][1]] if key == curses.KEY_DOWN: new_head[0] +=1 if key == curses.KEY_UP: new_head[0] -=1 if key == curses.KEY_LEFT: new_head[1] -=1 if key == curses.KEY_RIGHT: new_head[1] +=1 snake.insert(0, new_head) if snake[0] == food: food = None while food is None: nf = [ random.randint(1, sh-1), random.randint(1, sw-1) ] food = nf if nf not in snake else None w.addch(food[0], food[1], curses.ACS_PI) else: tail = snake.pop() w.addch(tail[0], tail[1], ' ') w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD) I am getting the following error on w.addch(food[0], food[1], curses.ACS_PI): TypeError: integer argument expected, got float. I am also usng python 3.6 version, so how to fix this code.
has comment: http://stackoverflow.com/comment/83131374
has comment: http://stackoverflow.com/comment/83131479
has comment: http://stackoverflow.com/comment/83131088
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1282945
has title: Error in Python application
has comment: http://stackoverflow.com/comment/83131009
favorite count: 0
has answer: http://stackoverflow.com/a/48078663
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/83131055
tagged with: python
has comment: http://stackoverflow.com/comment/83131026
has answer: http://stackoverflow.com/a/48078652
has comment: http://stackoverflow.com/comment/83131533
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48078652
upvote count: 1

http://stackoverflow.com/comment/83079964
type: Comment
has text: Are you asking whether you can write a class that inherits from another class without writing a class?
score: 0
comment on: http://stackoverflow.com/q/48053797
type: QuestionComment

rtp
tags question: http://stackoverflow.com/q/48158785
type: Tag
tag name: rtp

http://stackoverflow.com/a/48015573
accepted answer of: http://stackoverflow.com/q/48015460
answers question: http://stackoverflow.com/q/48015460
has comment: http://stackoverflow.com/comment/83000612
upvote count: 1
type: AcceptedAnswer
has body: "One"-liner, using some itertools: from itertools import groupby, chain a=[0,1,1,2,3,2,1,2,0,3,4,1,1,1,1,0,0,0,0,4,5,1,1,1,3,2,0,2,1,1,3,4,1] list( chain.from_iterable( ([0] * len(lst) if x == 1 and len(lst) &lt;= n else lst for x, lst in ((k, list(g)) for k, g in groupby(a))) ) ) # [0,0,0,2,3,2,0,2,0,3,4,1,1,1,1,0,0,0, 0,4,5,1,1,1,3,2,0,2,0,0,3,4,0] groupby groups the initial list into groups of identical objects. Its output is an iterator of pairs (k, g) where k is the element that is the grouping key and g is an iterator producing the actual elements in the group. Since you cannot call len on an iterator, this listifies the groups and chains the resulting lists except lists of 1 of the appropriate lengthes. Those are replaced by lists of 0 of the same length. In single steps (using intermediate lists instead of generators): grouped_lists_by_key = [k, list(g)) for k, g in groupby(a)] # [(0, [0]), (1, [1, 1]), ...] grouped_lists = [[0] * len(lst) if x == 1 and len(lst) &lt;= n else lst for x, lst in grouped] # [[0], [0, 0], [2], [3], ...] flattened = chain.from_iterable(grouped_lists) # [0, 0, 0, 2, 3, ...]
type: Answer
has comment: http://stackoverflow.com/comment/83000441
downvote count: 0
score: 1

http://stackoverflow.com/comment/83279632
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48150650
has text: I want to get rid of old content. Old content must not exist after new content is added. when API clients ask for HSET they shouldn't get old content. If I add HSET when I ask for a set, it will also return the old ones.
score: 3

http://stackoverflow.com/comment/83296215
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48157533
has text: ok cool, I think the `fileinput` module may be causing problems getting the correct output. What is the line `count = line.count(ok)` counting?
score: 0

http://stackoverflow.com/comment/83270011
has text: for python what will be package ?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48145852

c#
tags question: http://stackoverflow.com/q/48082043
tag name: c#
tags question: http://stackoverflow.com/q/48083313
tags question: http://stackoverflow.com/q/48173038
tags question: http://stackoverflow.com/q/48041476
tags question: http://stackoverflow.com/q/48095890
tags question: http://stackoverflow.com/q/48067809
tags question: http://stackoverflow.com/q/48159911
tags question: http://stackoverflow.com/q/48079577
type: Tag

http://stackoverflow.com/comment/83246595
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48134662
type: Comment
has text: Are you actually sending json? Or just plaintext?

http://stackoverflow.com/comment/83064966
type: Comment
type: QuestionComment
has text: @AmosEgel Linux by the look of it (the .so file makes me think that).
score: 0
comment on: http://stackoverflow.com/q/48046646

http://stackoverflow.com/comment/83044445
type: QuestionComment
has text: Ok. Set. edited again. thank you for the patience. The Flags thing was a good lesson.
type: Comment
comment on: http://stackoverflow.com/q/48030027
score: 0

http://stackoverflow.com/a/48113674
has comment: http://stackoverflow.com/comment/83203341
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83203241
has body: To encode a permutation to a value in pseudocode: A = list of cards value = 0 for i in range(52): cards_left = 52-i let pos = index of card i in A delete A[pos] value = value * cards_left + pos At the end, A will be an empty list, and value has a number representing the permutation. To decode: A = [] value is an input for i in reversed(range(52)): cards_left = 52-i pos = value % cards_left value = value / cards_left Insert card i at index pos in A At end, A should contain the original permutation. Example Python code: B=[3,2,0,1,4] def encode(A): value = 0 n = len(A) A = A[:] # Take a copy to avoid modifying original input array for i in range(n): cards_left = n-i pos = A.index(i) del A[pos] value = value * cards_left + pos return value def decode(value,n): A=[] for i in range(n-1,-1,-1): cards_left = n-i value,pos = divmod(value, cards_left) A.insert(pos,i) return A v=encode(B) print v print decode(v,len(B))
has comment: http://stackoverflow.com/comment/83203015
upvote count: 10
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48113498
has comment: http://stackoverflow.com/comment/83202979
accepted answer of: http://stackoverflow.com/q/48113498
score: 10

http://stackoverflow.com/comment/105480490
score: 0
has text: Just note this variable overrides `stdin`/`stdout`/`stderr` all at once. Python3 [docs](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONIOENCODING)
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48034692

http://stackoverflow.com/q/48074730
favorite count: 0
type: Question
tagged with: python
score: -1
tagged with: fixed-width
has title: How to scrape fixed-width files in Python?
answer count: 2
tagged with: web-scraping
downvote count: 1
has answer: http://stackoverflow.com/a/48075638
has body: In Python 3 I have a series of links with "fixed-width files". They are websites with public information about companies. Each line has information about companies Example links: http://idg.receita.fazenda.gov.br/orientacao/tributaria/cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/consultas/download/F.K03200UF.D71214AC and http://idg.receita.fazenda.gov.br/orientacao/tributaria/cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/consultas/download/F.K03200UF.D71214RO I have these links in a dictionary. The key is the name of the region of the country in which the companies are and the value is the link for chave, valor in dict_val.items(): print (f'Region of country: {chave} - and link with information: {valor}') Region of country: Acre - and link with information: http://idg.receita.fazenda.gov.br/orientacao/tributaria/cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/consultas/download/F.K03200UF.D71214AC Region of country: Espírito Santo - and link with information: http://idg.receita.fazenda.gov.br/orientacao/tributaria/cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/consultas/download/F.K03200UF.D71214ES ... I want to read these links (fixed-width files) and save the content to a CSV file. Example content: 0107397388000155ASSOCIACAO CULTURAL 02073973880001552 16MARIA DO SOCORRO RODRIGUES ALVES BRAGA 0101904573000102ABREU E SILVA COMERCIO DE MEDICAMENTOS LTDA-ME - ME 02019045730001022 49JETEBERSON OLIVEIRA DE ABREU 02019045730001022 49LUZINETE SANTOS DA SILVA ABREU 0101668652000161CONSELHO ESCOLAR DA ESCOLA ULISSES GUIMARAES 02016686520001612 10REGINA CLAUDIA RAMOS DA SILVA PESSOA 0101631137000107FORTERM * REPRESENTACOES E COMERCIO LTDA 02016311370001072 49ANTONIO MARCOS GONCALVES 02016311370001072 22IVANEIDE BERNARDO DE MENEZES But to fill the rows of the CSV columns I need to separate and test on each line of the links with "fixed-width files" I must follow rules like these: 1. If the line begins with "01" is a line with the company's regist…
accepted answer: http://stackoverflow.com/a/48075638
possible better answer: http://stackoverflow.com/a/48075116
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/48075116
linked to: http://stackoverflow.com/q/36226727

http://stackoverflow.com/q/48144610
score: 0
has comment: http://stackoverflow.com/comment/83267930
has comment: http://stackoverflow.com/comment/83268222
has comment: http://stackoverflow.com/comment/83268055
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83268034
tagged with: python
has title: python3: urllib.parse import error
answer count: 0
has comment: http://stackoverflow.com/comment/83267380
has comment: http://stackoverflow.com/comment/83268001
has body: I have a code like below in python 3 from urllib.parse import quote quote("Stanford University") When I run the code, I get below error ImportError: No module named parse Per docs, urllib.parse is part of python3. So I did pip install urllib but then getting error No matching distribution found for urllib What am I missing? EDIT: pip --version pip 9.0.1 from /Users/myusername/anaconda3/lib/python3.6/site-packages (python 3.6) output of (urllib.path) &gt;&gt;&gt; import urllib &gt;&gt;&gt; print(urllib.__path__) ['/Users/myusername/anaconda3/lib/python3.6/urllib']
has comment: http://stackoverflow.com/comment/83267906
type: Question
has comment: http://stackoverflow.com/comment/83267306

http://stackoverflow.com/a/48054089
has body: Though, your question is a bit unclear, try this: for x in range(2011, 2016): print("{}/{}".format(x, x+1)) Output: 2011/2012 2012/2013 2013/2014 2014/2015 2015/2016
score: 0
answers question: http://stackoverflow.com/q/48054019
type: Answer

http://stackoverflow.com/q/48040843
type: UnansweredQuestion
tagged with: amazon-web-services
type: Question
tagged with: pandas
tagged with: bootstrapping
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/83071118
has body: I have a script that needs some Python modules like numpy, putsy, pandas and sklearn. I made a Bootstrap on the EMR - Cluster with the following: sudo yum install -y python27-numpy sudo pip install matplotlib pandas putsy scipy sudo pip install -U scikit-learn Bootstrap is running. But the command Import pandas as pd gets the error: NameError: name 'pd' is not defined Why is pandas not running after successful Bootstrap? Do you have any idea?
has comment: http://stackoverflow.com/comment/83053191
has title: aws emr bootstrap python modules -
tagged with: numpy
answer count: 0

http://stackoverflow.com/q/48159461
has comment: http://stackoverflow.com/comment/83298922
favorite count: 0
has comment: http://stackoverflow.com/comment/83298615
has answer: http://stackoverflow.com/a/48160700
tagged with: python
has title: Scipy.optimize.minimize: Why is a global minimizing loss function much much slower than local one using Scipy minimize?
has comment: http://stackoverflow.com/comment/83298642
has comment: http://stackoverflow.com/comment/83298998
type: UnansweredQuestion
tagged with: scipy
has comment: http://stackoverflow.com/comment/83313314
has comment: http://stackoverflow.com/comment/83298569
has comment: http://stackoverflow.com/comment/83298830
has body: I have two loss functions here to be minimized: The first one is a local one, where: min f1(x1), min f2(x2), min f3(x3),.... min fn(xn) The other one is global one, where: min f(x1,x2,...,xn) = f1(x1)+f2(x2)+...fn(xn) For each local problem fi(x), I have 2 variables to be optimized, and I have 1000 local problems. Correspondingly, for the global problem, I have 2000 variables to be optimized. Surely the 2nd one has more parameters to be optimized, but since f1, f2, f3...fn are independent with each other, I hope they two should be comparable. I use the scipy minimize function for optimization (scipy.optimize.minimize). But the 2nd one much much slower than the 1st one. The only drawback of the global one, i think, is taking more gradients than it actually need to. For example, the gradient of x1 only comes from f1, but the global computes its gradient from f2, f3... fn, which is 0. Thus, making it slower. If that is the case, I do hope there would be some ways for acceleration. BTW, since I later on need to add a global constraint to the optimization, this is why I must use the global loss function instead of the local one.
score: -1
has comment: http://stackoverflow.com/comment/83298682
tagged with: optimization
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83298462
downvote count: 2
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/83159429
comment on: http://stackoverflow.com/q/48092427
type: Comment
type: QuestionComment
score: 0
has text: But since you're limiting the number of forward fills, it could become faster?

http://stackoverflow.com/q/48072521
tagged with: python
score: 0
answer count: 1
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/48073042
has body: I have this raw SQL statement that I would like to use for both Core and ORM: SELECT * FROM `buffet` WHERE `roomId` = '864495034004835' AND `recordMasa` &gt; '1514600000' AND `recordMasa` &lt; '1514900000' AND `recordMasa` mod 10 = 0 LIMIT 0,10000000000; Please do let me know how can I add to my existing code below to include the modulo function: select_statement = select([Buffet]).where(and_( Buffet.recordMasa &gt; arguments['startDate'], Buffet.recordMasa &lt; arguments['endDate'], Buffet.roomId == arguments['ident'] )) rooms = conn.execute(select_statement).fetchall()
type: AnsweredQuestion
has title: How to use modulo in sqlalchemy?
type: Question
accepted answer: http://stackoverflow.com/a/48073042

http://stackoverflow.com/comment/126763728
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48036961
type: Comment
has text: @Masquue the C++ standard is a *very* different beast from the Python documentation. I stand by my statement, Python is, relatively speaking, clearer and more consistent.

http://stackoverflow.com/comment/107680290
type: Comment
has text: When I try running this I get: ```Traceback (most recent call last): File "after.py", line 16, in <module> data = pd.DataFrame.from_dict(response_json['Time Series (Daily)'], orient= 'index').sort_index(axis=1) KeyError: 'Time Series (Daily)' ```
comment on: http://stackoverflow.com/a/59161026
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83175427
comment on: http://stackoverflow.com/q/48099075
has text: Sparse column selection is done with matrix multiplication, as described in https://stackoverflow.com/questions/39500649/sparse-matrix-slicing-using-list-of-int. Such a selection will create a new sparse matrix. Have you been able to do any other calculations with this large matrix? Make a copy?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48122225
accepted answer of: http://stackoverflow.com/q/48122170
has body: We can first build a regex that identifies positive integers: from re import compile INTEGER_REGEX = compile(r'\b\d+\b') Here \d stands for digit (so 0, 1, etc.), + for one or more, and \b are word boundaries. We can then use INTEGER_REGEX.findall(some_string) to identify all positive integers from the input. Now the only thing left to do is iterate through the elements of the list, and convert the output of INTEGER_REGEX.findall(..) to a tuple. We can do this with: output = [tuple(INTEGER_REGEX.findall(l)) for l in my_list] For your given sample data, this will produce: &gt;&gt;&gt; [tuple(INTEGER_REGEX.findall(l)) for l in my_list] [('123', '321'), ('223', '32221'), ('19823', '328771')] Note that digits that are not separate words will not be matched. For instance the 8 in 'see you l8er' will not be matched, since it is not a word.
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/48122170
score: 6
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83221267

http://stackoverflow.com/q/48069858
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/83119575
has comment: http://stackoverflow.com/comment/83120151
type: Question
tagged with: nginx
tagged with: digital-ocean
score: 0
tagged with: file-system-storage
has body: I am going to use to DigitalOcean Droplet and want to configure it for serving protected files like pictures, mp3 and videos with Nginx. Questions: Is it like I serve my file as FileSystemStorage on my local computer with setting up all permissions related thing? It will serve after payment process will complete. All functionality was implemented on localhost and it works well: from django.db import models from django.core.files.storage import FileSystemStorage class ProductFile(models.Model): file = models.FileField( upload_to=uploade_protected_file, storage=FileSystemStorage(location=settings.PROTECTED_ROOT) ) Do this same type of setup work on DigitalOcean as well?
has title: Serving protected files using Django through DigtalOcean and Nginx
tagged with: python

http://stackoverflow.com/q/48162778
has body: I'm writing a genetic algorithm for writing code, and was wondering whether a simple venv wrapper would prevent nonsense that could step from use of exec "import os; ...". I tried exec "..." in {}, which I had tried hoping to only make the things inside of {} available to exec. Basically, I'm looking for a safe way to execute randomly generated code. Would a venv wrapper do the trick? I read that venv could separate the virtual directory from my system's files, but I'm not sure I read that correctly.
has title: Is a python venv wrapper enough to isolate the effects of exec in python?
tagged with: python
score: 0
tagged with: python-venv
has comment: http://stackoverflow.com/comment/83304916
answer count: 0
has comment: http://stackoverflow.com/comment/83305308
type: UnansweredQuestion
type: Question

http://stackoverflow.com/q/48167088
has body: I'm working on the News model. I have a list page and a detail page. I need on the detail page with the option of selecting other related news in the admin panel and saving them on the site. My model: class News(models.Model): title = models.CharField(max_length=500) subtitle = models.CharField(max_length=1000, blank=True) text = models.TextField() link = models.ForeignKey('.'.join(LINK_MODEL), null=True, blank=True) link_title = models.CharField(max_length=500) date = models.DateField(null=True) image = FilerImageField() class Meta: verbose_name_plural = 'news' ordering = ['-date'] Should I use a foreign key?
tagged with: model
has comment: http://stackoverflow.com/comment/83318530
tagged with: python
has comment: http://stackoverflow.com/comment/83313569
answer count: 0
type: UnansweredQuestion
tagged with: select
tagged with: django
has title: Showing related items to the same model on detail page
type: Question
tagged with: django-select-related
score: 0
has comment: http://stackoverflow.com/comment/83314051

http://stackoverflow.com/q/48025538
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83020700
has title: Keras' ImageDataGenerator randomly throws an error when accessing image files
score: 1
has answer: http://stackoverflow.com/a/48025645
upvote count: 1
type: Question
tagged with: python-imaging-library
has body: I am using the keras.preprocessing.image ImageDataGenerator to stream images from a folder on my hard drive. It works mostly, but the code randomly throws an error when accessing images. The error message looks like this: img = pil_image.open(path) File "C:\Program Files\Anaconda3\envs\py35_cv2_nb_tf\lib\site-packages\PIL\Image.py", line 2452, in open % (filename if filename else fp)) OSError: cannot identify image file 'd:/workspace/cat_dog/train\\cats\\666.jpg' But I think it is misleading, since: sometimes it goes through the whole batch without any problem. When the crash occurs, it always happens at a different image. there is nothing obviously wrong with the cat666 image but after the crash, the file remains locked Any ideas? I have already removed all meta-data from the images.
answer count: 1
downvote count: 0
tagged with: keras

http://stackoverflow.com/comment/83136008
type: Comment
comment on: http://stackoverflow.com/a/48067326
type: AnswerComment
has text: @StefanPochmann Ok, I finally figured out how to do each group in linear time. Thanks for the encouragement.
score: 0

class-variables
tag name: class-variables
type: Tag
tags question: http://stackoverflow.com/q/48096506

buildpack
tag name: buildpack
type: Tag
tags question: http://stackoverflow.com/q/48119718

http://stackoverflow.com/a/48152675
has comment: http://stackoverflow.com/comment/96699206
accepted answer of: http://stackoverflow.com/q/48152674
has comment: http://stackoverflow.com/comment/133297711
has comment: http://stackoverflow.com/comment/133297706
has comment: http://stackoverflow.com/comment/101060915
type: Answer
has comment: http://stackoverflow.com/comment/113610927
has comment: http://stackoverflow.com/comment/133297846
has comment: http://stackoverflow.com/comment/129846769
upvote count: 1032
has comment: http://stackoverflow.com/comment/136918983
has comment: http://stackoverflow.com/comment/138826856
answers question: http://stackoverflow.com/q/48152674
downvote count: 7
has comment: http://stackoverflow.com/comment/83337969
score: 1025
has body: These functions should help: &gt;&gt;&gt; import torch &gt;&gt;&gt; torch.cuda.is_available() True &gt;&gt;&gt; torch.cuda.device_count() 1 &gt;&gt;&gt; torch.cuda.current_device() 0 &gt;&gt;&gt; torch.cuda.device(0) &lt;torch.cuda.device at 0x7efce0b03be0&gt; &gt;&gt;&gt; torch.cuda.get_device_name(0) 'GeForce GTX 950M' This tells us: CUDA is available and can be used by one device. Device 0 refers to the GPU GeForce GTX 950M, and it is currently chosen by PyTorch.
has comment: http://stackoverflow.com/comment/122796556
has comment: http://stackoverflow.com/comment/129095033
has comment: http://stackoverflow.com/comment/97373965
has comment: http://stackoverflow.com/comment/101059713
has comment: http://stackoverflow.com/comment/114529316
type: AcceptedAnswer

http://stackoverflow.com/q/48027842
has answer: http://stackoverflow.com/a/50122351
type: Question
has title: How to use variables in ffmpy (python wrapper for FFmpeg)?
score: 0
answer count: 2
tagged with: ffmpeg
tagged with: python
has answer: http://stackoverflow.com/a/60644732
tagged with: video
has body: I would like to ask how to use variables in ffmpy (Python wrapper for FFmpeg). To be exactly: I want to use variables to crop video. The FFmpeg command is: ffmpeg in.mp4 -filter:v "crop=out_w:out_h:x:y" out.mp4 https://ffmpeg.org/ffmpeg-filters.html#crop To use it in Python/ffmpy, I wrote these codes: from ffmpy import FFmpeg import ffmpy # define the variables out_w = 100 out_h = 120 x = 50 y = 80 inputFile = "F:\\in.avi" outputFile = "F:\\out.avi" ff = FFmpeg(inputs = {inputFile: None}, outputs= {outputFile: " -y -filter:v `crop=100:120:50:80'"}) #This line works fine. #Now rewrite the above line using variables... ff = FFmpeg(inputs = {inputFile: None}, outputs={outputFile: " -y -filter:v `crop=out_w:out_h:x:y'"} ) #...It line does not work. I guess it is wrong to use variables in the statement. #...This is my question. How to write this line using variables? ff.cmd ff.run() Thanks for your help!
type: UnansweredQuestion

http://stackoverflow.com/comment/83310320
score: 0
comment on: http://stackoverflow.com/q/48165302
type: Comment
type: QuestionComment
has text: @AntiMatterDynamite Can you elaborate on that? What do you mean?

geodjango
tags question: http://stackoverflow.com/q/48040545
tag name: geodjango
type: Tag
tags question: http://stackoverflow.com/q/48033648
tags question: http://stackoverflow.com/q/48035684

http://stackoverflow.com/comment/83263436
type: QuestionComment
has text: @Copperfield Oks thanks for the advice, will try to use some kind of list with saved coordinates and radius to avoid the overlapping.
comment on: http://stackoverflow.com/q/48142473
score: 0
type: Comment

http://stackoverflow.com/comment/84743096
type: QuestionComment
comment on: http://stackoverflow.com/q/48081971
has text: It is not that bad, If you consider the ratios of the approximate distances are 406/397 ~= 1.02 and 404/399 ~= 1.012 . So the pairwise distances are relatively preserved as expected by the https://en.wikipedia.org/wiki/Johnson%E2%80%93Lindenstrauss_lemma . Note the error term in the lemma is O(1/eps^2), so if you need more digits of precision, you need more dimensions.
score: 0
type: Comment

http://stackoverflow.com/comment/83296316
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48156294
has text: I changed the port to 12345 and now I'm getting the error: unknownError
score: 0

http://stackoverflow.com/a/48065391
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48065278
has body: I'd suggest you get all your data checking and correction handled up front, so your actual algorithm can be much simpler: numXs = 0 while numXs &lt;= 0: numXs = int(input('How many times should I print the letter X? ')) if numXs &lt;= 0: print('Enter an integer &gt; 0') print('X' * numXs)
accepted answer of: http://stackoverflow.com/q/48065278
has comment: http://stackoverflow.com/comment/83104427
upvote count: 5

http://stackoverflow.com/q/48106901
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
linked to: http://stackoverflow.com/q/7459246
linked to: http://stackoverflow.com/q/30506091
accepted answer: http://stackoverflow.com/a/48106917
has title: NameError on list that's initialized in the constructor [Python3]
tagged with: nameerror
has answer: http://stackoverflow.com/a/48106917
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83189395
has body: I'm extremely new to programming, and my projects thus far have consisted of Frankenstein-esque monsters of stitched together sample codes. This is my first project that I am developing largely independently. So far it has not gone well. It's fun though! I'm working on a class function that returns only the values of one list that aren't in another given list. I found code from here, but I'm getting a NameError. My code: def __init__ (self, extracted): #Constructor allWords = extracted shelfFile = shelve.open('knownWordsPersistant') #Opens preexisting shelve module file knownWords = shelfFile['knownWords'] #The list that the error specifies def getUnknownWords (self): return [x for x in allWords if x not in knownWords] #Line that causes error And the error: Traceback (most recent call last): File "C:\Users\Jack Hanson\Desktop\Programming\Python\VocabFinder\main.py", line 16, in &lt;module&gt; possUnknWrds = knownWordsObject.getUnknownWords(vocabArray) File "C:\Users\Jack Hanson\Desktop\Programming\Python\VocabFinder\KnownWordsUpdater.py", line 16, in getUnknownWords if (inArray[i] not in knownWords): NameError: name 'knownWords' is not defined If you need any more context or information, I'll happily provide.
tagged with: python

http://stackoverflow.com/a/48116857
downvote count: 0
answers question: http://stackoverflow.com/q/48116298
upvote count: 2
has body: There is a neat solution with numpy: import numpy as np arr = np.asarray([1, 2, 3, 4, 5, 6, 7, 8]) # converts your list in numpy array idx1 = [0, 3, 4, 6] idx2 = [1, 2, 5, 7] arr1 = arr[idx1] # [1 4 5 7] arr2 = arr[idx2] # [2 3 6 8]
type: Answer
score: 2

http://stackoverflow.com/comment/139701293
has text: fyi making `concurrent.futures.Process/ThreadPoolExecutor.map` lazy by only buffering a parameterized number of not-yet-yielded results is the exact goal of this PR https://github.com/python/cpython/pull/125663, if you can thumb up on it to give it visibility it may end up in Python 3.14
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48135348
score: 0

http://stackoverflow.com/comment/83255023
score: 0
type: Comment
type: QuestionComment
has text: Thanks a lot for your recommendation! When I tried to print the tensorflow version, Java printed out 1.3.0. Upon looking further I found out that eventhough I had added libtensorflow-1.5.0-rc0.jar to my project in eclipse, I hadnt added the appropriate tensorflow_jni.dll so Java was using tensorflow 1.3. Once I added the the correct tensorflow_jni.dll, my model was loaded successfully. Thanks again!
comment on: http://stackoverflow.com/q/48132420

http://stackoverflow.com/comment/83308143
type: Comment
comment on: http://stackoverflow.com/a/48158238
type: AnswerComment
has text: @Lizou try running the code on just one page (there are 2500+, too long to test all) but I get 24 drugs from page 1 with this code...
score: 0

http://stackoverflow.com/comment/83363069
comment on: http://stackoverflow.com/a/48134119
has text: Thanks! I'll try this and report back.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48112371
type: Answer
answers question: http://stackoverflow.com/q/48112034
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48112034
has body: You should commit the transaction, add the commands: ... conn.commit() conn.close() Alternatively, you can set the connection in autocommit mode: conn = psycopg2.connect(user='a', password='a', dbname='a') conn.autocommit = True cur = conn.cursor() cur.callproc('try_create', ()) conn.close() Read more about transactions in psycopg2.
has comment: http://stackoverflow.com/comment/83200370
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/62895556
has comment: http://stackoverflow.com/comment/136809544
type: Answer
has body: I wanted a solution for python 3.6 and the below solution worked for me. sudo apt-get install python3.6-dev
has comment: http://stackoverflow.com/comment/111296727
has comment: http://stackoverflow.com/comment/133844006
score: 11
downvote count: 1
answers question: http://stackoverflow.com/q/48154968
upvote count: 12

http://stackoverflow.com/comment/83040276
type: QuestionComment
has text: So maybe just `pd.to_datetime(new_df[0].str.replace(' ', '') + '2016', format='%d%b%Y')` ?
comment on: http://stackoverflow.com/q/48035105
score: 1
type: Comment

http://stackoverflow.com/q/48134059
linked to: http://stackoverflow.com/q/11026959
has comment: http://stackoverflow.com/comment/83245541
score: 0
accepted answer: http://stackoverflow.com/a/48134119
has title: Importing a raw dictionary in to Python that was exported using f.open()
duplicate of: http://stackoverflow.com/q/11026959
has comment: http://stackoverflow.com/comment/83245502
possible better answer: http://stackoverflow.com/a/48134116
has answer: http://stackoverflow.com/a/48134116
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83245429
has comment: http://stackoverflow.com/comment/83245632
has answer: http://stackoverflow.com/a/48134119
type: Question
has body: everyone. I was tinkering with ways to store dictionaries and retrieve them later, loading them into and replacing the existing dictionary values. I was intending to use this as a way to store game data in a simple text-based game. # Player dictionaries p1 = {'name' : "placeholder", 'hp': 0, 'str': 0, 'stm': 0, 'mana': 0, 'atk': 0, 'def': 0, 'cyra' : 0, 'monero' : 0, 'bits': 0, 'dollars': 0, 'nordas': 0,} p2 = {'name' : "placeholder", 'hp': 0, 'str': 0, 'stm': 0, 'mana': 0, 'atk': 0, 'def': 0, 'cyra' : 0, 'monero' : 0, 'bits': 0, 'dollars': 0, 'nordas': 0,} p3 = {'name' : "placeholder", 'hp': 0, 'str': 0, 'stm': 0, 'mana': 0, 'atk': 0, 'def': 0, 'cyra' : 0, 'monero' : 0, 'bits': 0, 'dollars': 0, 'nordas': 0,} p4 = {'name' : "placeholder", 'hp': 0, 'str': 0, 'stm': 0, 'mana': 0, 'atk': 0, 'def': 0, 'cyra' : 0, 'monero' : 0, 'bits': 0, 'dollars': 0, 'nordas': 0,} p5 = {'name' : "placeholder", 'hp': 0, 'str': 0, 'stm': 0, 'mana': 0, 'atk': 0, 'def': 0, 'cyra' : 0, 'monero' : 0, 'bits': 0, 'dollars': 0, 'nordas': 0,} p6 = {'name' : "placeholder", 'hp': 0, 'str': 0, 'stm': 0, 'mana': 0, 'atk': 0, 'def': 0, 'cyra' : 0, 'monero' : 0, 'bits': 0, 'dollars': 0, 'nordas': 0,} #save function import pickle def save() : f = open("p1.txt","w") f.write( str(p1) ) f.close() f = open("p2.txt","w") f.write( str(p2) ) f.close() f = open("p3.txt","w") f.write( str(p3) ) f.close() f = open("p4.txt","w") f.write( str(p4) ) f.close() f = open("p5.txt","w") f.write( str(p5) ) f.close() f = open("p6.txt","w") f.write( str(p6) ) f.close() print ("The game was saved.") To my delight, I discovered that this does work, and it creates six files names "p1.txt", "p2.txt", and so forth in the folder that the program is saved. It looks exactly like the original dictionary: {'name': 'placeholder', 'hp': 0, 'str': 0, 'stm': 0, 'mana': 0, 'atk': 0, 'def': 0, 'cyra': 0, 'monero': 0, 'bits': 0, 'dollars': 0, 'nordas': 0} However, upon attempting to try and create an import_save() function, I ran into a pr…
answer count: 2
has comment: http://stackoverflow.com/comment/83245585
tagged with: python

http://stackoverflow.com/q/48168328
has body: I have a particular folder(Test) in my D drive. Every week a new folder gets created inside test like 1234,4231,etc. I want to write a python script which can print the folder name recently created. I was able to do upto this. import os for file in os.listdir("D:\Test1"): if file.endswith(".txt"): #print(os.path.join("/mydir", file)) s = os.path.join("/mydir", file)
possible better answer: http://stackoverflow.com/a/48168746
tagged with: python
has answer: http://stackoverflow.com/a/48168746
tagged with: selenium-webdriver
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/83315808
type: Question
has answer: http://stackoverflow.com/a/48171123
accepted answer: http://stackoverflow.com/a/48171123
score: 1
has title: How to read the file name in a directory and print as output using timestamp
answer count: 2
linked to: http://stackoverflow.com/q/2014554
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83323371
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83323436

http://stackoverflow.com/comment/83048349
score: 0
type: QuestionComment
type: Comment
has text: ...holy shit you are right, totally missed that
comment on: http://stackoverflow.com/q/48038968

http://stackoverflow.com/comment/83082455
type: AnswerComment
has text: the data.html must be in the same folder?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48054997

http://stackoverflow.com/comment/83147024
has text: Your "iteration with indices" explicitly generates the same string twice, and the order needs to be explained.
type: Comment
comment on: http://stackoverflow.com/q/48085830
type: QuestionComment
score: 0

http://stackoverflow.com/comment/112957551
has text: @problemofficer thanks for your advice, I have updated.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48132578

http://stackoverflow.com/comment/83197988
has text: an array `I` of shape `(1,2,H,W)`, the second axis is a `2-class` probability distribution, means the pair add to 1, I want to reshape it to `(2,H*W)`, there is `H*W` pairs, this first axis add to 1, but numpy reshape does not preserve the pairs, is that clear?
comment on: http://stackoverflow.com/q/48110592
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/66449961
has body: For people who wants to resize(interpolate) a batch of numpy array, pytorch provide a faster function names torch.nn.functional.interpolate, just remember to use np.transpose first to change the channel from batchxWxHx3 to batchx3xWxH.
answers question: http://stackoverflow.com/q/48121916
upvote count: 6
score: 6
type: Answer
downvote count: 0

http://stackoverflow.com/a/48018632
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48018514
upvote count: 2
has body: pip is a packager for Python you should only ever be able to install python-things with it. homebrew is a package manager for OSX. You can install any software with it. It does not impose any restrictions on the type of software to install. Python can be installed via homebrew. Installing things with homebrew will install them into /usr/local Installing things with pip will fetch packages from the Python Package Index, and it will install them in a place where your python interpreter will find them, normally in some global search-path of your python interpreter (e.g. /usr/local/lib/python2.7/dist-packages/), or into your home directory (e.g. ~/.local/lib/python2.7/site-packages/)
type: Answer

http://stackoverflow.com/comment/83023025
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48026581
has text: Not `hai\\n` but `hai\n`
score: 0

http://stackoverflow.com/q/48045302
has comment: http://stackoverflow.com/comment/83062029
has title: Backtesting in trading systems
type: Question
linked to: http://stackoverflow.com/q/47738537
has comment: http://stackoverflow.com/comment/83061763
has comment: http://stackoverflow.com/comment/83061947
tagged with: system
score: 0
tagged with: spyder
tagged with: trading
answer count: 0
has comment: http://stackoverflow.com/comment/83061930
type: UnansweredQuestion
tagged with: python
has body: I'm working in a trading system and I was backtesting a simple moving average to make buy and sell points. I got a code from the internet to help me but in the backtesting part I got stuck in a error: "TypeError: 'float' object does not support item assignment" Here is the code: initial_capital = float(1000) positions = pd.DataFrame(index=signals.index).fillna=(0.0) positions['AAPL'] = 100*signals['signal'] portfolio = positions.multiply(aapl['Adj Close'], axis=0) pos_diff = positions.diff() portfolio['holdings'] = (positions.multiply(aapl['Adj `Close'],axis=0)).sum(axis=1).cumsum()` portfolio['total'] = portfolio['cash'] + portfolio['holdings'] portfolio['returns'] = portfolio['total'].pct_change() The error appears after I run the third line # Initialize the `signals` DataFrame with the `signal` column signals = pd.DataFrame(index=aapl.index) signals['signal'] = 0.0 # Create short simple moving average over the short window signals['short_mavg'] = aapl['Close'].rolling(window=short_window, min_periods=1, center=False).mean() # Create long simple moving average over the long window signals['long_mavg'] = aapl['Close'].rolling(window=long_window, min_periods=1, center=False).mean() # Create signals signals['signal'][short_window:] = np.where(signals['short_mavg'][short_window:] &gt; signals['long_mavg'][short_window:], 1.0, 0.0) # Generate trading orders signals['positions'] = signals['signal'].diff()
has comment: http://stackoverflow.com/comment/83061775

http://stackoverflow.com/q/48166292
score: 1
upvote count: 1
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/83374862
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/83311970
favorite count: 0
has body: I am using flask-sqlalchemy to control Mysql as ORM. Here is my simple database graph simple graph about database Problem is that I am supposed to make a user list. Gonna sort each user based on the avarage star of reviews which can be found and calculated in many levels depth So I made some codes: UserModel.query\ .group_by(UserModel.id) \ .join(UserServiceModel,UserModel.id == UserServiceModel.user_id) \ .join(BookModel,UserServiceModel.id == BookModel.user_service_id) \ .join(ReviewModel,BookModel.id == ReviewModel.book_id) \ .with_entities(func.avg(ReviewModel.star)) \ .all() It seems the problem has been solved, almost, but those users who have no books or reviews are not in the list after I used JOIN. Question is , how can I sort all users by avarage stars even most of them have no review records, I need all users in the list no matter avarage is 0 or None. Otherwise, is there any other good idea to do this?
has comment: http://stackoverflow.com/comment/83329872
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83343404
has title: Using Flask-sqlalchemy, how to sort data using order_by with some avarage data which is need to join?
answer count: 0

http://stackoverflow.com/a/48042331
has body: Here's one with np.repeat to replicate along the first axis after you have a as a 3D array - N = 2 # replication number out = np.repeat(a,N,axis=0) Alternatively, for a 4D read-only output, we can create a view with np.broadcast_to and that would be very efficient, as we won't be hogging up any extra memory, like so - m,n,r = a.shape out = np.broadcast_to(a[:,None],(m,N,n,r)) # Confirm it's a view In [32]: np.shares_memory(a, out) Out[32]: True
answers question: http://stackoverflow.com/q/48042218
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83055493
type: Answer
accepted answer of: http://stackoverflow.com/q/48042218
upvote count: 3
has comment: http://stackoverflow.com/comment/83055459
score: 3

django-admin
tags question: http://stackoverflow.com/q/48152908
tags question: http://stackoverflow.com/q/48126870
tags question: http://stackoverflow.com/q/48067281
tags question: http://stackoverflow.com/q/48015196
type: Tag
tag name: django-admin
tags question: http://stackoverflow.com/q/48129467

http://stackoverflow.com/q/48096415
type: Question
has body: I'm writing a django application where I will get a dictionary from the user that can be of variable size. I want to have a limit for how big the dictionary can be, i.e. how many (key, value) pairs it can hold. I want it to be no bigger than 200. I suspect that if I do: if len(user_dict)&gt;200: raise ValidationError("dict has too many (key, value) pairs") python will have to count the whole dict. If the dict is huge, because of a malicious user, this will eat unnecessary processing power. Or does the dict keep track of how many objects it holds, meaning len(user_dict) is a simple lookup operation? What is the best way to solve this problem? I was thinking something like: i=0 for key in user_dict.keys(): i += 1 if i&gt;200: raise ValidationError("dict has too many (key, value) pairs")
score: 5
has answer: http://stackoverflow.com/a/48096613
upvote count: 6
duplicate of: http://stackoverflow.com/q/2212433
has comment: http://stackoverflow.com/comment/83167984
has comment: http://stackoverflow.com/comment/83168020
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83167537
linked to: http://stackoverflow.com/q/2212433
has comment: http://stackoverflow.com/comment/83167502
tagged with: python
type: AnsweredQuestion
has title: How to safely count dictionary keys in python
has comment: http://stackoverflow.com/comment/83167543
accepted answer: http://stackoverflow.com/a/48096613
has comment: http://stackoverflow.com/comment/83167724
tagged with: django

http://stackoverflow.com/comment/83265047
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48136499
score: 1
has text: I'm just curious to understand this a bit more. Where can I find more information regarding this? Any suggestions please?

http://stackoverflow.com/comment/83114647
type: QuestionComment
has text: I'm not sure if it's relevant here, but precisely speaking, your arguments are integers, not doubles. Maybe try with `100.0` instead of `100`?
comment on: http://stackoverflow.com/q/48070373
score: 0
type: Comment

http://stackoverflow.com/comment/86687542
has text: That should be a comment really.
type: AnswerComment
comment on: http://stackoverflow.com/a/49836001
type: Comment
score: 1

http://stackoverflow.com/q/48053691
type: Question
accepted answer: http://stackoverflow.com/a/48053730
answer count: 2
has answer: http://stackoverflow.com/a/48053715
possible better answer: http://stackoverflow.com/a/48053715
favorite count: 0
has body: For this while loop in Python: def last_vowel(s): Return the last vowel in s if one exists; otherwise, return None. i = ________ while i &gt;= 0: if s[i] in 'aeiouAEIOU': return s[i] i = i - 1 return None The question is to find i's expression, which turns out to be len(s) - 1 rather than len(s). Can anyone explain to me why this is so?
has answer: http://stackoverflow.com/a/48053730
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: While Loop multiple choice what is value of increment index
score: 0
downvote count: 1

http://stackoverflow.com/comment/83903251
comment on: http://stackoverflow.com/q/48060041
type: QuestionComment
type: Comment
score: 1
has text: You should make a directory named 'modeldir'.

http://stackoverflow.com/comment/83198448
comment on: http://stackoverflow.com/q/48111296
score: 0
type: Comment
type: QuestionComment
has text: Thanks! I've posted some more stuff and now I'm reading the article and will do my best.

http://stackoverflow.com/q/48024720
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48024831
tagged with: network-programming
downvote count: 0
has answer: http://stackoverflow.com/a/62277798
favorite count: 0
has body: I have the following code, which is self explanatory: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(host, port) s.send("some data") # don't close socket just yet... # do some other stuff with the data (normal string operations) if s.stillconnected() is true: s.send("some more data") if s.stillconnected() is false: # recreate the socket and reconnect s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(host, port) s.send("some more data") s.close() How do I implement s.stillconnected() I do not wish to recreate the socket blindly.
possible better answer: http://stackoverflow.com/a/62277798
accepted answer: http://stackoverflow.com/a/48024831
tagged with: sockets
tagged with: python
has title: Python - How to check if socket is still connected
score: 19
type: AnsweredQuestion
upvote count: 19
tagged with: tcp
has comment: http://stackoverflow.com/comment/83027602
tagged with: tcpclient

http://stackoverflow.com/comment/83130894
type: Comment
has text: `pd.read_csv('file.csv', usecols=list(range(30)))`?
comment on: http://stackoverflow.com/q/48078558
score: 1
type: QuestionComment

http://stackoverflow.com/q/48078489
has comment: http://stackoverflow.com/comment/83131679
has comment: http://stackoverflow.com/comment/83136484
has comment: http://stackoverflow.com/comment/83135901
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83136765
has answer: http://stackoverflow.com/a/48081315
type: AnsweredQuestion
tagged with: tolist
has comment: http://stackoverflow.com/comment/83130849
score: 1
has comment: http://stackoverflow.com/comment/83131729
has comment: http://stackoverflow.com/comment/83130778
type: Question
tagged with: numpy
tagged with: arrays
has comment: http://stackoverflow.com/comment/83135615
tagged with: mat-file
has body: I want to read a matfile in python and then export the data in a database. in order to do this I need to have the data type as list in python. I wrote the code below: import scipy.io as si import csv a = si.loadmat('matfilename') b = a['variable'] list1=b.tolist() The variable has 1 row and 15 columns. when I print list1, I get the answer below: (It is indeed a list, but a list that contains only one element. It means when I call list1[0], I get the same result.): [[array(['A'], dtype='&lt;U13'), array(['B'], dtype='&lt;U14'), array(['C'], dtype='&lt;U6'), array(['D'], dtype='&lt;U4'), array(['E'], dtype='&lt;U10'), array(['F'], dtype='&lt;U13'), array(['G'], dtype='&lt;U11'), array(['H'], dtype='&lt;U9'), array(['I'], dtype='&lt;U16'), array(['J'], dtype='&lt;U18'), array(['K'], dtype='&lt;U16'), array(['L'], dtype='&lt;U16'), array(['M'], dtype='&lt;U16'), array(['N'], dtype='&lt;U14'), array(['O'], dtype='&lt;U13')]] While the form that I expect is: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'] Does anyone know what the problem is?
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/83140572
favorite count: 0
accepted answer: http://stackoverflow.com/a/48081315
has title: How to convert a numpy.ndarray type into a list?

http://stackoverflow.com/comment/83321516
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48170753
has text: Hi Ignacio, I'm trying to sort y accoding to the order of (the second axis) of x.

http://stackoverflow.com/a/70769459
score: 0
has body: This is a general way how the video can be resized to 480 x 800 (height x width) and made to loop. import cv2 # Change this path to your video location path = "path_to_your_video" cap = cv2.VideoCapture(path) while True: ret, img = cap.read() if not ret: cap = cv2.VideoCapture(path) ret, img = cap.read() img = cv2.resize(img, (800, 480)) cv2.imshow("Video", img) if cv2.waitKey(1) & 0xFF == ord("q"): break cap.release() cv2.destroyAllWindows()
answers question: http://stackoverflow.com/q/48040138
type: Answer

http://stackoverflow.com/q/48143870
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48143978
tagged with: dictionary
score: 1
answer count: 3
has answer: http://stackoverflow.com/a/48143922
upvote count: 1
tagged with: list
possible better answer: http://stackoverflow.com/a/48143915
accepted answer: http://stackoverflow.com/a/48143922
has answer: http://stackoverflow.com/a/48143915
tagged with: http://stackoverflow.com/tag/json
tagged with: mysql
type: AnsweredQuestion
downvote count: 0
has body: I'm new to Python and I'm having trouble with a very specific problem. I need to read data from various JSON files that have a similar structure. The procedure is: load the JSON file into a dictionary, save the relevant data from the dict in a list in order to insert it into a MySQL database. The problem is: some fields of the JSON files don't necessarily appear in EVERY JSON file. Some fields are missing in some of the files, and sometimes even inside the same file, as in: "actions": [ { "acted_at": "2014-12-10", "action_code": "Intro-H", "references": [], "text": "Introduced in House", "type": "action" }, { "acted_at": "2014-12-10", "action_code": "H11100", "committees": [ "HSWM" ], "references": [], "status": "REFERRED", "text": "Referred to the House Committee on Ways and Means.", "type": "referral" }, { "acted_at": "2014-12-12", "action_code": "B00100", "references": [ { "reference": "CR E1800-1801", "type": null } ], "text": "Sponsor introductory remarks on measure.", "type": "action" } ] Here is a code snippet to illustrate what the relevant (to the question) part of my program does: hr_list = [] with open("data.json") as json_data: d = json.load(json_data) actions_list.append(( d["actions"][j]["acted_at"], d["actions"][j]["action_code"], d["actions"][j]["status"], d["actions"][j]["text"], d["actions"][j]["type"])) As you can see, there is some consistency to the file. The problem is: whenever one of the fields is not present, I receive a KeyError stating that there is no such data to append to the list. What I need to do is a way to handle this exception, like add some type of "null" data as default, so it doesn't return any errors (what would be null anyway when added to the database).
has title: How to handle exceptions while appending a list in python with data read from a dict that stores data read from a .json file?

http://stackoverflow.com/comment/83310137
has text: INFO - Starting new HTTPS connection (1): api.airtime.geemedia.com, which am really not interested in, how do i disable it
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48165133

http://stackoverflow.com/q/48107235
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83190179
tagged with: if-statement
has comment: http://stackoverflow.com/comment/83190026
score: -1
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/83190121
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/83190565
upvote count: 0
has comment: http://stackoverflow.com/comment/83190113
has comment: http://stackoverflow.com/comment/83190177
possible better answer: http://stackoverflow.com/a/48107304
favorite count: 0
has answer: http://stackoverflow.com/a/48107304
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83190098
has answer: http://stackoverflow.com/a/48107301
has body: i have a list contains some values.I want to check if any of the element is presented in another list with if statement. I have done something like if condition with list comprehension this but not working as expected. my code is fileop=["create","open","append","delete","move","copy"] a=raw_input("enter a command\n") tokens=a.split(" ") def data(i): return i if [data(i) in tokens for i in fileop] in tokens: print "file operations" if "create" in tokens: print "create" elif "open" in tokens: print "open" elif "delete" in tokens: print "delete" If my input is like delete file.how to get the correct keyword.
tagged with: python
has title: if condition with list comprehension in python
accepted answer: http://stackoverflow.com/a/48107301
has comment: http://stackoverflow.com/comment/83190111

http://stackoverflow.com/comment/83240629
comment on: http://stackoverflow.com/q/48131710
score: 1
has text: I've never looked into Alexa before, but Isn't that (storing persistent data) what the [session object](https://developer.amazon.com/docs/custom-skills/request-and-response-json-reference.html#session-object) is for?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48127974
has body: &gt;&gt;&gt; hex(int('3f4800003f480000', 16)) '0x3f4800003f480000'
answers question: http://stackoverflow.com/q/48127757
upvote count: 1
score: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/48133010
has title: str object is not callable error python
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83243266
has body: I've been trying to run the following code in Python: def likes(names): dictionary_of_sizes = { 0:"no one likes this", 1:(lambda names: "{} likes this".format(names[0])), 2:(lambda names: "{} and {} like this".format(names[0], names[1])), 3:(lambda names: "{}, {} and {} like this".format(name[0], names[1],names[2])), 4:(lambda names: "{}, {} and {} others like this".format(names[0], names[1], len(names)-2)) } return dictionary_of_sizes[len(names)](names) if len(names)&lt;4 else dictionary_of_sizes[4] I always get the error 'str' object is not callable. Question: What am I doing wrong?
upvote count: 0
has comment: http://stackoverflow.com/comment/83243247
has comment: http://stackoverflow.com/comment/83243227
score: -1
has answer: http://stackoverflow.com/a/48133066
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/48133065
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83025840
type: QuestionComment
has text: I have updated my question
score: 0
comment on: http://stackoverflow.com/q/48027855
type: Comment

http://stackoverflow.com/q/48036468
has answer: http://stackoverflow.com/a/48037514
has comment: http://stackoverflow.com/comment/83043698
score: 0
has comment: http://stackoverflow.com/comment/83045278
has comment: http://stackoverflow.com/comment/83043175
has comment: http://stackoverflow.com/comment/83043554
tagged with: layout
has title: Python resturant management system how to add inventory reciept
accepted answer: http://stackoverflow.com/a/48037514
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83043902
type: Question
has comment: http://stackoverflow.com/comment/83043616
tagged with: python
has comment: http://stackoverflow.com/comment/83043461
has comment: http://stackoverflow.com/comment/83044092
answer count: 1
has body: The code given below is intended to calculate the bill of items entered by the cashier in the entry widget order_raw, to do so i have placed sum=0 before defining a function and then made the increment to the sum, but still my program doesn't calculate the total bill.It keeps giving me zero.Currently there is no error in my code. from tkinter import * order=[] window=Tk() order_raw=Entry(window) order_raw.pack() global bill bill=0 def totalbill(): global bill global billvar order.append(order_raw.get()) if order_raw.get()=="burger": bill=bill+200 if order_raw.get()=="fries": bill=bill+200 print(bill) billvar=StringVar(value=bill) checkout=Button(window, text="total", command=totalbill) checkout.pack() total=Entry(window, textvariable=billvar) total.pack() window.mainloop() then i shifted the StringVar inside to the function where the vriable sum is modified.But then it gives my an error, below is the code and its error. from tkinter import * order=[] window=Tk() order_raw=Entry(window) order_raw.pack() global bill bill=0 def totalbill(): global bill global billvar order.append(order_raw.get()) if order_raw.get()=="burger": bill=bill+200 if order_raw.get()=="fries": bill=bill+200 print(bill) billvar=StringVar(value=bill) checkout=Button(window, text="total", command=totalbill) checkout.pack() total=Entry(window, textvariable=billvar) total.pack() window.mainloop() error "Traceback (most recent call last): File "C:/Users/umerk/.PyCharmCE2017.2/config/scratches/scratch_7.py", line 20, in &lt;module&gt; total=Entry(window, textvariable=billvar) NameError: name 'billvar' is not defined

neo4django
tags question: http://stackoverflow.com/q/48120696
type: Tag
tag name: neo4django

http://stackoverflow.com/comment/83141061
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48083226
has text: you can use `str.startswith`, e.g. `allVariants.Downstream.str.startswith('G')`
score: 1

http://stackoverflow.com/q/48170086
has body: I am trying to run some code written by someone else, which contains the line from bokeh.charts import Bar When I run this in the Anaconda Prompt, I get the message "No module named 'bokeh.charts'". I have installed bokeh 0.12.13, so the problem isn't that I haven't installed it. Indeed, other bokeh modules run fine. I have noticed on the bokeh website that the 'charts' module says that it refers to a previous version (see https://docs.bokeh.org/en/0.12.4/docs/reference/charts.html). Does the latest version not have bokeh.charts? If so, is there an alternative?
tagged with: charts
type: AnsweredQuestion
has title: What to use instead of bokeh.charts
score: 17
tagged with: bokeh
type: Question
has comment: http://stackoverflow.com/comment/83319859
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48171833
accepted answer: http://stackoverflow.com/a/48171833
upvote count: 17

http://stackoverflow.com/comment/97478871
type: AnswerComment
has text: I just installed airflow 1.10.2 and RBAC feature is working when I tested basic DAG operations. But I am not so sure how to make use of `filter_by_owner` feature.Only with that feature we can go ahead with a real multi tenant Airflow setup.This is something related to above discussed issues.That's why I just commented here .
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48075387

http://stackoverflow.com/comment/83115458
score: 0
type: Comment
type: QuestionComment
has text: `song_table.find` just returns a cursor object, why do you think it can be iterated?
comment on: http://stackoverflow.com/q/48070863

http://stackoverflow.com/comment/83122525
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48074233
has text: click on the checkbox in the page
score: 0

http://stackoverflow.com/q/48151024
favorite count: 0
has title: Parsing SAS datetime to pandas dataframe
has comment: http://stackoverflow.com/comment/83281245
has comment: http://stackoverflow.com/comment/83280814
has body: I'm loading a CSV that was produced with SAS into a pandas DataFrame. In order to parse the SAS times I created a parser function like this: def parse_date(d): try: date = dt.timedelta(seconds=int(d)) + dt.datetime(1960, 1, 1) return date except ValueError: print("There was a problem parsing.") Now, when I pass this function a SAS datetime, like the first value in one of my date columns, it gives me exactly the output that I want: parse_date(1652745600) Out[9]: datetime.datetime(2012, 5, 16, 0, 0) However, when I pass the function as date_parser to pd.read_csv(), I get value errors, like so: def get_ods_reader(): ods_reader = pd.read_csv("mycsv.csv", chunksize=200000, parse_dates=[6, 9, 10, 16], dtype={"account_nbr": object, "REPOSSESSION_STATUS_CD": object}, converters={"repossession_ind": parse_int}, date_parser=parse_date) return ods_reader # Getting the data types of all columns chunk_dtypes = [] for chunk in get_ods_reader(): print(chunk.head(5)) chunk_dtypes.append(chunk.dtypes) Out[10]: There was a problem parsing. There was a problem parsing. There was a problem parsing. There was a problem parsing. There was a problem parsing. There was a problem parsing. There was a problem parsing. ...
tagged with: datetime
has comment: http://stackoverflow.com/comment/83281149
tagged with: python
type: AnsweredQuestion
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48151552
score: 1
has answer: http://stackoverflow.com/a/48151552
tagged with: sas
tagged with: pandas
downvote count: 0
answer count: 1

http://stackoverflow.com/a/48024246
type: Answer
answers question: http://stackoverflow.com/q/48023356
has body: You can try something like this: first collect sum and tuple in a list: connectionsList = [('C', 'B'), ('A', 'C'), ('D', 'B'), ('C','D')] valuesDict = {'A':3, 'B':5, 'C':1, 'D':2} tuple_sum=[] for i in connectionsList: tuple_sum.append((valuesDict.get(i[0])+valuesDict.get(i[1]),i)) it will give: [(6, ('C', 'B')), (4, ('A', 'C')), (7, ('D', 'B')), (3, ('C', 'D'))] Now sort it and take only nested tuple : print(list(map(lambda x:x[1],sorted(tuple_sum)))) output: [('C', 'D'), ('A', 'C'), ('C', 'B'), ('D', 'B')]
score: 0

import
type: Tag
tag name: import
tags question: http://stackoverflow.com/q/48098020
tags question: http://stackoverflow.com/q/48023771
tags question: http://stackoverflow.com/q/48147323
tags question: http://stackoverflow.com/q/48023717
tags question: http://stackoverflow.com/q/48088763
tags question: http://stackoverflow.com/q/48046431
tags question: http://stackoverflow.com/q/48126858
tags question: http://stackoverflow.com/q/48119332
tags question: http://stackoverflow.com/q/48093653
tags question: http://stackoverflow.com/q/48097707
tags question: http://stackoverflow.com/q/48065982
tags question: http://stackoverflow.com/q/48133102
tags question: http://stackoverflow.com/q/48024407
tags question: http://stackoverflow.com/q/48066306
tags question: http://stackoverflow.com/q/48051810
tags question: http://stackoverflow.com/q/48159908
tags question: http://stackoverflow.com/q/48169983
tags question: http://stackoverflow.com/q/48132991
tags question: http://stackoverflow.com/q/48054670
tags question: http://stackoverflow.com/q/48109590
tags question: http://stackoverflow.com/q/48111790

http://stackoverflow.com/comment/83152624
score: 0
type: QuestionComment
type: Comment
has text: may be you need to wait till the full DOM loading. add some delay and try again.
comment on: http://stackoverflow.com/q/48088916

http://stackoverflow.com/q/48121895
has answer: http://stackoverflow.com/a/48122801
linked to: http://stackoverflow.com/q/46291253
tagged with: neural-network
has answer: http://stackoverflow.com/a/48126837
upvote count: 2
has answer: http://stackoverflow.com/a/48584578
has body: I'm trying to implement a 5 layer deep convolutional neural network in Tensorflow with 3 convolutional layers followed by 2 fully connected layers. My current implementation is below. def deepnn(x): x_image = tf.reshape(x, [-1, FLAGS.img_width, FLAGS.img_height, FLAGS.img_channels]) img_summary = tf.summary.image('Input_images', x_image) with tf.variable_scope('Conv_1'): W_conv1 = weight_variable([5, 5, FLAGS.img_channels, 32]) tf.add_to_collection('decay_weights',W_conv1) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1,2) + b_conv1) h_pool1 = avg_pool_3x3(h_conv1) with tf.variable_scope('Conv_2'): W_conv2 = weight_variable([5, 5, 32, 32]) tf.add_to_collection('decay_weights',W_conv2) b_conv2 = bias_variable([32]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2,2) + b_conv2) h_pool2 = avg_pool_3x3(h_conv2) with tf.variable_scope('Conv_3'): W_conv3 = weight_variable([5, 5, 32, 64]) tf.add_to_collection('decay_weights',W_conv3) b_conv3 = bias_variable([64]) h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3,2) + b_conv3) h_pool3 = max_pool_3x3(h_conv3) with tf.variable_scope('FC_1'): h_pool3_flat = tf.reshape(h_pool3,[-1,4*4*64]) W_fc1 = weight_variable([4*4*64,64]) tf.add_to_collection('decay_weights',W_fc1) b_fc1 = bias_variable([64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat,W_fc1) + b_fc1) with tf.variable_scope('FC_2'): W_fc2 = weight_variable([64, FLAGS.num_classes]) tf.add_to_collection('decay_weights',W_fc2) b_fc2 = bias_variable([FLAGS.num_classes]) y_fc2 = tf.matmul(h_fc1, W_fc2) + b_fc2 with tf.variable_scope('softmax'): y_conv = tf.nn.softmax(y_fc2) return y_conv, img_summary def conv2d(x, W,p): output = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='VALID', name='convolution') return tf.pad(output, tf.constant([[0,0],[p, p,],[p, p],[0,0]]), "CONSTANT") def avg_pool_3x3(x): output = tf.nn.avg_pool(x, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='VALID', name='pooling') return tf.pad(output, tf.constant([[0,0],[0, 1,],[0, 1],[0,0]]…
favorite count: 0
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48585105
has title: Poor accuracy in Tensorflow CNN implementation
tagged with: python
has answer: http://stackoverflow.com/a/64262988
score: 2
tagged with: conv-neural-network
downvote count: 0
tagged with: machine-learning
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/83254356
type: Comment
has text: I see. I was just irritated, because the tank actually contains roughly 4000 litres of water, thus requiring just as much seconds to empty. I'd like to know, where this discrepancy in magnitude comes from. But anyway, thanks for clearing this up!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48129591

http://stackoverflow.com/a/48037403
has comment: http://stackoverflow.com/comment/83046265
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/83046396
has comment: http://stackoverflow.com/comment/83047010
has comment: http://stackoverflow.com/comment/83053605
type: Answer
answers question: http://stackoverflow.com/q/48037284
score: 4
has body: Your text editor has not saved the file as UTF-8, so Python can't read the file. You have 3 options: Change the first line to use the correct codec. It probably is Windows Codepage 1252, given that you are using Windows and the é character is encoded as 0xE1 in that codec: # -*- coding: cp1252 -*- Use a text editor that lets you specify the encoding to be used when saving, like Notepad++ or Sublime Text or Visual Studio, and make sure the file is actually saved as UTF-8. Use only ASCII codepoints in the file; the u'Montréal' value can also be specified using an \xhh or \uhhhh escape sequence for the é character: u'Montr\u00e9al'
has comment: http://stackoverflow.com/comment/83047020
has comment: http://stackoverflow.com/comment/83053665

http://stackoverflow.com/q/48055817
type: AnsweredQuestion
type: Question
tagged with: opencv
linked to: http://stackoverflow.com/q/21150914
has answer: http://stackoverflow.com/a/48082832
accepted answer: http://stackoverflow.com/a/48082832
score: 0
has body: I am trying to simply play a video in gtk environment using opencv code in python. In order to achieve it I made a glade file that contains a toplevel window, a file menu, a drawing area and a file chooser dialog. When user select a file, code starts a thread that calls function VideoPlayerDA that starts reading video and after every frame it generates a queue_draw signal to display frame in drawing area. The problem however is that after few frames the whole UI freezes and becomes unresponsive, video gets stuck. Tools: I am using Gtk version 3.22.11, python 3.5.3, OpenCV version 3.3.0 on debian stretch. PS: cv2.waitkey also seems to be not working. import cv2 import time import threading import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject, Gdk, GdkPixbuf GObject.threads_init() mymutex = threading.Lock() dimg = GdkPixbuf.Pixbuf.new_from_file('test.jpg') def VideoPlayerDA(filename,drawing_area): global dimg,dimg_available cap = cv2.VideoCapture(filename) while(cap.isOpened()): mymutex.acquire() ret, img = cap.read() if img is not None: boxAllocation = drawing_area.get_allocation() img = cv2.resize(img, (boxAllocation.width,\ boxAllocation.height)) img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) # opencv by default load BGR colorspace. Gtk supports RGB hance the conversion dimg = GdkPixbuf.Pixbuf.new_from_data(img.tostring(), GdkPixbuf.Colorspace.RGB,False,8, img.shape[1], img.shape[0], img.shape[2]*img.shape[1],None,None) #time.sleep(0.03) drawing_area.queue_draw() mymutex.release() time.sleep(0.03) #if ((cv2.waitKey(30) &amp; 0xFF) == ord('q')): # break else: mymutex.release() break print('end of file') class video_player_gui: def on_main_window_destroy(self,object): Gtk.main_quit() def on_open_activate(self,widget): response = self.file_chooser.run() if response == 0: self.filename = self.file_chooser.get_filename() thread = threading.Thread(target = VideoPlayerDA, args=(self.filename, self.drawing_area,)) thread.daemon = True thread.start()…
answer count: 1
has comment: http://stackoverflow.com/comment/83088245
has comment: http://stackoverflow.com/comment/83088651
has title: Video player in gtk using opencv gets stuck
tagged with: python
tagged with: gtk

wsgi
type: Tag
tags question: http://stackoverflow.com/q/48153448
tag name: wsgi

http://stackoverflow.com/a/48040022
answers question: http://stackoverflow.com/q/48039983
type: Answer
score: 0
has body: Try this and see if it works. All I did was take one of your lines inside the for loop. for i in range(len(generated)): j = Image.fromarray(generated[i]) j.save('/home/jovyan/GROUP_SHARED/Kimi.Zhang/imagetest_' + str(i) +'.jpg')
has comment: http://stackoverflow.com/comment/83050735

http://stackoverflow.com/comment/131577268
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48063210
has text: Yeah I was pulling my hair out trying to solve this issue. Thanks :)

http://stackoverflow.com/comment/83052867
has text: Run `db.execute('SET CONSTRAINTS ALL DEFERRED')` before your bulk operation in order to defer all deferrable constraints in the current transaction: https://www.postgresql.org/docs/current/static/sql-set-constraints.html. You could opt to defer the unique constraint only, if you know its name.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48038807
score: 1

http://stackoverflow.com/q/48027065
has comment: http://stackoverflow.com/comment/83026251
has comment: http://stackoverflow.com/comment/83025666
answer count: 1
has comment: http://stackoverflow.com/comment/83027244
favorite count: 0
has answer: http://stackoverflow.com/a/48028821
accepted answer: http://stackoverflow.com/a/48028821
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/83026202
downvote count: 0
tagged with: pivot
has comment: http://stackoverflow.com/comment/83025885
has comment: http://stackoverflow.com/comment/83026531
has comment: http://stackoverflow.com/comment/83026834
type: Question
has title: Pandas :: Values of one column as columns
has body: The data looks like this: origin_id type serialn event year month day 1 A 101 X1 2017 6 10 1 A 101 X2 2017 6 10 1 B 101 X3 2017 6 10 2 A 151 X1 2016 7 15 2 B 151 X3 2016 7 15 2 C 151 X4 2016 7 15 And I need it to be this way: origin_id serialn X1 X2 X3 X4 year month day 1 101 A A B null 2017 6 10 2 151 A null B C 2016 7 15 So basically what I need is to use the values of the column event as headers and put the value of the column type for each event, when there is no event for a certain origin_id put a null. Some other columns from the dataframe, like serialn and origin_id should be in the resulting one. Also there should be only one row for each origin_id This question: How to pivot a dataframe touches on some points, altough it's geared towards performing an aggregation at some point. This is a possible solution. I get a df with the origin_id as the index, the events as columns and the types as their value. stat = df.pivot(values='type', index='origin_id', columns='event') Now I need some information from the original dataframe, so I only keep one event for each origin_id and drop the columns I'm not gonna use df1 = df.drop_duplicates(subset='origin_id').drop(['type','event'], axis=1) Merging the both dataframes, df1 using the values of origin_id and stat using the index. pd.merge(df1, stat, how='inner', left_on = 'origin_id', right_index = True) Using the first dataframe with the code above I get this result: origin_id serialn X1 X2 X3 X4 year month day 1 101 A A B null 2017 6 10 2 151 A null B C 2016 7 15 Is there another way to do this? Thanks!
upvote count: 2
linked to: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/83025608
has comment: http://stackoverflow.com/comment/83026016
tagged with: pandas

http://stackoverflow.com/comment/83185399
type: Comment
comment on: http://stackoverflow.com/a/48100769
score: 0
has text: Ive removed that part and it doesnt make a difference?
type: AnswerComment

http://stackoverflow.com/a/75228842
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48163641
has body: place this on the top of the "asgi.py" file (there are conflicts between jwt auth, because it is accessing the user model before get_asgi_application function): django_asgi_app = get_asgi_application()

http://stackoverflow.com/a/48090575
score: 1
accepted answer of: http://stackoverflow.com/q/48090239
type: Answer
answers question: http://stackoverflow.com/q/48090239
upvote count: 1
has body: The bokeh command was introduced in version 0.11, it did not exist in version 0.10. The reason running bokeh works at all in the situation you describe is because you have both the old and new environments in your execution PATH, and it is being picked up from the new one (the only one it exists in). Prior to version 0.11 there was a bokeh-server command. However I must state unequivocally that that this old, first generation version of the Bokeh server (which was never truly functional) is now 100% deprecated and completely unsupported. It should not be used by anyone for any reason in new code. I would likewise say that use of Bokeh version 0.10 at all is also to be highly discouraged, as it is ancient at this point.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48124763
has comment: http://stackoverflow.com/comment/83226425
answer count: 0
type: UnansweredQuestion
has body: I am creating a bash script, for Mac OS, to run several python scripts in sequence. Right now I am just trying to get the bash script to run one python script and have been unsuccessful. #!/bin/bash python3 /Users/johndoe/Documents/Projects/Test.py I made the bash file executable with chmod 700, and gave the gatekeeper permission to run it. Here is what it says when I run the script: MacBook:~ JohnDoe$ /Users/JohnDoe/Documents/Projects/Bscript ; exit; Traceback (most recent call last): File "/Users/JohnDoe/Documents/Projects/Test.py", line 19, in &lt;module&gt; with open('Data/' + filename + '.json', 'w') as outfile: FileNotFoundError: [Errno 2] No such file or directory: 'Data/20180105-234709.json' logout Saving session... ...copying shared history... ...saving history...truncating history files... ...completed. [Process completed] This python script works just as intended when running from the terminal manually, but the Bash script gives me an error about the with open line. Does anyone have an idea whats going on? It appears that it is failing to create a new file... but why is that causing it to fail if that is the case? For background the Test.py is pulling Json data from internet and saving it to a new file it creates. Thank you.
has comment: http://stackoverflow.com/comment/83226408
type: Question
has comment: http://stackoverflow.com/comment/83226569
has title: Python script functions correctly except when I try to call it from a bash script
score: 0
tagged with: bash
has comment: http://stackoverflow.com/comment/83226407
has comment: http://stackoverflow.com/comment/83232708
tagged with: python

http://stackoverflow.com/a/48105983
answers question: http://stackoverflow.com/q/48105436
type: Answer
score: 0
has body: It seems you have forgotten to indent the code inside your functions. You should also add a if __name__ == '__main__' line so that you can run your code like a script: python test.py Try the following code: test.py def game_intro(): print "------------------ First Hero ------------------" global n1 n1 = raw_input("Please Type a Name for Your Hero: ") while not valid_name(n1): print "------------------ First Hero ------------------" n1 = raw_input("Please Type a Name for Your Hero: ") print "------------------ Second Hero ------------------" global n2 n2 = raw_input("Please Type a Name for Your Hero: ") while not valid_name(n2): print "------------------ Second Hero ------------------" n2 = raw_input("Please Type a Name for Your Hero: ") while not no_repeat(n2): n2 = raw_input("Please Type a Name for Your Hero: ") def valid_name(n): if n == " ": # TO AVOID THE PLAYER GIVING A NAME AS SPACE print "Your name can't be empty" return False elif n == "": return False return True def no_repeat(m): # TO MAKE SURE THE PLAYERS WON'T TAKE THE SAME NAME if m == n1: print m + " Already Assigned, Please Type a Different Name." return False return True if __name__ == '__main__': game_intro()

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/48160974
tags question: http://stackoverflow.com/q/48028871
tags question: http://stackoverflow.com/q/48052799
tags question: http://stackoverflow.com/q/48055209

http://stackoverflow.com/a/71678533
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48109650
has body: Alternatively, You can create your two masks and combine them into one mask like this; finalmask = mask_red | mask_blue It is the same as using bitwise_or. And you can pipe many masks like this; maskf = maskA | maskB | maskC

http://stackoverflow.com/comment/83074831
comment on: http://stackoverflow.com/q/48051368
type: Comment
type: QuestionComment
score: 1
has text: Try this selector `iframe[id$='_content_ifr']`, incase of DWT54 is randomly generated everytime. Put wait for the element visibility, too.

http://stackoverflow.com/comment/83180493
type: QuestionComment
comment on: http://stackoverflow.com/q/48102138
has text: Really, it would be easier if you provided a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Also see [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). It's tough to understand how you can progress from the Excel SS - is it a single DF? In which case, you could just simply sort the data.
score: 0
type: Comment

http://stackoverflow.com/comment/83032644
has text: page uses JavaScript to add elements but BeautifulSoup can't run JavaScipt so you can't find this element. You can use `Selenium` to control browser which will load page and run JavaScript. Or you can check in DevTool (Network->XHR) if JavaScript reads this data from different url, and then you can try to read from this url too. JavaScript mostly gets data as JSON which you can easily convert it to python dictionary using module `json`. See https://feeds.nfl.com/feeds-rs/scores.json
type: QuestionComment
comment on: http://stackoverflow.com/q/48030398
type: Comment
score: 3

http://stackoverflow.com/comment/83256684
has text: maybe storing all columns in a list and iterate over it?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48139549
score: 1

http://stackoverflow.com/a/48096486
downvote count: 0
type: Answer
has body: You can import the permission model with from django.contrib.auth.models import Permission However, if you want to create custom permissions, the documented approach is to add permissions to a model. Django will then create the permissions when you run manage.py migrate. class MyModel(models.Model): ... class Meta: permissions = ( ("can_do_something", "Can do something"), )
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48096327

http://stackoverflow.com/q/48049757
has answer: http://stackoverflow.com/a/48049863
has title: NoReverseMatch at /<url> When rendering form
has body: I am relatively new to Django and I am trying to insert data into a table using a Django form, but I am stuck at this error: NoReverseMatch at /vinesF/NewVid Reverse for 'NewVid' not found. 'NewVid' is not a valid view function or pattern name. Here is my view: def NewVid(request): if request.POST: form = AddVidForm(request.POST) if form.is_valid(): primaryName = form.cleaned_data['primaryName'] Origin = form.cleaned_data['Origin'] PreferredAudience = form.cleaned_data['PreferredAudience'] Date = form.cleaned_data['Date'] Link = form.cleaned_data['Link'] VPath = form.cleaned_data['VPath'] AddPath = form.cleaned_data['AddPath'] FreshVid = video(primaryName=primaryName, Origin=Origin, PreferredAudience=PreferredAudience, Date=Date,Link=Link, VPath=VPath, AddPath=AddPath) FreshVid.save() return HttpResponse("New Video added") else: return render(request,'vine/Newvid.html', {form:'form'}) else: form = AddVidForm() return render(request,'vine/Newvid.html', {form:'form'}) HTML template code: &lt;form method="post" action="{% url 'NewVid' %}" &gt; {% csrf_token %} &lt;!-- This line inserts a CSRF token. --&gt; &lt;table&gt; {{ form.as_table }} &lt;!-- This line displays lines of the form. --&gt; &lt;/table&gt; &lt;p&gt;&lt;input type="submit" value="Create" /&gt;&lt;/p&gt; &lt;/form&gt; {% endblock %} URL handler: app_name = 'vinesF' urlpatterns = [ url(r'^NewVid$',views.NewVid, name='NewVid'), ] Any help is appreciated.
type: UnansweredQuestion
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/83074462
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48050079
linked to: http://stackoverflow.com/q/48051118
has answer: http://stackoverflow.com/a/48063202
tagged with: python

http://stackoverflow.com/comment/83321117
score: 3
type: Comment
type: QuestionComment
has text: Can you at least come up with a better title? Your current one tells us nothing about your actual question.
comment on: http://stackoverflow.com/q/48170829

http://stackoverflow.com/q/48057841
upvote count: 4
tagged with: deep-learning
answer count: 1
tagged with: neural-network
downvote count: 0
tagged with: caffe
favorite count: 0
tagged with: python
has body: How to write an asyncronous data layer to preload batches while other processing is performed? Are there some example codes? Thanks
score: 4
type: UnansweredQuestion
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48065550
type: Question
has title: How to write a caffe python data layer with preload?

http://stackoverflow.com/comment/83254964
type: QuestionComment
score: 3
has text: I'd like to see 3 lines of your CSV file, and also how you're loading your data into the dataframe. You need to fix the _code_ that _loads_ the data.
comment on: http://stackoverflow.com/q/48138757
type: Comment

http://stackoverflow.com/comment/83253677
comment on: http://stackoverflow.com/a/48136236
type: AnswerComment
score: 0
has text: It not working pax80. You cannot assign "subprocess.check_call('netsh advfirewall show allprofiles state')" to result just that easily. I already try this. But, thanks for helps
type: Comment

http://stackoverflow.com/q/48035634
downvote count: 1
type: Question
tagged with: recursion
has comment: http://stackoverflow.com/comment/83041441
tagged with: fibonacci
accepted answer: http://stackoverflow.com/a/48035673
has body: I am trying to solve this problem Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, … By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. Link: https://projecteuler.net/problem=2 Below is the code I have to calculate a fibonacci number: # fibonacci series def fib(x): if x==0 or x==1: return 1 else: return fib(x-1) + fib(x-2) def test_fib(n): for i in range (n+1): print 'fib of', i, ' = ' , fib(i) test_fib(41) However, the program hangs after 40th term. What is the problem with this code and how to solve this problem for 40th and beyond terms?
has comment: http://stackoverflow.com/comment/83041354
has answer: http://stackoverflow.com/a/48037480
linked to: http://stackoverflow.com/q/15047116
has answer: http://stackoverflow.com/a/48035766
score: 1
possible better answer: http://stackoverflow.com/a/48037480
favorite count: 0
has comment: http://stackoverflow.com/comment/83041312
has answer: http://stackoverflow.com/a/48035750
has comment: http://stackoverflow.com/comment/83041280
has answer: http://stackoverflow.com/a/48035673
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/83041562
type: AnsweredQuestion
has title: fibonacci program hangs after 40th term
upvote count: 2

torsocks
tags question: http://stackoverflow.com/q/48104071
tag name: torsocks
type: Tag

http://stackoverflow.com/comment/93597463
score: 0
type: Comment
has text: For some reason if you want to install the rewrite version use this python3 -m pip install -U https://github.com/Rapptz/discord.py/archive/rewrite.zip
comment on: http://stackoverflow.com/a/48118965
type: AnswerComment

http://stackoverflow.com/comment/83243705
type: Comment
has text: @COLDSPEED df.shape (390, 414), v.shape (390,390)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48133141

http://stackoverflow.com/a/48070266
type: AcceptedAnswer
has body: Using &gt; opens the target file for write, same as if opened via fopen with mode "w". That immediately truncates the file, before your program even launches (it happens while the shell is configuring the environment before execing your program). You can't use this approach to read from a file and replace it as a single step. Best you could do would be something like: ./myrev infile &gt; infile.tmp &amp;&amp; mv -f infile.tmp infile where, if the command succeeds, you complete the work by replacing the original file with the contents of the new file.
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48070247
has comment: http://stackoverflow.com/comment/83115422
answers question: http://stackoverflow.com/q/48070247

http://stackoverflow.com/comment/83436833
comment on: http://stackoverflow.com/q/48090648
has text: Did you try to use [error handlers](http://flask.pocoo.org/docs/0.12/patterns/errorpages/#error-handlers)?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83217211
type: Comment
type: QuestionComment
has text: @roganjosh: it was Safari, I copied from FireFox and it is fine.
comment on: http://stackoverflow.com/q/48120181
score: 0

http://stackoverflow.com/comment/83183291
score: 0
comment on: http://stackoverflow.com/a/48036774
type: AnswerComment
type: Comment
has text: If you don't call [`clock.tick`](http://www.pygame.org/docs/ref/time.html#pygame.time.Clock.tick) the game will run with the maximum frame rate that your computer can achieve, so it should usually be called once per frame. Since it also returns the delta time, we can just use it instead of calculating it ourselves. BTW, if you multiply the velocity by the `dt` then you have a "variable time step" and that's not good for online multiplayer games (I think it's okay for single player games). Here's an interesting link: http://gameprogrammingpatterns.com/game-loop.html

http://stackoverflow.com/q/48019198
tagged with: google-apis-explorer
upvote count: 1
tagged with: pipe
type: Question
answer count: 1
downvote count: 0
score: 1
has title: BrokenPipeError when using Gmail API
tagged with: gmail-api
tagged with: python
has comment: http://stackoverflow.com/comment/85020613
favorite count: 0
has body: I'm using Gmail API to send an email with attachments in Python 3. I'm trying the same code as google developers as shown below: https://developers.google.com/gmail/api/guides/sending The problem is that when attachments are 4.2KB or 2.6MB, the code works Well; but when attachments are 3.0MB or 9.6MB or bigger, an Error occurs: Traceback (most recent call last): File "quickstart2.py", line 184, in &lt;module&gt; main() File "quickstart2.py", line 170, in main send_message(service, "me", message) File "quickstart2.py", line 147, in send_message message = (service.users().messages().send(userId=user_id, body=message).execute()) File "/home/yizhu/anaconda3/lib/python3.6/site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper return wrapped(*args, **kwargs) File "/home/yizhu/anaconda3/lib/python3.6/site-packages/googleapiclient/http.py", line 837, in execute method=str(self.method), body=self.body, headers=self.headers) File "/home/yizhu/anaconda3/lib/python3.6/site-packages/googleapiclient/http.py", line 176, in _retry_request raise exception File "/home/yizhu/anaconda3/lib/python3.6/site-packages/googleapiclient/http.py", line 163, in _retry_request resp, content = http.request(uri, method, *args, **kwargs) File "/home/yizhu/anaconda3/lib/python3.6/site-packages/oauth2client/transport.py", line 175, in new_request redirections, connection_type) File "/home/yizhu/anaconda3/lib/python3.6/site-packages/oauth2client/transport.py", line 282, in request connection_type=connection_type) File "/home/yizhu/anaconda3/lib/python3.6/site-packages/httplib2/__init__.py", line 1322, in request (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) File "/home/yizhu/anaconda3/lib/python3.6/site-packages/httplib2/__init__.py", line 1072, in _request (response, content) = self._conn_request(conn, request_uri, method, body, headers) File "/home/yizhu/anaconda3/lib/python3.6/site-packages/httplib2/__init__.py…
has answer: http://stackoverflow.com/a/48021331
type: UnansweredQuestion

http://stackoverflow.com/comment/83241799
comment on: http://stackoverflow.com/q/48132275
score: 0
type: QuestionComment
type: Comment
has text: It seems you are mixing up `__getattr__` and `__getattribute__` here.

http://stackoverflow.com/comment/83073669
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48050954
score: 1
has text: `add_numbers` also shouldn't have a `self` argument.

http://stackoverflow.com/a/48067151
score: 1
has body: df['Date'] = pd.to_datetime(df.Date) first convert the Date column to datetime type if needed df = df.reset_index().sort_values(by=['Date', 'index']).drop(['index'], axis=1) This will reset the index, creating a temporary column called index. Then sort using both the Date &amp; index columns, and finally drop the index column. leaving the data frame sorted by Date and the order in which they appeared in the original CSV file.
accepted answer of: http://stackoverflow.com/q/48066933
answers question: http://stackoverflow.com/q/48066933
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/q/48081717
has body: Here is my code: def option_A(): print("Pick a Fixture!") fixture_choice = int(input("Enter: ")) file = open("firesideFixtures.txt", "r") fixture_number = file.readlines(fixture_choice) fixture = [linecache.getline("firesideFixtures.txt", fixture_choice)] print(fixture) file.close() The first line from the file I am using is: 1,02/09/15,18:00,RNGesus,Ingsoc,Y,Ingsoc The expected result is: 1, 02/09/15, RNGesus, Ingsoc, Y, Ingsoc The result I get: ['1,02/09/15,18:00,RNGesus,Ingsoc,Y,Ingsoc\n'] How can I do this?
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48081817
answer count: 1
downvote count: 0
favorite count: 0
has title: How do I print certain parts of a list?
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/48081817

http://stackoverflow.com/comment/83097579
has text: show your `urls.py`.
comment on: http://stackoverflow.com/q/48062504
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/83037028
comment on: http://stackoverflow.com/q/48033347
type: Comment
type: QuestionComment
has text: All relevant info needs to go into the question itself, not in comments. Besides, comments don't preserve indentation, so they're virtually useless for multi-line Python code.
score: 2

http://stackoverflow.com/a/48107183
has body: It might be possible for you to abuse a defaultdict: from collections import defaultdict c = [8, 9, 10] dict1 = defaultdict(c.pop, {1: 2, 3: 4, 5: 6}) b = 7 e = dict1[b] This will pop an item from c and make it a value of dict1 whenever a key missing from dict1 is accessed. (That means the expression dict1[b] on its own has side-effects.) There are many situations where that behaviour is more confusing than helpful, though, in which case you can opt for explicitness: if b in dict1: e = dict1[b] else: e = dict1[b] = c.pop() which can of course be wrapped up in a function: def get_or_pop(mapping, key, source): if key in mapping: v = mapping[key] else: v = mapping[key] = source.pop() return v ⋮ e = get_or_pop(dict1, b, c)
score: 3
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48107144
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/48107144
has comment: http://stackoverflow.com/comment/83190127

http://stackoverflow.com/a/48061872
answers question: http://stackoverflow.com/q/48061843
type: Answer
has body: Unpack your tuple. &gt;&gt;&gt; t = ('a', 'b') &gt;&gt;&gt; '{!s}={!r}'.format(*t) "a='b'"
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48061843

http://stackoverflow.com/q/48070668
duplicate of: http://stackoverflow.com/q/47982894
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83115434
tagged with: arrays
has comment: http://stackoverflow.com/comment/83115652
has comment: http://stackoverflow.com/comment/83115060
has comment: http://stackoverflow.com/comment/83115317
has comment: http://stackoverflow.com/comment/83115157
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/47982894
has body: Suppose I have 2-dimensional numpy array e.g.: arr = np.arange(15).reshape(5,3) array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]) I would like to efficiently slice different columns for different rows. For example, I want to have 0:2 for the 0th row, 1:3 for the 1st row, 0:2 for the 2nd row, 1:3 for the 3rd row and 1:3 for the 4th row. I can do this inefficiently with a loop as: min_index = (0,1,0,1,1) max_index = (2,3,2,3,3) newarr = [] count = 0 for min_,max_ in zip(min_index,max_index): newarr.append(arr[count,min_:max_]) count += 1 np.array(newarr) array([[ 0, 1], [ 4, 5], [ 6, 7], [10, 11], [13, 14]]) This works but it is not efficient. Is there way to efficiently do this slicing? I tried arr[range(5),(0,1,0,1,0):(1,2,1,2,1)] but this did not work.
has title: python numpy slicing columns with different slice index for different rows
answer count: 0
score: 0

http://stackoverflow.com/comment/83286176
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48130047
type: AnswerComment
has text: Maybe you have to override the `nlp = spacy.load('en'); nlp.lemmatizer` and `nlp.tagger`?

http://stackoverflow.com/comment/83025636
score: 0
type: Comment
has text: yeah, but it doesn't even show the naan's just doesn't show anything at all
comment on: http://stackoverflow.com/a/48027798
type: AnswerComment

http://stackoverflow.com/q/48143955
tagged with: python
has title: Error running python program from Teminal but it runs fine in Pycharm
has comment: http://stackoverflow.com/comment/83266239
has comment: http://stackoverflow.com/comment/83266121
has comment: http://stackoverflow.com/comment/83266116
score: 0
has comment: http://stackoverflow.com/comment/83266302
type: Question
has comment: http://stackoverflow.com/comment/83266854
has comment: http://stackoverflow.com/comment/83266128
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83266087
answer count: 1
has comment: http://stackoverflow.com/comment/83266146
has answer: http://stackoverflow.com/a/48157170
has comment: http://stackoverflow.com/comment/83266104
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83266073
has body: I am using python2.7 in Pycharm and program runs fine when started from Pycharm the output from Pycharm is I am running the same program form terminal it shows error as shown below After some discussions, I did the following I changed the project interpreter in python to which python2 path as shown below Then running program from Pycharm works but running it from terminal still have the same issue
has comment: http://stackoverflow.com/comment/83289459
has comment: http://stackoverflow.com/comment/83266076

http://stackoverflow.com/q/48053527
type: Question
has comment: http://stackoverflow.com/comment/83080104
tagged with: if-statement
has comment: http://stackoverflow.com/comment/83079358
has comment: http://stackoverflow.com/comment/83079664
has comment: http://stackoverflow.com/comment/83079630
downvote count: 0
favorite count: 0
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Lambda Calculus function to return TRUE/FALSE without "if"
tagged with: lambda-calculus
score: 1
has comment: http://stackoverflow.com/comment/83080039
has body: I'm a new comer to Lambda Calculus &amp; trying to understand its workings via Python code. In Lambda calculus, TRUE, FALSE &amp; IFELSE conditional can be represented as: (I'm using L to stand for Lambda symbol) TRUE = Lx.Ly.x FALSE = Lx.Ly.y IFELSE = Lc.Lx.Ly.((c x) y) Using the above definitions, the following hold true: (I'm writing the function applications in Python style below) TRUE(e1)(e2) = e1 FALSE(e1)(e2) = e2 IFELSE(TRUE)(e1)(e2) = e1 IFELSE(FALSE)(e1)(e2) = e2 My attempt at creating an Lambda Calculus-style ABS function is coded below in Python. ABS applies the return value from GTZ (Greater-than-zero) repeatedly to compute abs(x). The GTZ function uses an if statement. And since Lambda calculus doesn't have an if statement (AFAIK), how can this be implemented in Lambda calculus? The online lambda calculus materials I reviewed all mention that IFELSE can be coded as function application; but none of them mention how the conditional input to IFELSE itself can be generated without an "if" statement or equivalent. Please help me understand how this can be written in Lambda calculus. Thanks! def TRUE(x): def f(y): return x return f def FALSE(x): def s(y): return y return s def GTZ(x): return TRUE if x &gt; 0 else FALSE def ABS(x): return GTZ(x)(x)(-x)
has comment: http://stackoverflow.com/comment/83079333

http://stackoverflow.com/comment/83087811
score: 2
comment on: http://stackoverflow.com/q/48057732
type: Comment
type: QuestionComment
has text: The table with `id=ctl00_mainContent_DataList1` is only displayed after a search is performed. It doesn't exist when the page loads for the first time.

azure
tags question: http://stackoverflow.com/q/48096390
tags question: http://stackoverflow.com/q/48109297
tags question: http://stackoverflow.com/q/48112639
tags question: http://stackoverflow.com/q/48018835
tags question: http://stackoverflow.com/q/48072056
tags question: http://stackoverflow.com/q/48064451
tags question: http://stackoverflow.com/q/48134928
tags question: http://stackoverflow.com/q/48078937
type: Tag
tags question: http://stackoverflow.com/q/48017874
tag name: azure
tags question: http://stackoverflow.com/q/48128075

http://stackoverflow.com/a/48154043
type: Answer
answers question: http://stackoverflow.com/q/48153907
upvote count: 4
downvote count: 0
score: 4
has body: The standard way of checking whether a string contains a character, in Python, is using the in operator. In your case, that would be: for i in content: if "@" in i: print(i) The find method, as you where using, returns the position where the @ character is located, starting at 0, as described in the Python official documentation. For instance, in the string abc@google.com, it will return 3. In case the character is not located, it will return -1. The equivalent code would be: for i in content: if i.find("@") != -1: print(i) However, this is considered unpythonic and the in operator usage is preferred.

http://stackoverflow.com/q/48024917
linked to: http://stackoverflow.com/q/9475241
possible better answer: http://stackoverflow.com/a/48025100
accepted answer: http://stackoverflow.com/a/48025093
tagged with: loops
has answer: http://stackoverflow.com/a/48025100
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48025052
has comment: http://stackoverflow.com/comment/83019202
score: -1
tagged with: mac-address
upvote count: 0
has answer: http://stackoverflow.com/a/48025150
has title: split string every nth character and append ':'
has answer: http://stackoverflow.com/a/48025093
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/48025292
has comment: http://stackoverflow.com/comment/83019217
tagged with: python
type: AnsweredQuestion
has body: I've read some switch MAC address table into a file and for some reason the MAC address if formatted as such: 'aabb.eeff.hhii' This is not what a MAC address should be, it should follow: 'aa:bb:cc:dd:ee:ff' I've had a look at the top rated suggestions while writing this and found an answer that may fit my needs but it doesn't work satomacoto's answer The MACs are in a list, so when I run for loop I can see them all as such: Current Output ['8424.aa21.4er9','fa2'] ['94f1.3002.c43a','fa1'] I just want to append ':' at every 2nd nth character, I can just remove the '.' with a simple replace so don't worry about that Desired output ['84:24:aa:21:4e:r9','fa2'] ['94:f1:30:02:c4:3a','fa1'] My code info = [] newinfo = [] file = open('switchoutput') newfile = file.read().split('switch') macaddtable = newfile[3].split('\\r') for x in macaddtable: if '\\n' in x: x = x.replace('\\n', '') if carriage in x: x = x.replace(carriage, '') if '_#' in x: x = x.replace('_#', '') x.split('/r') info.append(x) for x in info: if "Dynamic" in x: x = x.replace('Dynamic', '') if 'SVL' in x: x = x.replace('SVL', '') newinfo.append(x.split(' ')) for x in newinfo: for x in x[:1]: if '.' in x: x = x.replace('.', '') print(x)
has comment: http://stackoverflow.com/comment/83019368

http://stackoverflow.com/comment/83160906
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48088137
has text: Possible duplicate of [Using openpyxl to refresh pivot tables in Excle](https://stackoverflow.com/questions/48016206/using-openpyxl-to-refresh-pivot-tables-in-excle)
score: 0

http://stackoverflow.com/comment/83210772
score: 1
type: Comment
type: QuestionComment
has text: Can you post a screenshot of the image you get, and an example of how you would like it to look?
comment on: http://stackoverflow.com/q/48117247

http://stackoverflow.com/comment/83119759
type: Comment
has text: @user2864740 `Tomáš Linhart`'s answer worked for me
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48072862

http://stackoverflow.com/comment/83537715
comment on: http://stackoverflow.com/a/48157199
type: AnswerComment
has text: If you are not statisfied with my answer you can try to post on Cross Validated, but I'm certain you will receive something similar.
score: 0
type: Comment

recaptcha
tag name: recaptcha
tags question: http://stackoverflow.com/q/48034871
type: Tag

http://stackoverflow.com/q/48046350
tagged with: regex
has comment: http://stackoverflow.com/comment/83064070
type: AnsweredQuestion
upvote count: 0
has body: I'm a newbie and learning more about regular expressions. I'm still unclear as to why we use groups. I used them in the below regular expression below: (http:)\//(\w)+\.(\w)+\.(\w)+ This will extract URL's, as in the below sentence: This is http://www.google.com, this is http://www.yahoo.com. I did use groups but I was very unsure as to why. I saw this explanation online but confused as to what it means: By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. So any simplified clarification of groups would be great.
type: Question
score: -2
has comment: http://stackoverflow.com/comment/83064288
has answer: http://stackoverflow.com/a/48046993
accepted answer: http://stackoverflow.com/a/48046993
downvote count: 2
has comment: http://stackoverflow.com/comment/83064129
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: When to use Groups in Regular Expressions?
tagged with: python

http://stackoverflow.com/comment/83193976
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48056131
has text: `point_id = canvas.create_oval()` gives ID for every point which you have to keep on list and use with `move(point_id, ...)`

http://stackoverflow.com/comment/83159560
comment on: http://stackoverflow.com/q/48092184
score: 0
type: Comment
type: QuestionComment
has text: Given that, as far as I understand it, requests parses the response lazily, I'd guess it's related to the connection. But I've given you a tool to investigate this; have a look and find out.

http://stackoverflow.com/q/48066606
linked to: http://stackoverflow.com/q/337664
tagged with: python
has title: Finding the subsequence that starts and ends with the same number with the maximum sum
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83120552
has comment: http://stackoverflow.com/comment/83109392
type: Question
has comment: http://stackoverflow.com/comment/83109014
tagged with: performance
accepted answer: http://stackoverflow.com/a/48067326
tagged with: algorithm
score: -1
has comment: http://stackoverflow.com/comment/83106678
has comment: http://stackoverflow.com/comment/83106818
upvote count: 2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/83108658
downvote count: 3
has answer: http://stackoverflow.com/a/48067326
has comment: http://stackoverflow.com/comment/83106568
answer count: 1
favorite count: 0
has body: I have to make a program that takes as input a list of numbers and returns the sum of the subsequence that starts and ends with the same number which has the maximum sum (including the equal numbers in the beginning and end of the subsequence in the sum). It also has to return the placement of the start and end of the subsequence, that is, their index+1. The problem is that my current code runs smoothly only while the length of list is not that long. When the list length extends to 5000 the program does not give an answer. The input is the following: 6 3 2 4 3 5 6 The first line is for the length of the list. The second line is the list itself, with list items separated by space. The output will be 12, 1, 4, because as you can see there is 1 equal pair of numbers (3): the first and fourth element, so the sum of elements between them is 3 + 2 + 4 + 3 = 12, and their placement is first and fourth. Here is my code. length = int(input()) mass = raw_input().split() for i in range(length): mass[i]=int(mass[i]) value=-10000000000 b = 1 e = 1 for i in range(len(mass)): if mass[i:].count(mass[i])!=1: for j in range(i,len(mass)): if mass[j]==mass[i]: f = mass[i:j+1] if sum(f)&gt;value: value = sum(f) b = i+1 e = j+1 else: if mass[i]&gt;value: value = mass[i] b = i+1 e = i+1 print value print b,e

http://stackoverflow.com/q/48117803
tagged with: python
has body: I always heard that python was a language that was friendly to monkey patching... well now i need to monkey patch and know not what to do. I specifically need to disable the 'raising' of a parsing exception to see if a iso parsing library behaves. It's not so simple, because i'm using libmirage (which is a cdemu a cd emulator underlying library, to treat the first track of any kind of mode2 form 1 or mixed like a iso so that the iso parser library pycdlib can read it. This works almost perfectly except... some of the psx cds in the redump collection i'm testing this out raise a exception during the parsing in pycdlib because of various parsing errors: PyCdlibInvalidISO: data in 3rd unused field not zero \ ValueError: year is out of range \ PyCdlibInvalidISO: File structure version expected to be 1 etc. What i'm really looking for is to disable the raising of exceptions during parsing, since the information i'm looking for has nothing much to do with iso validation - basically the serial inside of a single txt file - and those isos are vetted by redump anyway. Is there any way to do this without importing and editing the library myself?
upvote count: 0
downvote count: 3
has comment: http://stackoverflow.com/comment/83223683
type: Question
has comment: http://stackoverflow.com/comment/83215330
has title: Hack python code
tagged with: monkeypatching
has comment: http://stackoverflow.com/comment/83212004
answer count: 1
has answer: http://stackoverflow.com/a/48124091
favorite count: 0
tagged with: exception
type: UnansweredQuestion
score: -3

http://stackoverflow.com/comment/83185150
score: 0
comment on: http://stackoverflow.com/q/48104143
type: QuestionComment
has text: There is no documentation about this "hidden implementation" method. It's supposed to be called whenever you want to call noeMat43.inverse(). Like in example above.
type: Comment

http://stackoverflow.com/q/48144925
possible better answer: http://stackoverflow.com/a/68327235
type: Question
answer count: 3
has answer: http://stackoverflow.com/a/72822445
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48146210
accepted answer: http://stackoverflow.com/a/48146210
tagged with: python
has answer: http://stackoverflow.com/a/68327235
has title: how to search other field in many2one?
upvote count: 2
score: 2
type: AnsweredQuestion
tagged with: odoo
has body: python code: _name = 'res.partner.table2' customer_id = fields.Many2one('res.partner', required=True ,string="Customer ID") XML: //how can i search by res.partner customer_id in here I need search by other field instead "name". How is it possible?
tagged with: odoo-8

http://stackoverflow.com/comment/129359515
type: Comment
score: 2
comment on: http://stackoverflow.com/a/59686678
type: AnswerComment
has text: It's always best to first consider the documentation :) That really helps. Thanks for the answer.

http://stackoverflow.com/comment/83143911
type: Comment
type: QuestionComment
has text: Use CookieAuthentication instead? The hashed password is a one-way hash so there's no way to "get" the hashed password without knowing it or breaking it.
comment on: http://stackoverflow.com/q/48054399
score: 0

http://stackoverflow.com/a/48291398
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48033044
type: Answer
answers question: http://stackoverflow.com/q/48033044
downvote count: 0
score: 1
has body: Take a look at https://github.com/Microsoft/CNTK/blob/master/Tutorials/CNTK_205_Artistic_Style_Transfer.ipynb You can create a learn-able input variable by specifiying need_gradient=True in its parameters. Thanks, Emad

http://stackoverflow.com/comment/83218230
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48120762
has text: It works with solve( ) but not solveset( ). Is there a reason for this?

http://stackoverflow.com/q/48101278
possible better answer: http://stackoverflow.com/a/48101547
score: 2
type: AnsweredQuestion
tagged with: list
upvote count: 2
has answer: http://stackoverflow.com/a/48101561
accepted answer: http://stackoverflow.com/a/48101522
type: Question
has answer: http://stackoverflow.com/a/48103885
has answer: http://stackoverflow.com/a/48101443
has comment: http://stackoverflow.com/comment/83177949
downvote count: 0
answer count: 7
has comment: http://stackoverflow.com/comment/83177808
has title: Python - Use a list containing keys to make a dictionary out of a string
favorite count: 0
has answer: http://stackoverflow.com/a/48101522
has answer: http://stackoverflow.com/a/48101547
has body: With something like this: keys = ["Name:", "Date:", "Time:sec:", "Room"] string = "Name:BobDate:1/3Time:sec:3:00:00RoomA1" How can I get a dictionary like: dict1 = {"Name" : "Bob", "Date" : "1/3", "Time:sec" : "3:00:00", "Room" : "A1"} Removing the colon is optional. I am able to remove keys from the string entirely using re.split(), .join(), and map() but I want to create a dictionary instead.
tagged with: python
has answer: http://stackoverflow.com/a/48101495
has answer: http://stackoverflow.com/a/48101839
tagged with: dictionary

http://stackoverflow.com/comment/83233247
type: QuestionComment
comment on: http://stackoverflow.com/q/48128025
type: Comment
has text: Does windows send a broadcast when the user try to use the drag n' drop system? EDIT: Is possible to get it via sys?
score: 0

http://stackoverflow.com/comment/85604477
type: QuestionComment
has text: not sure if useful, but I've found that this only happens on my Development server (Mac OS) and not on my production (Ubuntu with Apache and modWSGI). Furthermore, the error has got so bad that it means I cannot use my development server without having 'developer tools' open in the browser, I think it's got something to do with the fact that having this open clears the cache upon every request.
comment on: http://stackoverflow.com/q/48152535
score: 0
type: Comment

http://stackoverflow.com/comment/83261860
comment on: http://stackoverflow.com/a/48141900
score: 0
type: AnswerComment
has text: @heemayl I understand what you're saying. But this regex should be flexible enough as per OP's requirements.
type: Comment

http://stackoverflow.com/q/48142074
possible better answer: http://stackoverflow.com/a/48142158
downvote count: 2
has answer: http://stackoverflow.com/a/48142158
type: Question
has comment: http://stackoverflow.com/comment/83268850
has answer: http://stackoverflow.com/a/48142109
has body: I have list of dictionaries like below: A=[ {key1 : val11, key2 : val21, key3 : val31, key5 : val51, key6 : val61}, {key2 : val22, key3 : val32, key5 : val52, key6 : val62}, {key1 : val13, key2 : val23, key4 : val43, key5 : val53}, {key1 : val14, key3 : val34, key4 : val44, key5 : val54, key6 : val64}, {key4 : val45, key5 : val55, key6 : val65} ] As you see the length of the dictionaries are not the same and also the key : value in each dictionary are not necessarily similar. I was wondering how to sum the values assigned for each key in all dictionaries: For instance for key4: (val43 + val44 + val45) or for key3: (val31 + val32 + val34).
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83262195
accepted answer: http://stackoverflow.com/a/48142109
has title: How to sum the values assigned to a key in a list of dictionaries?
favorite count: 0
upvote count: 2
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/q/48123819
tagged with: http://stackoverflow.com/tag/csv
has body: I'm creating an application to essentially act as an asset database and I'm trying to open a CSV file, read the values and update them accordingly. I see many tutorials on how to read and write to CSV files, but I can't find one that details how to iterate over a CSV file and update individual values. Ideally it seems to be easier to use Dictionaries as opposed to lists so I can search by keyword (Part Names). It works for the most part, but I'm having issues writing the updated list to the CSV file. I'm getting the following error: "line 155, in writewrow return self.writer.writerow(self._dict_to_list(rowdict)) ValueError: I/O operation on closed file def write(part_name, part_num="null"): with open("Database.csv", "r") as file_read: fieldnames=["Part_Name", "Part_Num"] csv_reader = csv.DictReader(file_read, fieldnames=fieldnames) temp_list = [] # Create temp copy of the csv file for line in csv_reader: # Reading the CSV file and storing it in temp_list temp_list.append(line) for line in temp_list: # Printing the original list to verify contents were read correctly print (line) for line in temp_list: # Reading each element in the list and updating the value if different from the value passed into the function if (line["Part_Name"] == part_name and line["Part_Num"] != part_num): line["Part_Num"] = part_num for line in temp_list: # Printing out the new vesion of the temp_list to verify updates took print (line) with open("Database.csv", "w") as file_write: csv_writer = csv.DictWriter(file_write, fieldnames=fieldnames) for line in temp_list: # Attempting to write the updated temp_list to the csv file csv_writer.writerow(line)
has comment: http://stackoverflow.com/comment/83224795
tagged with: python
has comment: http://stackoverflow.com/comment/83224941
has comment: http://stackoverflow.com/comment/83225168
type: UnansweredQuestion
downvote count: 2
tagged with: file
tagged with: output
has answer: http://stackoverflow.com/a/48193716
type: Question
has comment: http://stackoverflow.com/comment/83224634
has title: Reading, Updating, and Writing updated CSV file in Python 3
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/83224870
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/83144735
type: QuestionComment
score: 0
has text: Have you considered that maybe your dataset is just huge? You've got 65524 columns and 130 rows. That's 8518120 items. If every item was a single bit large, then your dataset would be just over a mb large... Factor in overhead and the fact that your data is bigger than one bit, and you've got a significant memory hog.
comment on: http://stackoverflow.com/q/48084798
type: Comment

http://stackoverflow.com/comment/83243589
comment on: http://stackoverflow.com/q/48133160
score: 1
has text: Which line gives you the error? Do try to reduce your problem to a [mcve], and post the full traceback.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48122906
tagged with: mysql
tagged with: django
has body: I am not trying to check the db name to the connection, I have multiple database setup in django and also used the database route to create a failover but I am wondering if I can get the name of the connection host or the name given to the settings... for example DATABASES = { 'default': { # trying to get this name 'default' 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'euser', 'PASSWORD': 'password', 'HOST': 'host', # trying to get this host name 'host' 'PORT': 3306, }, 'node2': { # trying to get this name 'node2' 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'euser', 'PASSWORD': 'password', 'HOST': 'host2', # trying to get this host name 'host2' 'PORT': 3306, }, } Is it possible to get those names I commented out above? For my failover, I am trying to send an email if another db is being used, but it would be great if I can get especially the host so it would be easier on me P.S. off topic, is it possible to change the name default to other names? I tried changing it and I would get errors. Seems like I must have at least one database setting name called default Thanks in advance for any help.
has comment: http://stackoverflow.com/comment/83223369
accepted answer: http://stackoverflow.com/a/48123243
has comment: http://stackoverflow.com/comment/83222982
type: AnsweredQuestion
tagged with: database
score: 4
has comment: http://stackoverflow.com/comment/83223057
linked to: http://stackoverflow.com/q/10101602
has comment: http://stackoverflow.com/comment/83223019
type: Question
has comment: http://stackoverflow.com/comment/83222681
upvote count: 4
has comment: http://stackoverflow.com/comment/83223208
has title: able to check db connection host or name (not db name but the setting) ? django
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48123243
tagged with: python
tagged with: settings
has comment: http://stackoverflow.com/comment/83223032

http://stackoverflow.com/q/48093038
linked to: http://stackoverflow.com/q/17695456
tagged with: python
downvote count: 1
type: AnsweredQuestion
tagged with: list
duplicate of: http://stackoverflow.com/q/17695456
type: Question
has answer: http://stackoverflow.com/a/48093081
answer count: 1
score: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48093081
has body: I use a tool to reformat my code from Python2 to Python3. One of the things that it always does is replacing my_dict.items() by list(my_dict.items()) What is the motivation behind that? I assume that items() do not guaranty the ordering (it is stochastic, since dictionary is not ordered). So, by using list we order the key, value pairs. Is my assumption correct?
has title: Why does Python2 to Python3 converter put "items()" into "list"?
tagged with: items
upvote count: 2

http://stackoverflow.com/comment/83038819
comment on: http://stackoverflow.com/q/48034035
type: QuestionComment
score: 1
has text: Interesting question. Do you know ALL the values a particular column could contain in advance?
type: Comment

http://stackoverflow.com/comment/83234645
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48128586
has text: Thanks for all your comments! I have done a quick edit, to show how I push the values into the list (self.begin attribute). So I was indeed primarily confused about the fact that by setting self.end to self.begin, I am basically setting both of the them to the same node. And that all operations I perform in the else statement on self.end, extend everything what is happing on self.begin (e.g. self.begin.next.next etc., however, that is not happening for self.end (probably because of the replacement of that attribute with the node at that moment).. I will look into your resources. Thanks all!
score: 0

http://stackoverflow.com/q/48118216
has comment: http://stackoverflow.com/comment/83213730
has comment: http://stackoverflow.com/comment/83212969
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83213220
has comment: http://stackoverflow.com/comment/83212907
tagged with: python
answer count: 0
has title: python best practice of dealing with huge number of objects
has comment: http://stackoverflow.com/comment/83213157
has body: I am building a code in python which collecting huge number of objects and have a statistics periodically of those objects every object has a timestamp which represnet when it collected , i need to have in memory only the last 30 seconds objects and delete the rest (30 seconds as example) so the normal psudocode will be like this thread loop while True for elem in list if now - elem.timestamp &gt; 30 list.remove(elem) sleep(30) what is the best practice of doing such things edit : the app is acting as a receiver of object that comming from streaming server the load is very high may reach billion/hour and the app accepting every object from the server i will simplify the object with two members (timestamp and value) the server should have the min, max , avg, etc of all objects which their timestamp is not more than 30 seconds old and remove the rest from memory
type: Question
has comment: http://stackoverflow.com/comment/83213650
score: 0
has comment: http://stackoverflow.com/comment/83213420
has comment: http://stackoverflow.com/comment/83213018

http://stackoverflow.com/a/48122034
score: 2
downvote count: 0
has body: You are prematurely disposing of the DHT22 sensor variable and the PiGPIO daemon. You should not clean up the resources until the program is exiting. Change the end of your program as follows: def on_closing(): print('Cleaning up resources.') s.cancel() pi.stop() master.destroy() master.protocol("WM_DELETE_WINDOW", on_closing) loop() master.mainloop() Additionally the sleep(.03) method should be moved to the line directly after the s.trigger() method. I'm referring to the trigger in the readDHT22() function. The trigger at the top of your code is superfluous and should be removed. The delay after the trigger is only necessary on faster Pi's to ensure the trigger completes prior to reading the temperature and humidity.
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48071393
type: Answer
accepted answer of: http://stackoverflow.com/q/48071393

http://stackoverflow.com/comment/126933987
type: Comment
comment on: http://stackoverflow.com/a/71746420
type: AnswerComment
score: 2
has text: Converting between PySpark and Pandas creates inefficiently on the master node, as all the data needs to be collected from the different worker nodes. So for this problem the solution work but not scalable.

http://stackoverflow.com/q/48099546
has comment: http://stackoverflow.com/comment/83210734
has title: How to change Function by without Changing its Parameters
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83210296
has comment: http://stackoverflow.com/comment/83206124
tagged with: odeint
tagged with: python
upvote count: 3
has comment: http://stackoverflow.com/comment/83210420
has body: I am new to python and in learning stages. I wanted to implement Particle Swarm Optimization(PSO) algorithm which I did by taking help from on-line materials and python tutorials. In PSO, a simple calculus problem is inferred i-e 100 * ((y - (x2))2) + ((1 - (x2))2). This problem is defined in a fitness function. def fitness(x, y): return 100 * ((y - (x**2))**2) + ((1 - (x**2))**2) Now, I want to replace this simple calculus problem by simple first order Ordinary Differential Equation(ODE) by without changing existing function parameters (x,y) and want to return the value of dy_dx,y0 and t for further process. # Define a function which calculates the derivative def dy_dx(y, x): return x - y t = np.linspace(0,5,100) y0 = 1.0 # the initial condition ys = odeint(dy_dx, y0, t)` In python odeint function is used for ODE which requires three essential parameters i-e func/model, y0( Initial condition on y (can be a vector) and t(A sequence of time points for which to solve for y) Example of odeint parameters. I don't want to change its parameters because it will be difficult for me to make changes in algorithm. For simplicity I pasted the full code below and my question is open to anyone if wants to modify the code with further parameters in General Best, Personal Best and r[i]. import numpy as np from scipy.integrate import odeint import random as rand from scipy.integrate import odeint from numpy import array import matplotlib.pyplot as plt def main(): #Variables n = 40 num_variables = 2 a = np.empty((num_variables, n)) v = np.empty((num_variables, n)) Pbest = np.empty((num_variables, n)) Gbest = np.empty((1, 2)) r = np.empty((n)) for i in range(0, num_variables): for j in range(0, n): Pbest[i][j] = rand.randint(-20, 20) a[i][j] = Pbest[i][j] v[i][j] = 0 for i in range(0, n): r[i] = fitness(a[0][i], a[1][i]) #Sort elements of Pbest Order(Pbest, r, n) Gbest[0][0] = Pbest[0][0] Gbest[0][1] = Pbest[1][0] generation = 0 plt.ion() fig = plt.figure() ax = fig.add_subplot(111) a…
tagged with: scipy
tagged with: numpy
has comment: http://stackoverflow.com/comment/83209181
has comment: http://stackoverflow.com/comment/83210258
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83209283
favorite count: 0
type: Question
score: 3

http://stackoverflow.com/comment/83237318
comment on: http://stackoverflow.com/q/48130218
has text: You could just rename your `price` column in `df2` to `BBprice`, and drop the `name` column in `df2`.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/83295794
type: Comment
type: QuestionComment
has text: sounds like you need resample or asfreq
comment on: http://stackoverflow.com/q/48158167
score: 0

http://stackoverflow.com/comment/83261389
score: 4
comment on: http://stackoverflow.com/q/48141731
type: QuestionComment
type: Comment
has text: rename everything back to make your life even easier (:

http://stackoverflow.com/comment/83220814
has text: @Charlesduffy what branch are you referring to?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48121643

http://stackoverflow.com/comment/83326192
type: QuestionComment
score: 1
has text: It's not a limitation of Django, but this is how HTTP actually works. As a workaround, you can create a separate form specifically for files. So when the user chooses a file, you can automatically submit that form using JavaScript so that the file starts uploading in the background and meanwhile the user can fill out the *other* form. But, it's too much of a headache, really, and in my opinion, not worth it.
comment on: http://stackoverflow.com/q/48172808
type: Comment

http://stackoverflow.com/q/48061864
has body: Wrt to the code snippet below, why is super().__init__ used in the model? How does it work? model.py class DuckForm(forms.ModelForm): class Meta: model = Duck fields = ('description', 'name') def __init__(self, community, *args, **kwargs): super().__init__(*args, **kwargs) self.community = community def save(self, commit=True): duck = super().save(commit=False) if not duck.community_id: duck.community = self.community if commit: duck.save() return duck views.py def add_duck(request): if request.method == 'POST': form = DuckForm(request.animal.community, data=request.POST) if form.is_valid(): duck = form.save() return redirect('DuckData') else: form = DuckForm(request.user.community) return TemplateResponse(request, 'MyDuck.html', {'form': form})
type: Question
has answer: http://stackoverflow.com/a/48061969
has title: super function in Python
score: 0
accepted answer: http://stackoverflow.com/a/48061969
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83096276
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83096252
upvote count: 3
downvote count: 3
has comment: http://stackoverflow.com/comment/83096206

http://stackoverflow.com/comment/83021222
score: 0
type: Comment
has text: I used these three lines as an example that express my idea about an outcome. The problem is how to use a specific statement to plug it into the classifier to get the outcome. The model based on the movie_review data is the trained model. The data from my questionnaire are new and unseen data. As they are organized in totally different way as the data in movie_review, I am asking how to make both compatible with each other.
type: QuestionComment
comment on: http://stackoverflow.com/q/48025614

http://stackoverflow.com/q/48036069
has comment: http://stackoverflow.com/comment/83042815
downvote count: 0
has comment: http://stackoverflow.com/comment/83043032
favorite count: 0
has comment: http://stackoverflow.com/comment/83042737
upvote count: 2
has comment: http://stackoverflow.com/comment/83043029
has comment: http://stackoverflow.com/comment/83043066
has comment: http://stackoverflow.com/comment/83044228
tagged with: python
possible better answer: http://stackoverflow.com/a/48041891
tagged with: qt
score: 2
type: AnsweredQuestion
has title: How to subclass QSqlTableModel in pyqt5?
has answer: http://stackoverflow.com/a/48041891
has comment: http://stackoverflow.com/comment/83043109
has answer: http://stackoverflow.com/a/48036765
has comment: http://stackoverflow.com/comment/83043135
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/83042950
has comment: http://stackoverflow.com/comment/83042603
type: Question
has comment: http://stackoverflow.com/comment/83042422
answer count: 2
has comment: http://stackoverflow.com/comment/83042222
has body: After hanging around with some posts with C++ answers which don't fit to my question and which are more confusing than explaining I try to ask here. I'm trying to subclass QSqlTableModel because I need some boolean columns with checkboxes. The complete working program is: from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtSql import * import sys class ImportFilter (QDialog): def __init__(self): super().__init__() self.initUI() def initUI(self): print("Welcome to StandardDialog") # Load the Window #self.ui = uic.loadUi("ImportFilter.ui",self) #self.ui.setModal(True) self.buttonBox = QDialogButtonBox() self.tableView_typeOfValues = QTableView() layout = QVBoxLayout() layout.addWidget(self.buttonBox) layout.addWidget(self.tableView_typeOfValues) self.setLayout(layout) # Init Environmment self.db = createConnection() # create Models self.setupModel() #setup Views self.setupView() # connect Signals self.buttonBox.clicked.connect(self.pushButton_Box_clicked) self.show() print("&lt;- initUI") def setupView(self): print("-&gt; setupView") self.tableView_typeOfValues.setModel(self.tableView_typeOfValues_Model) self.tableView_typeOfValues.setColumnWidth(0,10) self.tableView_typeOfValues.setColumnWidth(1,130) self.tableView_typeOfValues.setColumnWidth(2,130) self.tableView_typeOfValues.setColumnWidth(3,60) self.tableView_typeOfValues.setColumnWidth(4,60) self.tableView_typeOfValues.setColumnWidth(5,60) self.tableView_typeOfValues.setColumnWidth(6,60) self.tableView_typeOfValues.hideColumn(0) self.tableView_typeOfValues.hideColumn(3) print("&lt;- setupView") def setupModel(self): print("-&gt; setupModel") # own model self.tableView_typeOfValues_Model = ImportSqlTableModel() print(" tables:", self.db.tables()) print(' Before .setTable("typeOfValue") and select()') self.tableView_typeOfValues_Model.info() self.tableView_typeOfValues_Model.setTable("typeOfValue") self.tableView_typeOfValues_Model.setEditStrategy(QSqlTableModel.OnFieldCh…
has comment: http://stackoverflow.com/comment/83042392
has comment: http://stackoverflow.com/comment/83043085
has comment: http://stackoverflow.com/comment/83042551
accepted answer: http://stackoverflow.com/a/48036765
has comment: http://stackoverflow.com/comment/83042575
tagged with: pyqt

http://stackoverflow.com/a/48061935
has body: What about ', '.join(['{!s}={!r}'.format(item[0], item[1]) for item in list]) ?
type: Answer
score: 1
answers question: http://stackoverflow.com/q/48061843
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/83138778
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48077955
has text: Oh it worked! Thank you so much! I didn't know there was an update function

http://stackoverflow.com/comment/83153997
type: Comment
type: QuestionComment
has text: `df.query("index > 1")`? Or are you referring to the columns? Sorry, what's your expected output?
comment on: http://stackoverflow.com/q/48089786
score: 0

http://stackoverflow.com/q/48032648
has answer: http://stackoverflow.com/a/48036137
accepted answer: http://stackoverflow.com/a/48036137
answer count: 1
tagged with: distributed-system
tagged with: pyzmq
upvote count: 1
tagged with: sockets
tagged with: python
favorite count: 0
downvote count: 0
has body: Where A in theory 'acts' like a server, where D and E are both a subscriber and a publisher and F is a subscriber. An example would be highly appreciated, if it indeed is feasible. If not, please provide an alternative. Websockets are not an option in my goal.
has title: Can the following model be achieved in ZeroMQ?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/46615141
tagged with: zeromq
score: 1
type: Question

http://stackoverflow.com/q/48061510
has comment: http://stackoverflow.com/comment/83096319
has comment: http://stackoverflow.com/comment/83096026
has title: How to SELECT a field from a LEFT JOIN'ed table/model with Django's ORM (1.11)
score: 0
tagged with: sql
answer count: 1
has comment: http://stackoverflow.com/comment/83096008
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/48062355
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48062355
tagged with: orm
has body: Context: Using Django Rest Framework, I've created a ModelViewSet. With these models: class Claim(models.Model): permalink = models.SlugField(max_length=255, blank=True, unique=True) author = models.ForeignKey(get_user_model(), db_index=True, on_delete=models.SET_NULL, null=True, blank=True) deleted = models.BooleanField(db_index=True, default=False) collaborators = models.ManyToManyField(get_user_model(), through='ClaimCollaborator', through_fields=('claim', 'user'), related_name='claims') # ...other fields class ClaimCollaborator(models.Model): claim = models.ForeignKey(Claim, db_index=True, on_delete=models.CASCADE) user = models.ForeignKey(get_user_model(), db_index=True, on_delete=models.CASCADE) access_project_only = models.BooleanField(default=True) I'm trying to query Claim to LEFT JOIN ClaimCollaborator and bring back the access_project_only field. ClaimCollaborator is actually an intermediary model handling the ManyToMany relationship between claims and users (collaborators of the claim). So far I have the following view (cut down for brevity): class ClaimViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated, ) serializer_class = serializers.ClaimSerializer lookup_field = 'permalink' def get_queryset(self): return models.Claim.objects.filter(Q(author=self.request.user) | Q(claimcollaborator__user=self.request.user)) Serializer: class ClaimSerializer(serializers.HyperlinkedModelSerializer): author = serializers.PrimaryKeyRelatedField(allow_null=True, queryset=get_user_model().objects.all()) class Meta: model = Claim fields = ('url', 'permalink', 'author', 'deleted') lookup_field = 'permalink' extra_kwargs = { 'url': {'lookup_field': 'permalink'}, } Listing produces this SQL: SELECT "api_claim"."permalink", "api_claim"."author_id", "api_claim"."deleted" LEFT OUTER JOIN "api_claimcollaborator" ON ("api_claim"."id" = "api_claimcollaborator"."claim_id") WHERE ("api_claim"."author_id" = 39 OR "api_claimcollaborator"."user_id" = 39) So I'm getting…
has comment: http://stackoverflow.com/comment/83095844
type: Question

http://stackoverflow.com/q/48069491
has title: PHP compile string to bytecode without evaling it
type: Question
has body: Python (CPython and Jython at least, possibly all Pythons) have a function called compile that can be used to compile a file into a string into or a bytecode object. # foo.py a = compile(""" print(47) """, filename="testfile", mode="exec") exec(a) Running foo.py produces: $ python foo.py 47 Does PHP (Zend specifically, any version) expose its bytecode compiler to user code in a similar way? More specifically, can you dynamically compile strings without executing them like eval does.
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83112720
has answer: http://stackoverflow.com/a/48069851
has answer: http://stackoverflow.com/a/48069663
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83112903
tagged with: python
tagged with: php

http://stackoverflow.com/comment/83110153
score: 0
comment on: http://stackoverflow.com/q/48068247
type: Comment
has text: How would "they" know it's an image of code? (I mean, wow – Stack Overflow would be interested!)
type: QuestionComment

http://stackoverflow.com/q/48066171
answer count: 2
downvote count: 3
favorite count: 0
tagged with: python-asyncio
type: UnansweredQuestion
tagged with: python
score: 3
has answer: http://stackoverflow.com/a/48117351
has title: "Lazy" version of asyncio.gather?
type: Question
has answer: http://stackoverflow.com/a/48066761
has body: I'm using Python's asyncio module and async/await to process a character sequence in chunks concurrently and collect the results in a list. For that I'm using a chunker function (split) and a chunk processing function (process_chunk). They both come from a third-party library, and I would prefer not to change them. Chunking is slow, and the number of chunks is not known up front, which is why I don't want to consume the whole chunk generator at once. Ideally, the code should advance the generator in sync with the process_chunk's semaphore, i.e., every time that function returns. My code import asyncio def split(sequence): for x in sequence: print('Getting the next chunk:', x) yield x print('Finished chunking') async def process_chunk(chunk, *, semaphore=asyncio.Semaphore(2)): async with semaphore: print('Processing chunk:', chunk) await asyncio.sleep(3) return 'OK' async def process_in_chunks(sequence): gen = split(sequence) coro = [process_chunk(chunk) for chunk in gen] results = await asyncio.gather(*coro) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(process_in_chunks('ABC')) kind of works and prints Getting the next chunk: A Getting the next chunk: B Getting the next chunk: C Finished chunking Processing chunk: C Processing chunk: B Processing chunk: A although that means that the gen generator is exhausted before the processing begins. I know why it happens, but how do change that?
upvote count: 6
has comment: http://stackoverflow.com/comment/95037366

http://stackoverflow.com/comment/83147503
has text: I haven't downvoted but you could've shown which code "gets the actual value". That would make the question answerable instead of relying on guessing what did happen.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48086214
type: Comment

http://stackoverflow.com/comment/83000635
type: QuestionComment
has text: Possible duplicate of [Python 3 ImportError: No module named 'ConfigParser'](https://stackoverflow.com/questions/14087598/python-3-importerror-no-module-named-configparser)
comment on: http://stackoverflow.com/q/48015668
score: 0
type: Comment

amazon-ecs
type: Tag
tag name: amazon-ecs
tags question: http://stackoverflow.com/q/48091774
tags question: http://stackoverflow.com/q/48076616

http://stackoverflow.com/a/48017776
has comment: http://stackoverflow.com/comment/83005018
type: Answer
score: 3
upvote count: 3
has body: I've figured out a solution. instead of making the e.get() a variable, i just put it into the pygame statement. pygame.mixer.music.load(s+".mp3") changed to pygame.mixer.music.load((e.get())+".mp3") and it works
answers question: http://stackoverflow.com/q/48017614
downvote count: 0

http://stackoverflow.com/comment/83179548
score: 0
type: Comment
type: QuestionComment
has text: Yes. It’s not there. Not even in sent mail of the sending email
comment on: http://stackoverflow.com/q/48023948

http://stackoverflow.com/a/49516493
score: 0
answers question: http://stackoverflow.com/q/48066517
has body: First of all you need to install xlrd &amp; pandas packages. Then try below code. import xlrd import pandas as pd xl = pd.ExcelFile("fileName.xlsx") print(xl.parse(xl.sheet_names[0]))
type: Answer

http://stackoverflow.com/q/48052616
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83077451
has answer: http://stackoverflow.com/a/48058647
type: Question
has comment: http://stackoverflow.com/comment/83077434
score: 0
has body: I would like to display an error dialog for a wxpython app I have. Currently I'm using the following code that I found from a blog post that I can't seem to get to work. I added some code which I know will throw a directory name error and the error will display in the IDE but not throw up an error dialog as I would like it to. try: app = wx.App(False) frame = MyScriptApp(None, "Move Tool") app.MainLoop() except: import sys, traceback xc = traceback.format_exception(*sys.exc_info())
answer count: 1
tagged with: wxpython
has title: Display Error in Dialog using wxpython

http://stackoverflow.com/q/48082426
downvote count: 3
upvote count: 0
type: UnansweredQuestion
tagged with: flask
tagged with: flask-sqlalchemy
score: -3
favorite count: 0
has answer: http://stackoverflow.com/a/48083547
tagged with: python-2.7
type: Question
has body: Iv'e been doing some maintenance on the server side and then deployed the app to the GAE. since I deployed the new version, it doesn't recognize the flask_sqlalchemy module. It worked perfectly before the commit. is there something that I'm missing?
tagged with: google-app-engine
tagged with: python
answer count: 1
has title: No module named flask_sqlalchemy after deploying app GAE

http://stackoverflow.com/q/48135938
tagged with: python-requests
has comment: http://stackoverflow.com/comment/83271263
type: Question
score: 3
tagged with: pdfkit
has body: import requests import pdfkit # start a session s = requests.Session() data = {'username': 'name', 'password': 'pass'} # POST request with cookies s.post('https://www.facebook.com/login.php', data= data) url = 'https://www.facebook.com' # navigate to page with cookies set options = {'cookie': s.cookies.items(), 'javascript-delay': 1000} pdfkit.from_url(url, 'file.pdf', options= options) I'm trying to automate the process of saving a login-protected webpage as a PDF by setting the cookies and navigating to the page using requests. Is there a better way to tackle this/something I'm doing wrong?
has title: Save a PDF of a webpage that requires login
answer count: 2
has comment: http://stackoverflow.com/comment/83268294
has comment: http://stackoverflow.com/comment/83271500
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48147023
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/83287629
has comment: http://stackoverflow.com/comment/83249116
has comment: http://stackoverflow.com/comment/83271332
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51952657
tagged with: browser-automation
linked to: http://stackoverflow.com/q/45884654

http://stackoverflow.com/q/48042872
has title: Python - Scrapy - Creating a crawler that gets a list of URLs and crawls them
has answer: http://stackoverflow.com/a/48043539
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/83057652
has answer: http://stackoverflow.com/a/48043540
has comment: http://stackoverflow.com/comment/83058366
type: UnansweredQuestion
tagged with: python
has body: I am trying to create a spider with the package "Scrapy" that gets a lists of URLs and crawls them. I have searched stackoverflow for an answer but could not find something that will solve the issue. My script is as follows: class Try(scrapy.Spider): name = "Try" def __init__(self, *args, **kwargs): super(Try, self).__init__(*args, **kwargs) self.start_urls = kwargs.get( "urls" ) print( self.start_urls ) def start_requests(self): print( self.start_urls ) for url in self.start_urls: yield Request( url , self.parse ) def parse(self, response): d = response.xpath( "//body" ).extract() When I crawl the spider: Spider = Try(urls = [r"https://www.example.com"]) process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(Spider) process.start() I get the following info printed while printing self.start_urls: In the __init__ function printed on screen is: [r"https://www.example.com"] (as passed to the spider). In the start_requests function printed on screen is: None Why do I get None? Is there another way to approach this issue? or Is there any mistakes in my spider's class? Thanks for any help given!
tagged with: scrapy
type: Question

http://stackoverflow.com/a/48694422
accepted answer of: http://stackoverflow.com/q/48064477
answers question: http://stackoverflow.com/q/48064477
type: Answer
has comment: http://stackoverflow.com/comment/112558228
score: 0
type: AcceptedAnswer
has body: In Multiclass CatBoost uses Buckets method for calculating ctrs. The formula that you have written is correct. A separate ctr feature is calculated for each class. Here the countInClass is the count of objects with the same category value before given one in random permutation, that have this class value. And the totalCount is the number of objects before given with same category value that have any class value.

http://stackoverflow.com/comment/83142392
has text: Many linters will silence if you use _ instead of i (_ makes it explicit that it is a throw away variable)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48083822

http://stackoverflow.com/a/48056289
type: Answer
accepted answer of: http://stackoverflow.com/q/48051368
upvote count: 0
answers question: http://stackoverflow.com/q/48051368
has body: As per the HTML you have shared the value of the id attribute i.e. DWT54 looks dynamic to me. So we have to construct a dynamic css or xpath to identify the frame and instead of driver.switch_to_frame(driver.find_element_by_id(frame_reference)) we have to use driver.switch_to.frame(frame_reference) as follows: driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@id,'_content_ifr') and contains(@title,'Texte richeFaites')]"))
score: -1
type: AcceptedAnswer
downvote count: 1

http://stackoverflow.com/comment/83622320
type: Comment
comment on: http://stackoverflow.com/a/48147473
has text: This works okay for me (see gif above, balls keep moving during rotation), does this happend with code above? May be an issue with your matplotlib backend or caused by the "Click Go" user input . The ball positions/figure redraw is from the `step in range(100)` loop and the rotation is a user event, see https://matplotlib.org/users/event_handling.html so you'd need to see if this is interfering/stopping this loop. I'd post as a new question if you can't fix.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83303257
has text: True, you can't actually *click a button* with `requests` but you can almost always emulate browser-server interactions using `requests` and get the information you want. It's just a matter of figuring out the right things to do... I think this is what OP was asking. In this particular case, there is no network call when you click the button and the page loads with JS disabled. So the information is likely already in the DOM.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48160554

http://stackoverflow.com/comment/83235736
score: 1
comment on: http://stackoverflow.com/a/48129393
type: AnswerComment
type: Comment
has text: How do I reused the token? I was searching exactly for this. I can access it via session.access_token, so I can save it, but how do I re-create the session with that token?

http://stackoverflow.com/comment/83194333
comment on: http://stackoverflow.com/a/48100424
score: 0
type: Comment
has text: If the id where distinct by date this would have been it. Thanks for this.
type: AnswerComment

lstm
tags question: http://stackoverflow.com/q/48042012
tags question: http://stackoverflow.com/q/48063076
tags question: http://stackoverflow.com/q/48140989
tags question: http://stackoverflow.com/q/48129814
tags question: http://stackoverflow.com/q/48028385
tags question: http://stackoverflow.com/q/48034625
tags question: http://stackoverflow.com/q/48069241
tags question: http://stackoverflow.com/q/48152730
tags question: http://stackoverflow.com/q/48145150
tag name: lstm
tags question: http://stackoverflow.com/q/48160063
tags question: http://stackoverflow.com/q/48084798
tags question: http://stackoverflow.com/q/48055536
type: Tag
tags question: http://stackoverflow.com/q/48121763
tags question: http://stackoverflow.com/q/48158454

http://stackoverflow.com/a/48048880
type: Answer
score: 1
has body: It would seem a little preprocessing is needed to fix your data. Let's combine the adjacent records, so that the data in keys is also read in - y = data['rows'] for i, j in zip(y[::2], y[1::2]): i.update(dict(zip(['keyword', 'url'], j['keys']))) Now, read in every alternate record in data - df = pd.io.json.json_normalize(data['rows'][::2]) df clicks ctr impressions keyword position \ 0 79.0 NaN 307.0 spring break 2018 1.013029 1 179.0 NaN 5307.0 spring break zrce 1.013029 2 759.0 NaN 3307.0 spring break 2017 1.013029 3 749.0 0.257329 3567.0 zrce 1.013029 url 0 https://zrce.eu/partykalender/big-beach-spring... 1 https://zrce.eu/partykalender/big-beach-spring... 2 https://zrce.eu/partykalender/big-beach-spring... 3 https://zrce.eu/ Calling to_dict('r') on this df will give you something like this - [ { "clicks": 79.0, "url": "https://zrce.eu/partykalender/big-beach-spring-break/", "position": 1.013029315960912, "ctr": NaN, "impressions": 307.0, "keyword": "spring break 2018" }, ... ] Disclaimer! This method will modify your data in place. If you don't want that, I'd recommend making a copy first.
accepted answer of: http://stackoverflow.com/q/48046500
upvote count: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48046500

http://stackoverflow.com/a/48059910
score: 0
has body: If you absolutely cannot alter your schema, then you could unpivot performance data and join with users. Sample mappings for relations, since none were provided: In [2]: class User(Base): ...: __tablename__ = "users" ...: username = Column(Unicode(255), primary_key=True) ...: firstname = Column(Unicode(255)) ...: lastname = Column(Unicode(255)) ...: In [3]: class Performance(Base): ...: __tablename__ = "performance" ...: timestamp = Column(Date, primary_key=True) ...: # NOTE: this works **only** in a class body context, ...: # and your schema shouldn't be like this anyway. ...: for name in ['alice', 'bob']: ...: locals()[name] = Column(Integer, nullable=False) ...: Get usernames that have performance data using inspection. You could also hold on to a static list of usernames: In [11]: users = inspect(Performance).attrs.keys()[1:] In [12]: users Out[12]: ['alice', 'bob'] Form the unpivot query – just one way to do it: In [15]: from sqlalchemy.dialects import postgresql ...: performance = session.query( ...: func.unnest(postgresql.array(users)).label('username'), ...: func.unnest(postgresql.array( ...: [getattr(Performance, name) ...: for name in users])).label('value')).\ ...: filter(Performance.timestamp == '2017-11-2').\ ...: subquery() ...: Join users with their performance values: In [24]: session.query(User, performance.c.value).\ ...: join(performance, performance.c.username == User.username).\ ...: all() Out[24]: [(&lt;__main__.User at 0x7f79eb5d2c88&gt;, 1), (&lt;__main__.User at 0x7f79eb5d2cf8&gt;, 5)] Were you to alter your schema such that performance data is stored as (timestamp, username, value) tuples, you could simply do this: In [2]: class User(Base): ...: __tablename__ = "users" ...: ... ...: performance = relationship("BetterPerformance") ...: In [25]: class BetterPerformance(Base): ...: __tablename__ = "better_performance" ...: timestamp = Column(Date, primary_key=True) ...: username = Column(ForeignKey('users.username'), primary_key=True) ...: val…
type: Answer
answers question: http://stackoverflow.com/q/48023625

http://stackoverflow.com/comment/122932070
type: AnswerComment
has text: Same for Firefox.
type: Comment
comment on: http://stackoverflow.com/a/60596229
score: 1

http://stackoverflow.com/comment/83038975
score: 0
comment on: http://stackoverflow.com/q/48034172
type: QuestionComment
type: Comment
has text: Thank you so much! It worked!!

http://stackoverflow.com/comment/83203307
comment on: http://stackoverflow.com/a/48109675
score: 0
type: Comment
type: AnswerComment
has text: Yes, I can confirm that creating clones of the workers works 100%. Even more interesting is the implied constraint of creating only 50 clones for each. Thanks again Peter!

http://stackoverflow.com/comment/83292592
comment on: http://stackoverflow.com/q/48156294
has text: TCPlient comes from SwiftSocket. I will give you the link to the github: https://github.com/swiftsocket/SwiftSocket
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83304158
comment on: http://stackoverflow.com/a/48161923
type: AnswerComment
has text: In the shell script snippet, you should properly use double quotes around `"$INPUT"` where it is used as a file name argument to `mongoimport`. The code works fine for trivial file names, but has ugly errors when you have a file named literally `*.json` or something.
score: 0
type: Comment

http://stackoverflow.com/q/48115281
has body: I have Problem and Solution model defined in my models.py. Solution has a foreignkey to the Problem model. That is, a problem can have many solutions. I want to create urls like www.example.com/problem/problem_id/solution/solution_number/ where problem_id describes the primary key of Problem model and solution_number describes the order in which the solution was posted for a particular problem. In other words, if a solution is first solution to a given problem, its order should be 1 and second solution to the same problem gets an order 2. This will allow me to access a solution to particular problem like Solution.objects.get(problem=problem, order=order)
has answer: http://stackoverflow.com/a/48115405
has title: order a child model with respect to parent model in Django
tagged with: django-models
type: Question
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/q/48019883
tagged with: python-3.x
tagged with: qlistwidget
tagged with: python
has body: (I'm an absolute PyQt beginner.) I would like to update a QLabel with the description of a software option whenever the user uses the arrow keys to scroll down a very long list of options displayed in a QListWidget or clicks on an option in the QListWidget. I've already to managed to connect the click option to do what I want to do, but I can't figure out how to detect arrow key presses. This is what I have so far: main.ui <?xml version="1.0" encoding="UTF-8"?> Dialog <x>0</x> <y>0</y> 341 244 Dialog <x>10</x> <y>10</y> 321 231 TextLabel QDialogButtonBox::Cancel|QDialogButtonBox::Ok <resources/> buttonBox accepted() Dialog accept() <x>170</x> <y>228</y> <x>170</x> <y>121</y> test.py #!/usr/bin/env python # -*- coding: utf-8 -*- import sys from PyQt5 import uic, QtWidgets from PyQt5.Qt import QMessageBox class GUI(QtWidgets.QDialog): listOptions = [] dicDescriptions = {} for x in range(0, 100): option = 'Option ' + str(x) description = 'Description for ' + option listOptions.append(option) dicDescriptions[option] = description def __init__(self): super(GUI, self).__init__() uic.loadUi('C:/Users/User/Desktop/main.ui', self) self.accepted.connect(self.ReadValue) self.lwOptions.addItems(self.listOptions) self.lwOptions.itemClicked.connect(self.UpdateDescription) self.lbDescription.setText(self.dicDescriptions[self.listOptions[0]]) def UpdateDescription(self): currentItem = self.lwOptions.currentItem().text() self.lbDescription.setText(self.dicDescriptions[currentItem]) def ReadValue(self): currentItem = self.lwOptions.currentItem().text() QMessageBox.information(self, "Selection", "You've selected: " + currentItem) app = QtWidgets.QApplication(sys.argv) window = GUI() window.show() sys.exit(app.exec_()) How do detect the arrow key presses and update the QLabel. How do I use uic.loadUi with relative paths? I've tried uic.loadUi('main.ui', self) and uic.loadUi('./main.ui', self), but it didn't work even though both files are in the same folder.
has answer: http://stackoverflow.com/a/48021055
accepted answer: http://stackoverflow.com/a/48021055
type: Question
tagged with: qlabel
type: AnsweredQuestion
score: 0
has title: Connect a QLabel with a QListWidget selection
tagged with: pyqt
answer count: 1

http://stackoverflow.com/a/57709777
upvote count: 0
score: -1
has body: Or you could just open a for loop. for i,j in df['a'],df['b']: if j&gt;0: df['c']=i/j else: df['c']=0.0
answers question: http://stackoverflow.com/q/48123368
type: Answer
has comment: http://stackoverflow.com/comment/103347921
downvote count: 1

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

http://stackoverflow.com/comment/82999896
comment on: http://stackoverflow.com/a/48015166
score: 0
type: AnswerComment
has text: Yes it does reload the page. That is the desired state. I wanted the page reloaded because I have written the code already that populates the tables in that manner. It's python based code. If I did it with success on AJAX, I would have to write all that in Javascript.
type: Comment

http://stackoverflow.com/comment/83052882
type: Comment
type: QuestionComment
has text: @furas You can't always do so. For example, passing a `zip` or `map` objects results in a TypeError.
comment on: http://stackoverflow.com/q/48041043
score: 0

http://stackoverflow.com/comment/83115060
type: QuestionComment
has text: See this question. https://stackoverflow.com/questions/47982894/selecting-random-windows-from-multidimensional-numpy-array-rows/47982961#47982961
comment on: http://stackoverflow.com/q/48070668
score: 0
type: Comment

http://stackoverflow.com/a/48124800
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48124647
has body: Yes, inefficient, but also harder to read and understand with repeated opening and line reading. Please to not post such code. .readlines produces a list of strings representing lines, terminated by \n if the line in the file is so terminated. Your test is correct, if obscured. &gt;&gt;&gt; '\n' in [''] False &gt;&gt;&gt; '\n' in ['a'] False &gt;&gt;&gt; '\n' in ['a\n'] False &gt;&gt;&gt; '\n' in ['\n'] True It must be that your file does not contain a blank line ending with a newline.
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/48017448
has body: Let's use pd.get_dummmies with parameter prefix: #Using @Lambda setup label = ["a", "b", "a", "a", "c", "n o", "ye s"] s = pd.Series(label) pd.get_dummies(s, prefix='label') Output: label_a label_b label_c label_n o label_ye s 0 1 0 0 0 0 1 0 1 0 0 0 2 1 0 0 0 0 3 1 0 0 0 0 4 0 0 1 0 0 5 0 0 0 1 0 6 0 0 0 0 1 Timings: for keys loop method &gt; %%timeit for key in keys: &gt; df[("label_%s" % key).replace(" ", "_")] = (s == key).astype(int) 100 loops, best of 3: 6.7 ms per loop String accessor get_dummies method &gt; %timeit s.str.get_dummies().add_prefix('label_') 100 loops, best of 3: 6.03 ms per loop pd.get_dummies with prefix parameter: &gt; %timeit pd.get_dummies(s, prefix='label') 1000 loops, best of 3: 1.77 ms per loop
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48016370
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48016370

http://stackoverflow.com/comment/83117170
has text: ooh okay let me try this approach thank you @saranya Sridharan
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48071458
type: AnswerComment

http://stackoverflow.com/comment/83313705
type: AnswerComment
score: 0
type: Comment
has text: This will also match `999.999.999.999`, which cannot be an IP number.
comment on: http://stackoverflow.com/a/48167269

http://stackoverflow.com/comment/83156601
type: Comment
comment on: http://stackoverflow.com/a/48091064
type: AnswerComment
has text: I tried setup the proxy and it shows <Response [200]>. Does it mean it works?
score: 0

http://stackoverflow.com/comment/83119330
score: 1
comment on: http://stackoverflow.com/a/48072571
has text: Yes that is what I am thinking about. Thanks.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/83091127
score: 0
comment on: http://stackoverflow.com/q/48058914
type: Comment
type: QuestionComment
has text: Seem to be spot on yes. But having no understanding of how these things are working under the hood I am strained for options. Would it be possible to create a socket for each process and using that to call the lookup function? Could the lookups be queued some how? - Yes, I have tried sleeping, but since I have 4 processes running there's no guarantee that not one of these will be executed at the same time.

http://stackoverflow.com/q/48052766
has comment: http://stackoverflow.com/comment/83078941
favorite count: 0
tagged with: python-3.x
tagged with: tkinter
type: UnansweredQuestion
has body: The code that I have been working with as a fun side project has been working perfectly fine until when running the search function I uncounted an error which I have never had before. I've tried to figure out why it ain't working because in the past it has and all of a sudden it isn't. import sqlite3 def connect(): """Set up a connection with the database.""" conn_obj = sqlite3.connect("movies.db") cur_obj = conn_obj.cursor() cur_obj.execute("CREATE TABLE IF NOT EXISTS " "movie (id integer PRIMARY KEY, " "title text, " "director text, " "year integer, " "studio integer)") conn_obj.commit() conn_obj.close() def insert(title, director, year, studio): """Insert entry into database.""" conn_obj = sqlite3.connect("movies.db") cur_obj = conn_obj.cursor() cur_obj.execute("INSERT INTO movie " "VALUES (NULL, ?, ?, ?, ?)", (title, director, year, studio)) conn_obj.commit() conn_obj.close() def view(): """View all database entries.""" conn_obj = sqlite3.connect("movies.db") cur_obj = conn_obj.cursor() cur_obj.execute("SELECT * FROM movie") rows = cur_obj.fetchall() conn_obj.close() return rows def update(id, title, author, year, isbn): """Update a database entry.""" conn_obj = sqlite3.connect("movies.db") cur_obj = conn_obj.cursor() cur_obj.execute("UPDATE movie " "SET title = ?, " "director = ?, " "year = ?, " "studio = ? " "WHERE id = ?", (title, director, year, studio, id)) conn_obj.commit() conn_obj.close() def delete(id): """Delete a database entry.""" conn_obj = sqlite3.connect("movies.db") cur_obj = conn_obj.cursor() cur_obj.execute("DELETE FROM movie " "WHERE id = ?", (id,)) conn_obj.commit() conn_obj.close() def search(title = "", director = "", year = "", studio = ""): """Search for a database entry.""" conn_obj = sqlite3.connect("movies.db") cur_obj = conn_obj.cursor() cur_obj.execute("SELECT * " "FROM movie " "WHERE title = ? OR director = ? OR year = ? OR studio = ?", (title, director, year, studio)) rows = cur_obj.fetchall() conn_obj.close() return rows connect()…
tagged with: python
has title: sqlite3.OperationalError: near "?": syntax error just randomly occurred
downvote count: 1
type: Question
tagged with: syntax-error
has answer: http://stackoverflow.com/a/48054702
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/83078930
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/83078110

http://stackoverflow.com/comment/83319267
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48150347
type: Comment
has text: @Terry Jan Reedy I'm not quite sure how you would go about setting them as globals because what I've tried kept erroring me. Also do you maybe know how I could loop the video so that it would play non-stop until a button is pressed? But anyhow thank you for your help!

http://stackoverflow.com/comment/83076742
type: QuestionComment
has text: `"[" + ", ".join("a" + str(i) for i in range(0, 3)) + "]"`
comment on: http://stackoverflow.com/q/48052336
score: 0
type: Comment

http://stackoverflow.com/q/48150346
tagged with: python
tagged with: dataframe
type: Question
answer count: 2
score: 4
has answer: http://stackoverflow.com/a/48150588
tagged with: pandas
downvote count: 1
has title: How to partition pandas data frame based on week and save as CSV?
has body: I have a pandas data frame as below. This data frame about one month period. How do I partition this data frame based on week? I need save each 4 weeks as seperate 4 CSV files. Time Stamp Id Latitude Longitude 01/10/2016 15:22:51:700 1 23 50 01/10/2016 16:28:08:026 1 23 50 01/10/2016 16:28:09:026 1 12 45 02/10/2016 19:00:08:026 2 23 50 02/10/2016 20:28:08:026 1 23 50 03/10/2016 19:00:08:000 2 23 50 03/10/2016 01:02:33:123 2 23 50 03/10/2016 06:15:08:500 1 23 50 03/10/2016 10:01:07:022 3 28 88 ...... ...... 31/10/2016 13:09:17:044 1 33 80 My expected output is: Time Stamp Id Latitude Longitude 01/10/2016 15:22:51:700 1 23 50 01/10/2016 16:28:08:026 1 23 50 01/10/2016 16:28:09:026 1 12 45 02/10/2016 19:00:08:026 2 23 50 02/10/2016 20:28:08:026 1 23 50 03/10/2016 19:00:08:000 2 23 50 03/10/2016 01:02:33:123 2 23 50 03/10/2016 06:15:08:500 1 23 50 03/10/2016 10:01:07:022 3 28 88 ...... ...... 07/10/2016 03:09:10:066 5 28 78 This should be my first week. Next weeks from 08/10/2016 to 14/10/2017, from 15/10/2016 to 21/10/2017 and from 22/10/2016 to 31/10/2017.
has answer: http://stackoverflow.com/a/48150479
favorite count: 0
upvote count: 5
type: UnansweredQuestion

http://stackoverflow.com/a/48058403
has comment: http://stackoverflow.com/comment/83089781
has body: You can use: #convert column to datetime df['Time'] = pd.to_datetime(df['Time']) #simplier solution with strftime df['WW'] = df['Time'].dt.strftime('%G-%V') #solution with isocalendar df['WW1'] = df['Time'].apply(lambda x: str(x.isocalendar()[0]) + '-' + str(x.isocalendar()[1]).zfill(2)) print (df) Time WW WW1 0 2017-01-01 00:00:00 2016-52 2016-52 &lt;- changed datetime 1 2016-08-10 23:20:00 2016-32 2016-32 2 2016-09-10 23:20:00 2016-36 2016-36 3 2017-09-10 23:20:00 2017-36 2017-36 4 2016-09-10 23:20:00 2016-36 2016-36 Thank you @Fierr for correct '%Y-%V' to '%G-%V'.
type: Answer
has comment: http://stackoverflow.com/comment/106049362
score: 8
downvote count: 0
has comment: http://stackoverflow.com/comment/106049381
has comment: http://stackoverflow.com/comment/83089741
has comment: http://stackoverflow.com/comment/83089730
upvote count: 8
has comment: http://stackoverflow.com/comment/106052314
answers question: http://stackoverflow.com/q/48058304
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48058304

http://stackoverflow.com/comment/83287950
comment on: http://stackoverflow.com/q/48152557
score: 0
type: Comment
type: QuestionComment
has text: I clearly don't understand your question well enough without [mcve].

http://stackoverflow.com/q/48096902
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: sqlalchemy
type: Question
has body: I have two lists of column names: setcols and wherecols. I want to build a query with SQLAlchemy methods that is along the lines of UPDATE tablename SET setcols[0]= ?, ... WHERE wherecols[0]= ?, ... What I tried is t = sa.table('tablename', *[sa.column(name) for name in setcols+wherecols]) query = t.update(). \ where(t.c[cn] == sa.bindparam(cn) for cn in wherecols).\ values({cn: sa.bindparam(cn) for cn in setcols}) and this query = t.update({cn: sa.bindparam(cn) for cn in setcols}). \ where(t.c[cn] == sa.bindparam(cn) for cn in wherecols) but neither of these worked and I got the following error: sqlalchemy.exc.ArgumentError: SQL expression object or string expected, got object of type &lt;class 'generator'&gt; instead I've read the manual and thought that the values to be set can be provided as a dictionary, but I see that I'm wrong... Could anyone help? I'm using sqlalchemy-1.1.13.
has answer: http://stackoverflow.com/a/48096975
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48096975
tagged with: python
has title: Constructing an UPDATE .. SET .. WHERE .. statement with SQLAalchemy

http://stackoverflow.com/comment/83088602
type: Comment
type: QuestionComment
score: 1
has text: `outer` is an `int`, so you need `for inner in range(len(my_list[outer]))`
comment on: http://stackoverflow.com/q/48058197

http://stackoverflow.com/a/48171723
type: Answer
accepted answer of: http://stackoverflow.com/q/48171492
answers question: http://stackoverflow.com/q/48171492
score: 9
upvote count: 9
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/95167422
has body: You data1 type in your df is object , we need adding pd.to_numeric datedatF.dtypes Out[39]: data1 object key1 datetime64[ns] key2 int64 dtype: object grouped2=pd.to_numeric(datedatF['data1']).groupby(datedatF['key2']) grouped2.mean() Out[41]: key2 2015001 1.3 Name: data1, dtype: float64

http://stackoverflow.com/q/48116700
has comment: http://stackoverflow.com/comment/83210714
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83210443
has answer: http://stackoverflow.com/a/48117449
score: 0
accepted answer: http://stackoverflow.com/a/48117449
answer count: 1
has comment: http://stackoverflow.com/comment/83210840
has comment: http://stackoverflow.com/comment/83211283
has comment: http://stackoverflow.com/comment/83209510
has body: I have a large array K (29000 x 29000): K= numpy.random.random((29000, 29000)) I want to apply the following operation on K: output = K* (1.5 - 0.5 * K* K) To try preventing 'MemoryError' , I am doing my computations as suggested on the answer from this thread. However, when I try to do the assignment operation on the large array as follows, I still get the MemoryError: K *= 1.5 - 0.5 * K * K Any help welcome. NOTE: this is not a duplicate post. There is a suggestion on this post using cython. But I am looking for alternative solutions which may not rely on Cython.
tagged with: python
linked to: http://stackoverflow.com/q/4318615
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48115074
has comment: http://stackoverflow.com/comment/83209733
has comment: http://stackoverflow.com/comment/83210068
has title: Why is assignment operation still giving MemoryError for large arrays in Python?

http://stackoverflow.com/q/48103072
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/48103202
favorite count: 0
upvote count: 3
linked to: http://stackoverflow.com/q/38589830
tagged with: cron
tagged with: python
has answer: http://stackoverflow.com/a/48103202
downvote count: 0
has title: django-crontab does not execute scheduled jobs
tagged with: django
has body: I am having a very similar virtualenv setup than in the question: Django crontab not executing test function. in my_app.cron.py def test(): print('HELLO') in settings.py INSTALLED_APPS = ( ... 'django_crontab', ) CRONTAB_COMMAND_SUFFIX = '2&gt;&amp;1' CRONJOBS = [ ('*/1 * * * *', 'my_app.cron.test','&gt;&gt; /cron_job.log'), ] python manage.py crontab add adding cronjob: (bee8ad945bb9c6b15a3ff0847481a181) -&gt; ('*/1 * * * *', 'my_app.cron.test', '&gt;&gt; /cron_job.log') python manage.py crontab show Currently active jobs in crontab: bee8ad945bb9c6b15a3ff0847481a181 -&gt; ('*/1 * * * *', 'my_app.cron.test', '&gt;&gt; /cron_job.log') Everything seems fine yet nothing is printed in the log file or the console. What's missing here?
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/83148984
has text: Then is there a way to get it working without the hashed password? What is it?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48054399

http://stackoverflow.com/a/48122198
has comment: http://stackoverflow.com/comment/95844364
has comment: http://stackoverflow.com/comment/95847426
has comment: http://stackoverflow.com/comment/95844498
type: Answer
has body: Define a function which will plot the identity line on the current axes, and apply it to the off-diagonal axes of the grid using PairGrid.map_offdiag() method. For example: import seaborn as sns import numpy as np import matplotlib.pyplot as plt def plot_unity(xdata, ydata, **kwargs): mn = min(xdata.min(), ydata.min()) mx = max(xdata.max(), ydata.max()) points = np.linspace(mn, mx, 100) plt.gca().plot(points, points, color='k', marker=None, linestyle='--', linewidth=1.0) ds = sns.load_dataset('iris') grid = sns.pairplot(ds) grid.map_offdiag(plot_unity) This makes the following plot on my setup. You can tweak the kwargs of the plot_unity function to style the plot however you want.
has comment: http://stackoverflow.com/comment/83221401
has comment: http://stackoverflow.com/comment/83241380
upvote count: 10
answers question: http://stackoverflow.com/q/48122019
has comment: http://stackoverflow.com/comment/83241590
score: 10
has comment: http://stackoverflow.com/comment/83221453
accepted answer of: http://stackoverflow.com/q/48122019
has comment: http://stackoverflow.com/comment/95845009
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/83243417
type: Comment
comment on: http://stackoverflow.com/q/48133102
score: 6
type: QuestionComment
has text: The code you've posted shouldn't give you an error. What error are you getting, and can you provide a [mcve] of your code?

http://stackoverflow.com/comment/83075206
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48051565
type: Comment
has text: Works on my machine!

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/48072484
tags question: http://stackoverflow.com/q/48127273
tags question: http://stackoverflow.com/q/48027290
tags question: http://stackoverflow.com/q/48113905

http://stackoverflow.com/a/48063208
type: Answer
answers question: http://stackoverflow.com/q/48062858
has comment: http://stackoverflow.com/comment/83099577
has body: The problem is you are directly assigning the single value to column rather than list/array/series. A single value is replicating itself in each row. I would suggest you to make a list and assign it to your df['Status'] column. status=[] for elemento in df['Analisis']: if elemento == 'Estable' status.append('Stable: The client''s performance was Stable') else: status.append('NoAnalyzed') df['Status'] = status This should work.
has comment: http://stackoverflow.com/comment/83099696
score: 0

http://stackoverflow.com/comment/106633411
type: AnswerComment
has text: To answer your question I will destructure this a little bit: `2*x - array_sum = x + x - array_sum = (x - array_sum) + x` where `x + array_sum` is the right part of the sum and x is the left part of the sum. e.g.: `A[0] - array_sum` is the tail. `A[0]` is the head. So `last_minimum = abs(A[0] + A[0] - array_sum)` is the difference between head and tail.
type: Comment
comment on: http://stackoverflow.com/a/60141255
score: 5

http://stackoverflow.com/q/48039229
has answer: http://stackoverflow.com/a/48039259
accepted answer: http://stackoverflow.com/a/48039259
upvote count: 3
has body: I have developed a program that puts a user's username, subject, unit, score and grade into a text file. This is the code: tests.extend([subject, unit, str(score), grade]) print tests with open("test.txt", "a") as testFile: for test in tests: userName = test[0] subject = test[1] unit = test[2] score = test[3] grade = test[4] testFile.write(userName + ';' + subject + ';' + unit + ';' + str(score) + ';' + grade + '\n') It prints: ['abc', 'history', 'Nazi Germany', '65', 'C'] ('abc' being the username) And the following error: grade = test[4] IndexError: string index out of range I don't know why I'm getting this error? Any ideas? *Already added in previously in quiz: * quizzes = [] quizzes.append(userName)
downvote count: 1
type: Question
type: AnsweredQuestion
tagged with: list
answer count: 1
favorite count: 0
has title: string index out of range error using lists and text files (using Python)
tagged with: python
tagged with: text-files
score: 2

performance
tags question: http://stackoverflow.com/q/48143177
tags question: http://stackoverflow.com/q/48086073
tags question: http://stackoverflow.com/q/48020149
tags question: http://stackoverflow.com/q/48028674
tags question: http://stackoverflow.com/q/48088783
tags question: http://stackoverflow.com/q/48103157
tags question: http://stackoverflow.com/q/48073980
tags question: http://stackoverflow.com/q/48080567
tags question: http://stackoverflow.com/q/48035125
tags question: http://stackoverflow.com/q/48025999
tags question: http://stackoverflow.com/q/48066606
tags question: http://stackoverflow.com/q/48075841
tags question: http://stackoverflow.com/q/48084325
tags question: http://stackoverflow.com/q/48040869
tag name: performance
tags question: http://stackoverflow.com/q/48134612
tags question: http://stackoverflow.com/q/48104401
type: Tag
tags question: http://stackoverflow.com/q/48116496
tags question: http://stackoverflow.com/q/48094341
tags question: http://stackoverflow.com/q/48161305
tags question: http://stackoverflow.com/q/48031283
tags question: http://stackoverflow.com/q/48161562

http://stackoverflow.com/comment/83298703
comment on: http://stackoverflow.com/q/48158746
score: 0
type: Comment
type: QuestionComment
has text: @roganjosh I return an array? or list (i believe its called in python). I should have len(alpha) entries and I want to integrate it with respect to b.

http://stackoverflow.com/comment/83208821
has text: I'm obviously not... in my peewee model: def get_tags(self): return tag_list.select(), gives me output from the table, then in flask app.py I just do output = model.get_tags() and then in app route: @app.route(.... output=output...), then on a webpage I can loop through using column headers {{ row.header }} but none of this works with db.execute_sql() method.
comment on: http://stackoverflow.com/q/48112466
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48094595
answer count: 2
tagged with: python
tagged with: continued-fractions
tagged with: fractions
downvote count: 3
has answer: http://stackoverflow.com/a/48095912
has body: How would I convert a fraction to a continued fraction in Python? I tried looking around and found people using the Fraction module to do things similar to my problem, but I did not manage to modify them. An example with an image I found: So if the input is 181 101, then the output should be 1 1 3 1 4 4. Thanks ahead!
has comment: http://stackoverflow.com/comment/83163664
upvote count: 0
has title: Convert fraction to continued fraction
score: -3
has comment: http://stackoverflow.com/comment/83163893
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48095912
possible better answer: http://stackoverflow.com/a/58902937
favorite count: 0
has answer: http://stackoverflow.com/a/58902937

http://stackoverflow.com/comment/83293479
comment on: http://stackoverflow.com/a/48145353
type: AnswerComment
score: 1
has text: I modified your answer a bit to make it one-liner. `df = reduce(lambda left,right: pd.DataFrame.combine_first(left,right), [pd.read_csv(f,dtype={'[UPC]': 'str'}).set_index(sch_inx) for f in files])`
type: Comment

http://stackoverflow.com/a/58297482
answers question: http://stackoverflow.com/q/48024654
has body: Change project interpreter to system interpreter file > setting > project > project interpreter > gear icon > system interpretor
score: 0
type: Answer

http://stackoverflow.com/a/48166998
downvote count: 0
type: AcceptedAnswer
upvote count: 2
type: Answer
score: 2
has body: Don't reuse and overwrite function and variable names. You should make sure that lattice returns the array it creates There is some inconsistency. Why does lattice accept N as an argument but nearestneighbours accesses the global variable? def lattice(n): arr = np.random.rand(n, n) arr = np.where(arr &lt;= 0.5, 1, -1) return arr def nearestneighbours(arr, n, x, y): return arr[(x - 1) % n, y] + arr[(x + 1) % n, y] + \ arr[x, (y - 1) % n] + arr[x, (y + 1) % n] N = 5 lat = lattice(5) print nearestneighbours(lat, N, 2, 3) # 0
answers question: http://stackoverflow.com/q/48166766
accepted answer of: http://stackoverflow.com/q/48166766

authentication
tags question: http://stackoverflow.com/q/48126785
tags question: http://stackoverflow.com/q/48158119
tag name: authentication
type: Tag
tags question: http://stackoverflow.com/q/48104013
tags question: http://stackoverflow.com/q/48083155
tags question: http://stackoverflow.com/q/48048955
tags question: http://stackoverflow.com/q/48074834
tags question: http://stackoverflow.com/q/48073834
tags question: http://stackoverflow.com/q/48049498
tags question: http://stackoverflow.com/q/48072563
tags question: http://stackoverflow.com/q/48119389

http://stackoverflow.com/a/48086638
downvote count: 1
has comment: http://stackoverflow.com/comment/83148418
has comment: http://stackoverflow.com/comment/83148358
upvote count: 4
has body: Really simple: print ("\n".join(mylist)) The method str.join uses the string to join an iterable.
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/83148439
has comment: http://stackoverflow.com/comment/83148374
answers question: http://stackoverflow.com/q/48086626
has comment: http://stackoverflow.com/comment/83148381

http://stackoverflow.com/q/48081791
has comment: http://stackoverflow.com/comment/83182851
has title: OpenCV template matching or feature detection to correctly categorize types of faxes?
tagged with: template-matching
has comment: http://stackoverflow.com/comment/83213749
has comment: http://stackoverflow.com/comment/83220209
has comment: http://stackoverflow.com/comment/83220257
has comment: http://stackoverflow.com/comment/83367470
has body: Sorry, this is my first time posting a question. I need a process to identify images within other images to be able to categorize images (ex. sorting faxes based on a company symbol). I have tried openCV template matching but I doesn't seem to be that accurate and if I try to use it by looping through multiple images I cant seem to find a threshold of accuracy that would tell me there is a correct match. I have also tried openCV feature matching with ORB but it seems that my images might not be complex enough so the features get matched all over the page. For template matching I follow the basic code from the documentation: # load the image image, convert it to grayscale, and detect edges template = cv2.imread('PATH TO TEMPLATE IMAGE') template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) template = cv2.Canny(template, 50, 200) (tH, tW) = template.shape[:2] cv2.imshow("Template", template) match_list = [] # loop over the images to find the template in for imagePath in glob.glob('PATH TO DIRECTORY OF IMAGES'): # load the image, convert it to grayscale, and initialize the # bookkeeping variable to keep track of the matched region image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) found = None # loop over the scales of the image for scale in np.linspace(0.2, 1.0, 20)[::-1]: # resize the image according to the scale, and keep track # of the ratio of the resizing resized = imutils.resize(gray, width = int(gray.shape[1] * scale)) r = gray.shape[1] / float(resized.shape[1]) # if the resized image is smaller than the template, then break # from the loop if resized.shape[0] &lt; tH or resized.shape[1] &lt; tW: break # detect edges in the resized, grayscale image and apply template # matching to find the template in the image edged = cv2.Canny(resized, 50, 200) result = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF_NORMED) (minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(result) match_list.append((maxVal, imagePath)) print(match_list) My questions…
has comment: http://stackoverflow.com/comment/83148284
downvote count: 0
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/83365786
has comment: http://stackoverflow.com/comment/83195290
tagged with: opencv
score: 1
tagged with: feature-detection
type: Question

http://stackoverflow.com/q/48117575
tagged with: python
has body: I am seeing partial results with the 'after()' in the main definition however the updated result is not passed on to the main display. Placing a call to the 'after()' specified definition works the same as if the 'after()' syntax wasn't in place. I need the display track to update as changes occur to the database. My intention was to set the interval to 1000. Please help. def commquery(): # Database Call dbi = mdb.connect("localhost", port=3306, user="access", passwd="pass", db="interactive_db") cursor = dbi.cursor() cursor.execute("""SELECT dept,name FROM active""") dbi.commit() row = cursor.fetchall() cpt = 0 for row in row: track.insert('', 'end', values=(row[0], row[1])) cpt += 1 # increment the ID cursor.close() print (cursor) print (row) #root.after(10, commquery) # when uncommented it works but does not update entry def selfupdate(): root.after(20, commquery) # when called it works oncecommtrack = ttk.Treeview(queryFrame) root = Tk() track = ttk.Treeview(queryFrame) track["columns"] = ("one", "two") track.column("one", width=40) track.column("two", width=70) track.configure(show='') track.configure(height='1') track.grid(row=0, column=1, sticky="W", padx=5) selfupdate() # updates the once root.mainloop()
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83211946
has comment: http://stackoverflow.com/comment/83212179
has comment: http://stackoverflow.com/comment/83213187
has comment: http://stackoverflow.com/comment/83211701
type: Question
has comment: http://stackoverflow.com/comment/83213936
has comment: http://stackoverflow.com/comment/83212810
accepted answer: http://stackoverflow.com/a/48157377
has title: How do I get my displayed SQL value update automatically? The 'after()' option does not have the intended results - Tkinter
has comment: http://stackoverflow.com/comment/83213025
score: 0
has comment: http://stackoverflow.com/comment/83212985
answer count: 1
has answer: http://stackoverflow.com/a/48157377
has comment: http://stackoverflow.com/comment/83221060
has comment: http://stackoverflow.com/comment/83211728
has comment: http://stackoverflow.com/comment/83258579
has comment: http://stackoverflow.com/comment/83212528
has comment: http://stackoverflow.com/comment/83211807

http://stackoverflow.com/q/48054343
has comment: http://stackoverflow.com/comment/83085849
score: 0
tagged with: python
tagged with: python-3.x
answer count: 0
has comment: http://stackoverflow.com/comment/83085979
has comment: http://stackoverflow.com/comment/83113709
type: UnansweredQuestion
tagged with: web-scraping
has title: Scrapy: what happens when a crawlspider has multiple callbacks?
tagged with: scrapy
has body: Questions: if I have a Scrapy crawlspider with a callback that does standard link extraction and another that finds relative file paths under the img src tag with xpath, what is happening generally as these functions are executed? Is all of the information relevant to both functions held in memory so there is no need for multiple crawls? Or will the site be crawled multiple times since the callbacks seem to be finding different things (i.e., absolute paths as well as relative paths the standard link extractor doesn't return)? Background: I had a crawlspider that does basic link extraction and another that looks for relative file paths for images under the img src HTML tag. For the sake of efficiency, I just put the two function definitions under the same spider. However, before I pulled the trigger on crawling the target site, I wanted to get a sense for whether this could increase the risk of getting blocked or generally place larger demands on the target site. If, for example, the spider crawled the entire domain twice, that would seem to increase the risk level. But, if I'm correctly interpreting the main response to this question, the crawlspider may hold everything these different functions are scraping in memory such that having multiple callbacks doesn't increase my footprint on the target domain. If I understood a little better what is going on under the hood, I would feel more comfortable before crawling sites where I think there is a legitimate risk of getting banned or something else. Thank you!
type: Question
linked to: http://stackoverflow.com/q/23695716
linked to: http://stackoverflow.com/q/48051158
has comment: http://stackoverflow.com/comment/83085821

http://stackoverflow.com/comment/83112697
score: 0
type: AnswerComment
type: Comment
has text: You may need admin privalages to access the Enchantments.
comment on: http://stackoverflow.com/a/48065090

http://stackoverflow.com/comment/83064988
comment on: http://stackoverflow.com/q/48046729
has text: == is not Boolean , it’s equality ie `__eq__` I don’t think there is anything unpythonic about using it
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/83076373
has text: your current proble can be that you have two findAll` - so finally you have something like `soup.findAll('table',border=1).findAll('tr')`. After you use first `findAll` you have to use `for` loop (`for item in tables:`) and use second `findAll` with every table separatelly - `item.findAll()`.
comment on: http://stackoverflow.com/q/48051371
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/105990991
type: Comment
score: 0
has text: Yes it should be! Thank you
type: AnswerComment
comment on: http://stackoverflow.com/a/52757235

http://stackoverflow.com/q/48050573
has body: I wanna set custom UserAgentMiddleware with scrapy. But I don't know the action of request.headers.setdefault('User-Agent', ua) when I saw it, and I didn't find the method both document of scrapy and requests. Where can I find the any explanation about it?
has comment: http://stackoverflow.com/comment/83073055
accepted answer: http://stackoverflow.com/a/48052076
has title: what's the meaning of request.headers.setdefault() in scrapy
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/48052076
tagged with: python-requests
tagged with: scrapy
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/83054551
has text: BTW, a tuple is constructed by the commas, not the parentheses, the parentheses are only needed in some situations to prevent ambiguity. So you can do, eg `return 0, right`.
comment on: http://stackoverflow.com/a/48041800
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48014929
type: Question
tagged with: python
answer count: 1
has title: Adjusting space in-between subplots
has body: I am plotting 4 subplots in one figure, and I want to adjust the space in-between evenly. I tried grid.GridSpec.update. import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec plt.figure(figsize=(8,8)) gs2 = gridspec.GridSpec(2, 2) gs2.update(wspace=0.01, hspace=0.01) ax1 = plt.subplot(gs2[0,0],aspect='equal') ax1.imshow(img) ax1.axis('off') ax2 = plt.subplot(gs2[0,1],aspect='equal') ax2.imshow(img) ax2.axis('off') ax3 = plt.subplot(gs2[1,0],aspect='equal') ax3.imshow(img) ax3.axis('off') ax4 = plt.subplot(gs2[1,1],aspect='equal') ax4.imshow(img) ax4.axis('off') The vertical space in-between 2 plots is too big, and it does not change no matter how I adjust gs2.update(hspace= ), as shown below:
tagged with: matplotlib
linked to: http://stackoverflow.com/q/42475508
score: 0
has comment: http://stackoverflow.com/comment/82999647
has comment: http://stackoverflow.com/comment/82999557
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82999819
has answer: http://stackoverflow.com/a/48601012

http://stackoverflow.com/a/48174220
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83362078
has body: You can surely do both if you want, the thing is if that is what you need. According to the keras docs: class_weight: Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class. sample_weight: Optional Numpy array of weights for the training samples, used for weighting the loss function (during training only). You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data [...]. So given that you mention that you "have far more of the first class compared to the second" I think that you should go for the class_weight parameter. There you can indicate that ratio your dataset presents so you can compensate for imbalanced data classes. The sample_weight is more when you want to define a weight or importance for each data element. For example if you pass: class_weight = {0 : 1. , 1: 50.} you will be saying that every sample from class 1 would count as 50 samples from class 0, therefore giving more "importance" to your elements from class 1 (as you have less of those samples surely). You can custom this to fit your own needs. More info con imbalanced datasets on this great question. Note: To further compare both parameters, have in mind that passing class_weight as {0:1., 1:50.} would be equivalent to pass sample_weight as [1.,1.,1.,...,50.,50.,...], given you had samples whose classes where [0,0,0,...,1,1,...]. As we can see it is more practical to use class_weight on this case, and sample_weight could be of use on more specific cases where you actually want to give an "importance" to each sample individually. Using both can also be done if the case requires it, but one has to have in mind its cumulative effect. Edit: As per your new question, digging on the Keras source code it seems that i…
has comment: http://stackoverflow.com/comment/83339845
type: Answer
has comment: http://stackoverflow.com/comment/112945146
has comment: http://stackoverflow.com/comment/83348862
has comment: http://stackoverflow.com/comment/83411479
upvote count: 17
score: 17
has comment: http://stackoverflow.com/comment/83339780
accepted answer of: http://stackoverflow.com/q/48173168
has comment: http://stackoverflow.com/comment/112950996
has comment: http://stackoverflow.com/comment/83412058
has comment: http://stackoverflow.com/comment/112950937
answers question: http://stackoverflow.com/q/48173168

http://stackoverflow.com/comment/83285849
score: 0
has text: I don't understand your comment. So do you group all of the lines for a block together or not? If you do group them, and you just want them in a different format, you can do that. So, you stop reading a file as soon you have two distinct block numbers? i.e. block 12 would never be read in the example?
type: Comment
comment on: http://stackoverflow.com/a/48153004
type: AnswerComment

http://stackoverflow.com/comment/83001857
score: 0
has text: Possible duplicate of [Decorators with parameters?](https://stackoverflow.com/questions/5929107/decorators-with-parameters)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48016284

http://stackoverflow.com/comment/83329642
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48173800
has text: @hop Ahh, good point, I skipped over the part about the repeats! Will add to the answer :)

http://stackoverflow.com/q/48143373
tagged with: python-unittest
has title: Why do assert functions in unittest.TestCase have to be member functions?
has answer: http://stackoverflow.com/a/48143426
answer count: 1
downvote count: 0
has body: The assert functions in unittest.TestCase are member functions. It means one has to call them by: self.assertTrue(2 + 2 == 5) instead of something like: unittest.assertTrue(2 + 2 == 5) I found it a bit inconvenient when I want to use those assert functions in another function, for example: import unittest def outside_test(test): test.assertTrue(2 + 2 == 5) class T(unittest.TestCase): def test_something(self): outside_test(self) t = T() t.test_something() I had to pass self into outside_test() to use assertTrue(). Is there any reason for those assert functions to be member functions of unittest.TestCase?
score: 1
has comment: http://stackoverflow.com/comment/83265116
favorite count: 0
accepted answer: http://stackoverflow.com/a/48143426
tagged with: python
type: AnsweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/83265283
type: Question

http://stackoverflow.com/q/48129863
has title: Can't access parent attribute in inherited Python class
has answer: http://stackoverflow.com/a/48130021
tagged with: python
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/48129885
has comment: http://stackoverflow.com/comment/83236496
type: Question
score: 3
has body: This is my parent class, class BaseResource: def __init__(self): self.logger = logging.getLogger(__name__) fmt = '[%(asctime)s] [%(levelname)s] [%(message)s] [--&gt; %(pathname)s [%(process)d]:]' logging.basicConfig(format=fmt, level=logging.DEBUG) def log(self, msg): self.logger.debug(msg) This is my inherited object, class SendOTP(BaseResource): def __init__(self): super(BaseResource, self).__init__() def on_post(self, req, res): self.logger.log("[FAILURE]..unable to read from POST data") This throws up the following error, AttributeError: 'SendOTP' object has no attribute 'logger' What am I doing wrong here.
tagged with: inheritance
has comment: http://stackoverflow.com/comment/83236523
accepted answer: http://stackoverflow.com/a/48129885
has answer: http://stackoverflow.com/a/48130098
answer count: 3
has comment: http://stackoverflow.com/comment/83236516
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48130098

http://stackoverflow.com/a/48160381
accepted answer of: http://stackoverflow.com/q/48160197
answers question: http://stackoverflow.com/q/48160197
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: df.groupby(['Item']).agg({'Item':'first','Sales':'sum','Dept': 'first'}).\ assign(Itemrank=df.Sales.rank(ascending=False,method='min').astype(int) ) Out[64]: Item Dept Sales Itemrank Item 1 1 A 12 3 2 2 A 6 2

http://stackoverflow.com/q/48017347
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48019535
has title: Run function after response has been returned
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
linked to: http://stackoverflow.com/q/34321986
duplicate of: http://stackoverflow.com/q/34321986
type: Question
tagged with: callback
tagged with: flask
score: 0
has body: In Flask, how could I run a function after returning a response for a particular route? For example: # This function takes a long time to run def long_func(): ... @app.route('/') def index(): ... return response If I wanted to run long_func after returning the response for only the index route, how could I do that?

http://stackoverflow.com/comment/83242820
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48132807
score: 0
has text: Done, look at the edit

http://stackoverflow.com/comment/83136575
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48081042
has text: i suspect if there was a fix it would have been mainlined already, do you know if this is a generic pygame bug or a platform specific one? i.e. does it only affect macos? or windows and linux too?

http://stackoverflow.com/comment/83236634
has text: @DejanDozet yes exactly and I need code that checks to see if the amount they want is available
score: 0
comment on: http://stackoverflow.com/q/48129540
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83136458
type: QuestionComment
comment on: http://stackoverflow.com/q/48064415
has text: @sjdh Shouldn't `w = tf.Variable([0.] * order, name="parameters")` be `w = tf.Variable([0.] ** order, name="parameters")`? i.e. with two `*`.
score: 0
type: Comment

http://stackoverflow.com/comment/83026991
score: 0
type: QuestionComment
has text: So I can only make an image PNG or other files (using hardcopy backends) if the plot is larger than the screen, without the capability to display it interactively?
type: Comment
comment on: http://stackoverflow.com/q/48027155

http://stackoverflow.com/comment/83056684
has text: whenever you use sys.path in the file it uses your system filepath reference, so whenever database.py is initiated from any other file, sys.path refers to database.py folder for all its instances. Hence you need to specify ../database to go to go back to database folder from classes folder and. I would suggest you to use import to get the required module from database.py eg: " import classes.database"
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48042835

http://stackoverflow.com/comment/83198751
has text: This is a good suggestion that saves me a lot of difficulty in the future, thanks!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48111503
type: Comment

http://stackoverflow.com/q/48136409
accepted answer: http://stackoverflow.com/a/48137226
downvote count: 1
type: Question
tagged with: ttk
has answer: http://stackoverflow.com/a/48138804
score: -1
has body: i'm trying to start a program with the checkbutton selected but I don't know how to do it. import tkinter as tk from tkinter import ttk root = tk.Tk() v = tk.IntVar() cb = ttk.Checkbutton(root,text='Remember user',onvalue=1,offvalue=0, variable = v);cb.pack()
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/48138804
favorite count: 0
tagged with: tkinter
tagged with: python
type: AnsweredQuestion
has title: python ttk checked checkbutton
has answer: http://stackoverflow.com/a/48137226

http://stackoverflow.com/comment/83041559
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48035748
has text: The same problem is already discussed in this question: https://stackoverflow.com/questions/3170055/test-if-lists-share-any-items-in-python

http://stackoverflow.com/a/48151187
downvote count: 0
has body: Prefix your command with ! to disable the pdb magic. ipdb&gt; !args
answers question: http://stackoverflow.com/q/48151148
type: Answer
upvote count: 11
score: 11
accepted answer of: http://stackoverflow.com/q/48151148
type: AcceptedAnswer

http://stackoverflow.com/comment/83216641
type: AnswerComment
comment on: http://stackoverflow.com/a/48119917
type: Comment
has text: @JohnGordon the OP wants data formatted with no duplicates where there occurs a letter that does not have equal counts in each string.
score: 0

http://stackoverflow.com/comment/83000680
has text: I have so much to learn. Thank you for your time and effort. Your advice worked. Can I ask you, my localhost link to this page is: `http://127.0.0.1:8000/admin/scorecards/daterange/add/`. Is the reason for all the namespacing to get to the change_form.html because the paths need to match the admin?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48015291
type: Comment

http://stackoverflow.com/a/48029669
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48029530
has body: I think you just want a factor plot: import numpy import pandas import seaborn blocks = 3 conditions = 4 trials = 12 ndatapoints = blocks * conditions * trials blockcol = list(range(1, blocks + 1)) * (conditions * trials) concol = list(range(1, conditions + 1)) * (blocks * trials) trialcol = list(range(1, trials + 1)) * (blocks * conditions) valcol = numpy.random.normal(0, 1, ndatapoints) fg = pandas.DataFrame({ 'blocks': blockcol, 'condition': concol, 'trial': trialcol, 'value': valcol }).pipe( (seaborn.factorplot, 'data'), x='blocks', y='value', hue='condition', kind='box' )

http://stackoverflow.com/comment/83202189
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48101696
has text: posted please check and help

http://stackoverflow.com/comment/83266409
comment on: http://stackoverflow.com/q/48135071
score: 0
type: Comment
type: QuestionComment
has text: Please take a look [here](https://stackoverflow.com/questions/26814427/group-result-by-15-minutes-time-interval-in-mongodb). Let me know what you think.

http://stackoverflow.com/a/56622634
has body: I had the same issue, finally figured it out. Instead of using client = MongoClient() client = MongoClient('localhost', 27017) db = client.sampleDB1 Delete all that and try this: mongo1 = PyMongo(app, uri = 'mongodb://localhost:27017/Database1') mongo2 = PyMongo(app, uri = 'mongodb://localhost:27017/Database2') Then, when you want to call a particular database you can use: @app.route('/routenamedb1', methods=['GET']) def get_data_from_Database1(): Database1 = mongo1.db.CollectionName ##Notice I use mongo1, #If I wanted to access database2 I would use mongo2 #Walk through the Database for DC to for s in Database1.find(): #Modifying code return data
upvote count: 5
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/48021748
type: Answer

http://stackoverflow.com/q/48125395
has title: using google APIs with python to make folders encountered error
accepted answer: http://stackoverflow.com/a/48125600
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48125600
tagged with: google-api
tagged with: python
type: AnsweredQuestion
has body: With the help of Tanaike, I can make folders with rest API. But I got error with python code.The error was "https://www.googleapis.com/drive/v3/files?fields=id&amp;alt=json returned "Insufficient Permission">". Here is my code which I referenced here: #!/usr/bin/python #-*- coding:utf-8 -*- import os import httplib2 from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None SCOPES = [ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.file' ] CLIENT_SECRET_FILE = 'client_secret.json' def get_credentials(): home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'googleapis.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) # flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Http()) file_metadata = { 'name': 'movie', 'mimeType':'application/vnd.google-apps.folder' } DRIVE = discovery.build("drive", "v3", http=http) file = DRIVE.files().create(body=file_metadata, fields="id").execute() print(file.get('id')) if __name__ == '__main__': main() Thanks. Please help me!
score: 1
upvote count: 1

http://stackoverflow.com/a/48064085
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48063376
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48063376
has comment: http://stackoverflow.com/comment/83101843
has body: I tried to replicate your problem with ForeignKey on a abstract model, but it seems to work fine with Django version 1.11.1: class BaseModel(models.Model): other = models.ForeignKey('self', null=True, blank=True) class Meta: abstract = True class FirstModel(BaseModel): pass class AnotherModel(BaseModel): pass Using the models: &gt;&gt;&gt; fm1 = FirstModel.objects.create() &gt;&gt;&gt; fm2 = FirstModel.objects.create() &gt;&gt;&gt; &gt;&gt;&gt; fm1.other = fm2 &gt;&gt;&gt; fm1.save() The following assignment to other results in an error: &gt;&gt;&gt; am = AnotherModel.objects.create() &gt;&gt;&gt; am.other = fm1 ValueError: Cannot assign "&lt;FirstModel: FirstModel object&gt;": "AnotherModel.other" must be a "AnotherModel" instance.

http://stackoverflow.com/comment/83282230
type: QuestionComment
score: 0
has text: @Jean-FrançoisFabre hmm, then obviously I had done something else wrong, because it would sometimes give me duplicates. Now, unfortunately, I can't show you exactly what the code used to look like; I don't have a previous version.
comment on: http://stackoverflow.com/q/48151660
type: Comment

http://stackoverflow.com/comment/83261839
has text: Yeah. Wait till that change to _anything_ :)
type: Comment
comment on: http://stackoverflow.com/a/48141900
score: 0
type: AnswerComment

http://stackoverflow.com/q/48138475
type: AnsweredQuestion
score: 1
tagged with: machine-learning
upvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/83254740
has answer: http://stackoverflow.com/a/48139263
accepted answer: http://stackoverflow.com/a/48139263
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83254637
tagged with: neural-network
downvote count: 0
has body: I'm having difficulties with the CartPole problem. The input to the Cart takes either 0 or 1 as input; Either move left or right. Lets say we have a net with 4 inputs plus bias, 3 hidden layers with 1 neuron each and 1 output; where all weights are randomized floats between 0 and 1, and the inputs will also be randomized floats between -10 and 10. Because i chose everything random, I inherently expect the output to be approximately 0.5 on average, and that the cart will go as much right as it goes left. This is not the case; i approximately get 0.63 on average. This leads to big problems, because the cart never decides to go to the left. This seems to be dependent on the amounts of neurons per hidden layer. class NeuralNetwork(object): def __init__(self): self.inputLayerSize = 4 self.hiddenLayerCount = 3 self.hiddenLayerSize = 1 self.outputLayerSize = 1 #Initialize weights self.W = [] self.W.append(np.random.rand(self.inputLayerSize + 1, self.hiddenLayerSize)) for _ in range(self.hiddenLayerCount - 1): self.W.append( np.random.rand(self.hiddenLayerSize, self.hiddenLayerSize)) self.W.append( np.random.rand(self.hiddenLayerSize, self.outputLayerSize)) def forward(self, data): layers = [] data = np.append(data, [1]) #ADD BIAS layers.append(data) for h in range(self.hiddenLayerCount + 1): z = np.dot( layers[h], self.W[h] ) a = sigmoid(z) layers.append(a) return sigmoid( layers[self.hiddenLayerCount + 1] ) I fix the problem by subtracting the output with 0.1, but this is obviously cheating; I see no mathematical reason to use 0.1 as some sort of magic number. I believe I'm approaching the problem wrong, or got some of my code messed up. Any help would be appreciated!
answer count: 1
favorite count: 0
has title: Neural networks: avoid bias in any direction for output
tagged with: python

http://stackoverflow.com/comment/83224776
score: 0
type: Comment
has text: Thank you so much for your reply. I have many files and hence was wondering if the script can be automated so that the prefix takes value starting from 1 till 5000. I am very new to the bash scripts, although i have used some for renaming the fasta headers and splitting the multi-fasta files.
comment on: http://stackoverflow.com/a/48113179
type: AnswerComment

http://stackoverflow.com/comment/83368127
comment on: http://stackoverflow.com/a/48163830
has text: Your suggestion was the fastest way to solve my problem among other suggestions. Thanks!
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48136266
has body: i wrote a script in python to pull out particular paragraphs but then i end up getting all the information in that page. I want to scrap paragraphs inside with varying ids with different pages eg. &lt;div id="content-body-123123"&gt; and this id varies for different pages. How can i identify this particular tag and pull out paragraphs inside this tag alone? url='http://www.thehindu.com/opinion/op-ed/Does-Beijing-really-want-to- ldquobreak-uprdquo-India/article16875298.ece' page = requests.get(url) html=page.content soup = bs(html, 'html.parser') for tag in soup.find_all('p'): print tag.text.encode('utf-8')+'\n'
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
score: 0
tagged with: http://stackoverflow.com/tag/html
has title: article scraping with beautifulsoup: scraping tags inside tags with ids
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83249830
has answer: http://stackoverflow.com/a/48136809
accepted answer: http://stackoverflow.com/a/48136809
tagged with: web-scraping
type: Question

http://stackoverflow.com/q/48129464
answer count: 0
has title: MoviePy + VisPy only saving black screen to .gif
tagged with: moviepy
upvote count: 1
type: Question
downvote count: 0
score: 1
favorite count: 0
type: UnansweredQuestion
has body: I have a script that animates a simple canvas using VisPy (in the "bad" way) successfully. However, when i export the animation to file, whether it's a .gif, or video formats (.MP4, etc) most of the time it produces a completely black image that doesn't change. Other, seemingly random times it does actually save the correct animation. I have literally tried everything I can think of. import vispy import vispy.scene from make_shape import Make_shape from vispy.scene import visuals from vispy import app, gloo from moviepy.editor import VideoClip from vispy.gloo.util import _screenshot # Canvas setup canvas = vispy.scene.SceneCanvas(keys='interactive', show=True, resizable=True) view = canvas.central_widget.add_view() # Initial shape data cube = Make_shape(3) verts = cube.verts() linepos = cube.frame(verts) # Adds initial visuals to shape data # lines can be done as a function with LinePlot scatter = visuals.Markers() lines = visuals.Line() axis = visuals.XYZAxis(parent=view.scene) scatter.set_data(verts, edge_color=None, face_color=(1, 1, 1, .5), size=10) lines.set_data(pos=linepos, connect="segments") view.add(scatter) view.add(lines) # Animation of visuals def update(ev): global verts, scatter verts += 0.0005 linepos = cube.frame(verts) scatter.set_data(pos=verts) lines.set_data(pos=linepos) #Ttime = 5 #intv = 0.000001 #intr = int(Ttime / intv) timer = app.Timer() timer.connect(update) timer.start(interval=.01, iterations=500) # Setup of camera # view.camera = 'turntable' # view.camera = 'perspective' view.camera = 'arcball' view.camera.center = (0.5, 0.5, 0.5) view.camera.distance = 100 #view.camera.set_range(x=(-0.5, 1)) view.camera.fov = (1) # Runs animation if __name__ == '__main__': import sys if sys.flags.interactive != 1: vispy.app.run() # Writes animation to file def make_frame(t): update(t) canvas.on_draw(None) return _screenshot((0, 0, canvas.size[0], canvas.size[1]))[:, :, :3] animation = VideoClip(make_frame, duration=5) animation.write_gif("test_animati…
tagged with: python
tagged with: animated-gif
has comment: http://stackoverflow.com/comment/94137977
tagged with: vispy

http://stackoverflow.com/a/48108676
has comment: http://stackoverflow.com/comment/99943259
type: Answer
has comment: http://stackoverflow.com/comment/83218531
has comment: http://stackoverflow.com/comment/83219583
has body: As Warren Weckesser said, the numpy.cov(X, Y) is a poor fit for the job because it will simply join the arrays in one M by (N+1) array and find the huge (N+1) by (N+1) covariance matrix. But we'll always have the definition of covariance and it's easy to use: A = np.sqrt(np.arange(12).reshape(3, 4)) # some 3 by 4 array b = np.array([[2], [4], [5]]) # some 3 by 1 vector cov = np.dot(b.T - b.mean(), A - A.mean(axis=0)) / (b.shape[0]-1) This returns the covariances of each column of A with b. array([[ 2.21895142, 1.53934466, 1.3379221 , 1.20866607]]) The formula I used is for sample covariance (which is what numpy.cov computes, too), hence the division by (b.shape[0] - 1). If you divide by b.shape[0] you get the unadjusted population covariance. For comparison, the same computation using np.cov: import numpy as np A = np.sqrt(np.arange(12).reshape(3, 4)) b = np.array([[2], [4], [5]]) np.cov(A, b, rowvar=False)[-1, :-1] Same output, but it takes about twice this long (and for large matrices, the difference will be much larger). The slicing at the end is because np.cov computes a 5 by 5 matrix, in which only the first 4 entries of the last row are what you wanted. The rest is covariance of A with itself, or of b with itself. Correlation coefficient The correlation coefficientis obtained by dividing by square roots of variances. Watch out for that -1 adjustment mentioned earlier: numpy.var does not make it by default, to make it happen you need ddof=1 parameter. corr = cov / np.sqrt(np.var(b, ddof=1) * np.var(A, axis=0, ddof=1)) Check that the output is the same as the less efficient version np.corrcoef(A, b, rowvar=False)[-1, :-1]
has comment: http://stackoverflow.com/comment/99942635
upvote count: 7
accepted answer of: http://stackoverflow.com/q/48105922
score: 7
answers question: http://stackoverflow.com/q/48105922
has comment: http://stackoverflow.com/comment/83219171
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83219330

http://stackoverflow.com/comment/83243147
type: Comment
type: QuestionComment
has text: Please watch carefully the question and carefully the answers of what you think is a duplicate, and you'll change your mind
score: 0
comment on: http://stackoverflow.com/q/48132786

http://stackoverflow.com/comment/83043616
score: 0
comment on: http://stackoverflow.com/q/48036468
has text: @UmerNaeem If it did, it would've been an _answer_ as opposed to a comment.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48014905
downvote count: 1
type: Question
has body: I would like to do things like this with a for in a single line, can i do it or i have to use a filter? not 0 &lt;= n &lt;= 255 for n in [-1, 256, 23] # True 0 &lt;= n &lt;= 255 for n in [0, 255, 256] # False 0 &lt;= n &lt;= 255 for n in [0, 24, 255] # True
has comment: http://stackoverflow.com/comment/82998814
answer count: 3
has answer: http://stackoverflow.com/a/48016988
favorite count: 0
tagged with: python-3.x
upvote count: 8
tagged with: python
has answer: http://stackoverflow.com/a/48014969
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48015051
score: 7
has answer: http://stackoverflow.com/a/48015051
accepted answer: http://stackoverflow.com/a/48014969
has title: Python3 - using for loop in a if condition

http://stackoverflow.com/comment/131430229
has text: ...You can work around this limitation by putting the operation in a custom Keras layer `call` and calling that layer on this symbolic input/output.
type: Comment
comment on: http://stackoverflow.com/a/48082967
score: 1
type: AnswerComment

http://stackoverflow.com/q/48053070
has comment: http://stackoverflow.com/comment/83078458
has body: I'm trying to set pgpassword and run pg command in one line but not working, I'm using Windows. os.system('SET PGPASSWORD=admin &amp;&amp; psql -U postgres -c "CREATE DATABASE TEST"') what I got: psql: FATAL: Ident authentication failed for user "postgres" It's weird because it's the password How can I solve this? EDIT: SOLVED cmd1 = 'SET PGPASSWORD=admin' cmd2 = 'psql -U postgres -c "CREATE DATABASE TEST"' os.system(cmd1 + '&amp;&amp;' + cmd2)
downvote count: 0
has comment: http://stackoverflow.com/comment/83078466
favorite count: 0
has title: How to set pgpassword and run postgres command in one line using Python?
tagged with: postgresql
has comment: http://stackoverflow.com/comment/83078592
score: 1
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
type: Question

http://stackoverflow.com/a/48055788
type: AcceptedAnswer
downvote count: 0
has body: I'm not sure if it is what you are looking for, but as long as the subclass has an attribute, even though it's not defined in the baseclass it will be able to access it through the instance. class Base(object): def getValue(self): print(self.myvalue) class Derived(Base): def __init__(self, myvalue): self.myvalue = myvalue val = 3 derived = Derived(3) derived.getValue() #&gt;3
answers question: http://stackoverflow.com/q/48055678
type: Answer
accepted answer of: http://stackoverflow.com/q/48055678
score: 3
upvote count: 3

http://stackoverflow.com/comment/83258421
comment on: http://stackoverflow.com/q/48140194
type: QuestionComment
has text: Use [`random.uniform(-1, 1)`](https://docs.python.org/3/library/random.html#random.uniform)
score: 4
type: Comment

http://stackoverflow.com/q/48049690
answer count: 0
duplicate of: http://stackoverflow.com/q/11144513
has title: Vectorized operations on 2 columns of different dataframes
has comment: http://stackoverflow.com/comment/83071504
type: Question
has comment: http://stackoverflow.com/comment/83071439
linked to: http://stackoverflow.com/q/11144513
score: 0
tagged with: pandas
has body: I have a function func that takes two strings as input and returns an integer as an output. I have two different dataframes and I want to use the 'Name' column of both these dataframes as an input to the function. Suppose, In [12]: DF1 Out[12]: Name 0 Apple 1 Banana 2 Orange and In [13]: DF2 Out[13]: Name 0 Spider 1 Yak 2 Wolf Now, I want use func and provide inputs to it like func('apple','spider') func('apple','yak') func('apple','wolf') func('banana','spider') ... I tried doing this by using itertools but as the dataset is large it is taking a lot of time. So how could it be done using vectorized operations or what would be the most efficient way to do it? edit: I am trying to do something like: for i in DF1['Name']: for j in DF2['Name']: func(i,j)
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/83184727
score: 0
comment on: http://stackoverflow.com/q/48104449
has text: @khelwood, Thank you!
type: Comment
type: QuestionComment

passlib
tag name: passlib
tags question: http://stackoverflow.com/q/48134551
type: Tag

http://stackoverflow.com/a/48141358
has comment: http://stackoverflow.com/comment/83260754
downvote count: 1
upvote count: 0
has body: Looks like the input box is taking a few seconds to load. Try putting a delay before your request: driver.implicitly_wait(3) If that doesn't work, increase the number in parentheses a second at a time. If that solves the problem, you could instead do an explicit wait.
score: -1
answers question: http://stackoverflow.com/q/48141221
type: Answer

http://stackoverflow.com/comment/83116154
comment on: http://stackoverflow.com/q/48070409
has text: @Tom thanks that solved my problem. To help others better understand this: Postgres requires uppercase table / column names to be quoted ([reference](https://stackoverflow.com/a/6331643/6305831)).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48025052
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48024917
has body: x = '8424.aa21.4er9'.replace('.','') print(':'.join(x[y:y+2] for y in range(0, len(x) - 1, 2))) &gt;&gt; 84:24:aa:21:4e:r9 Just iterate through the string once you've cleaned it, and grab 2 string each time you loop through the string. Using range() third optional argument you can loop through every second elements. Using join() to add the : in between the two elements you are iterating.
downvote count: 0
type: Answer

http://stackoverflow.com/q/48095678
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83170538
tagged with: python
has comment: http://stackoverflow.com/comment/83170551
has comment: http://stackoverflow.com/comment/83170759
has comment: http://stackoverflow.com/comment/83169033
answer count: 0
has comment: http://stackoverflow.com/comment/83169177
has body: I am a beginner in python3 I want to copy snippet java file in the middle of other temp file which i gain the address of this file from downloading URL. my problem is when i execute my program i have this error: RESTART: C:/Users/user/AppData/Local/Programs/Python/Python36/refactordwon.py the Url is: ('C:\\Users\\user\\AppData\\Local\\Temp\\tmpq5m7m_og', &lt;http.client.HTTPMessage object at 0x0000003A854879E8&gt;) Traceback (most recent call last): File "C:/Users/user/AppData/Local/Programs/Python/Python36/refactordwon.py", line 14, in &lt;module&gt; file_out = open("path_file" , "r") FileNotFoundError: [Errno 2] No such file or directory: 'path_file' &gt;&gt;&gt; i do not know why? because when i download the url, url shows me this address: the Url is: ('C:\\Users\\user\\AppData\\Local\\Temp\\tmpey3yovte', &lt;http.client.HTTPMessage object at 0x0000002233347978&gt;) i tried to use this address in different way but anyway i have error. i found the temp file and copied in python address. I am sure that i have this file and the address is correct but again i have error that can not find file. could you help me, please?! I hope my question is clear my code is: import urllib.request import os import tempfile #download URL #[------------------------- url = 'http://pages.di.unipi.it/corradini/Didattica/AP-17/PROG-ASS/03/assignment3.html' gt_url = urllib.request.urlretrieve(url) print("the Url is: ") print(gt_url) #--------------------------] #copy sniper java file inside remote file #[-------------------------- path_file =r'C:/Users/user/AppData/Local/Programs/Python/Python36/tmpokv2s_dw' file_out = open("path_file" , "r") file_in = open("snip1.java", "r") file_out.readlines() open("file_back", "w") file_back.write(file_out) pos_fileout = file_back.tell() file_back.seek(pos_fileout) file_back.write(file_in) print("the content of file is: ") file_back.close() file_out.close() file_in.close() open("file_back", "r") file_back.readlines() print(file_back) file_back.close()
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83172474
has title: copy the snippet java file in middle of temp file in python
downvote count: 0

http://stackoverflow.com/q/48154566
has title: Which .pypirc file is used?
answer count: 0
tagged with: pip
tagged with: pypi
type: Question
score: 0
has body: I've created a .pypirc file into my HOME directory (/home/myname/.pypirc) [distutils] index-servers = local [local] repository: xxx username: xxx password: xxx When I run python setup.py register -r local I've got the message ValueError: local not found in .pypirc But when I edit my setup.py by defining _get_rc_file to return ~/.pypirc then the execution is correct. I wonder which .pypirc file is used when I don't define _get_rc_file and how can I find it?
has comment: http://stackoverflow.com/comment/83306055
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83288156

http://stackoverflow.com/a/48160937
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/83301495
answers question: http://stackoverflow.com/q/48160819
upvote count: 0
has comment: http://stackoverflow.com/comment/83301435
has comment: http://stackoverflow.com/comment/83301477
has body: Assume csv looks like name,color,price apple,red,10 banana,yellow,5 import csv with open(file_path, "r") as f: file = csv.reader(f) for line in file: print(line[0], line[1], line[2]) print out would be name color price apple red 10 banana yellow 5
score: -1

http://stackoverflow.com/comment/83283445
has text: @Rohit, I get it. I also develop network applications on the same machine I run the client... but the code assumes anything can happen (the network might crash, the remote machine might disappear, a proxy in the middle got fried, whatever)... sending messages isn't always possible and I always code in timeout detection (usually based on the last time the socket was active).
type: Comment
comment on: http://stackoverflow.com/q/48150823
score: 0
type: QuestionComment

http://stackoverflow.com/a/48063653
score: 1
has comment: http://stackoverflow.com/comment/83125824
has body: If you want to learn and use MySQL, then start without anything above it - no Django, no ORM, not even a Python script. Learn to configure your mysql server (the server process I mean - doesn't have to be on a distinct computer), to work with the command-line mysql client (database creation, tables creations / modifications, adding/updating/deleting rows, and, most important, doing simple and complex queries). While you're at it, learn about proper relational data modeling (normalisations etc) so you fully understand how to design your schemas. Once you're confortable with this, spend some time (should be quite fast at this point) learning to do the same things from python scripts with your python's version mysql connector. Then if you want to learn web development and Django, well go for it. The ORM is quite easy to use when you already have a good understanding of what happens underneath, so by that time you shouldn't have much problems with this part. What you'll still have to learn are the HTTP protocol (trying to do web programming without understanding the HTTP protocol is like trying to win a car race without knowing how to drive a car - it's not technically impossible but it might end up being very painful experience), then front-end stuff (html/css/javascript) and finally the views / templates parts of Django (which should be easy once you know HTTP and html). You can of course jump right in into Django, but you will probably fight with way too many concepts at once and end up spending twice more time to figure out how everything works and why it works that way.
answers question: http://stackoverflow.com/q/48062763
upvote count: 1
has comment: http://stackoverflow.com/comment/83101679
has comment: http://stackoverflow.com/comment/83100977
has comment: http://stackoverflow.com/comment/83101454
has comment: http://stackoverflow.com/comment/83101323
type: Answer
downvote count: 0

http://stackoverflow.com/a/48038595
has body: If I understand your question, it looks like you may want to merge() the results of your csv files, instead of concat() them together. import pandas as pd m1 = pd.read_csv('metadata1.csv') m2 = pd.read_csv('metadata2.csv') mm = pd.merge(m1, m2, how='outer', on='Sample_name') # Cleanup to merge duplicate non-index column mm['TITLE'] = mm'TITLE_x', 'TITLE_y'.fillna('').sum(axis=1) mm.drop(['TITLE_x','TITLE_y'], axis=1, inplace=True) # Replace NaN if you desire mm.fillna('Missing:Not Applicable') You can find out more about merge() and how to do joins here if you want to adjust the results you are getting to match your requirements better: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html Hope that helps.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48037627
has comment: http://stackoverflow.com/comment/83177006

http://stackoverflow.com/comment/83227282
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48125239
has text: `./bin/python` starts Python3's shell or Python2.7's ? Please check

http://stackoverflow.com/q/48115779
score: 0
answer count: 1
has body: Python 3.6 and Django 1.11 I am sending from a client multipart/form-data to a Django form, the model looks like class Document(models.Model): name = models.CharField(max_length=300) author = models.CharField(max_length=100) file = models.FileField(upload_to='files/') and I am using class based views class DocumentCreate(CreateView): model = Document form_class = DocumentForm success_url = reverse_lazy('document_list') and a classic ModelForm: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' I'm on the embedded server, which I know may perform poorly, but when I send a 2gb files with the client, is see that the file is created after ~10 seconds (and databases entries etc..) but the client have to wait 10 more seconds for the Django server to send the response (seen with Wireshark). I can even keyboardinterupt the client script before the Django server answer, with no consequences to the data transmission. Here is the client script in gross: fich = open('2go', 'rb') sess = requests.session() data = {'author': 'gerard', 'csrfmiddlewaretoken': csrftoken, 'name': 'gerard'} sess.post('http://127.0.0.1:8000/post_document', data=data, files{'file': fich}) I got another script which streams the multipart data, but its slower and also have to wait for the server response. So the question is, why is the server answer so slow, although everything is already uploaded?
accepted answer: http://stackoverflow.com/a/48116431
tagged with: python
type: AnsweredQuestion
has title: Django slow server response with large file upload
tagged with: django
type: Question
has answer: http://stackoverflow.com/a/48116431

http://stackoverflow.com/comment/83156970
type: QuestionComment
comment on: http://stackoverflow.com/q/48090962
has text: @Silencer The meaning is that if there is no backup, there is no way to find it?
score: 0
type: Comment

http://stackoverflow.com/a/48158647
has comment: http://stackoverflow.com/comment/83296965
has comment: http://stackoverflow.com/comment/83297086
has comment: http://stackoverflow.com/comment/83330093
has comment: http://stackoverflow.com/comment/83367813
type: Answer
has comment: http://stackoverflow.com/comment/83297168
accepted answer of: http://stackoverflow.com/q/48157533
has comment: http://stackoverflow.com/comment/83383335
has comment: http://stackoverflow.com/comment/83297014
has comment: http://stackoverflow.com/comment/83368499
has body: Seems the fileinput module may be causing issues with correctly writing the file output, but I am not sure how that module works so I cannot suggest how to use it. The main correction may be to use different file handler pointers for reading the input file and writing to the output file (don't reuse f as mentioned in the comments). Here's some refactoring of your original code: from __future__ import print_function import linecache from random import choice from string import digits, ascii_lowercase import random, string from collections import defaultdict L = ''.join([random.choice(string.ascii_letters + string.digits) for n in xrange(10)]) print(L) total_count = defaultdict(lambda: 0) with open("input.txt", 'r') as f: for line in f: ok = line.strip() if int(line) &gt; 6: total_count[int(line)] += 1 with open('output.txt', 'a' ) as ff: ff.write( str(ok) + " " + str(L) + '\n') infile_contents = [] outfile_contents = [] # get list of input.txt contents with open('input.txt', 'r') as infile: for line in infile.readlines(): infile_contents.append(line.strip()) # get list of output.txt first column contents with open('output.txt', 'r') as outfile: for line in outfile.readlines(): outfile_contents.append(line.split()[0]) # dictionary to hold count of occurrences totals = {} # count occurrences for num in infile_contents: totals[num] = outfile_contents.count(num) # print counts for item in totals.items(): print('{num} appears {count} times.'.format(num=item[0], count=item[1])) Example output after running script twice: vlVHVi3t9L 55 appears 2 times. 99 appears 2 times. 42 appears 2 times. 65 appears 2 times. 49 appears 4 times.
answers question: http://stackoverflow.com/q/48157533
has comment: http://stackoverflow.com/comment/83368564
has comment: http://stackoverflow.com/comment/83297400
has comment: http://stackoverflow.com/comment/83330346
has comment: http://stackoverflow.com/comment/83299061
has comment: http://stackoverflow.com/comment/83333294
has comment: http://stackoverflow.com/comment/83333985
has comment: http://stackoverflow.com/comment/83368438
score: 0
has comment: http://stackoverflow.com/comment/83368654
has comment: http://stackoverflow.com/comment/83367647
has comment: http://stackoverflow.com/comment/83297991
has comment: http://stackoverflow.com/comment/83378938
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83378957
has comment: http://stackoverflow.com/comment/83297875
has comment: http://stackoverflow.com/comment/83333873

http://stackoverflow.com/comment/83219067
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48121168
has text: the other option would be to pop a department each time and pass the remaining ones on to the next instance, but I couldn't think of how to pass the remaining values from an instance that gets destroyed
score: 0

http://stackoverflow.com/comment/83255008
score: 0
type: QuestionComment
type: Comment
has text: Possible duplicate of [How to search for a string in text files?](https://stackoverflow.com/questions/4940032/how-to-search-for-a-string-in-text-files)
comment on: http://stackoverflow.com/q/48138209

http://stackoverflow.com/q/48087010
type: Question
has comment: http://stackoverflow.com/comment/83148990
has comment: http://stackoverflow.com/comment/83149726
has answer: http://stackoverflow.com/a/48087477
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83150268
has body: I build a tree based on a directed graph. The source data is a series of parent child relationships in an SQL table. It's guaranteed to be a tree (which I verify anyway). I want the set of simple paths from the root to each leaf. The data is headers in an accounting "chart of accounts", and the paths will look like "Root -> Assets -> Current Assets -> Receivables -> Trade Debtors" where 'Trade Debtors' is the actual account. At the moment, I collect the leaf IDs (the actual accounts) as I build the graph. I can do this because they are identified by certain attributes in the data. Then I iterate: for leaf in detail_or_bank_accts: paths_to_detail_or_bank_accts.append(list(nx.all_simple_paths(G,0,leaf))) But lucky for me that I know the leaf nodes. Is there a more elegant way of doing this?
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/48087477
tagged with: python
has comment: http://stackoverflow.com/comment/83149072
tagged with: networkx
has title: python networkx: simple way to get all simple paths from root to leaf
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/83010026
type: Comment
type: QuestionComment
has text: I just edited the original post to include more detail!
score: 0
comment on: http://stackoverflow.com/q/48020296

http://stackoverflow.com/q/48025628
has answer: http://stackoverflow.com/a/48025748
has title: Default values in inheritance classes in python
downvote count: 0
tagged with: inheritance
has comment: http://stackoverflow.com/comment/83020796
tagged with: class
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83020779
accepted answer: http://stackoverflow.com/a/48025748
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 2
has body: I have two classes. Where the Parent class has some default values. I would like the Child class to inherit the init() method of the Parent class and also the default values. However, when I try to change the values of the optional arguments, I can't do it. For example, in the code below, I can't change the value of year_born. def get_current_age(x): return 2017-x get_age = get_current_age class Parent(): def __init__(self,name,last_name, siblings=0, year_born=1900, age=get_age): self.name = name self.last_name = last_name self.siblings = siblings self.year_born=year_born self._get_age = get_age(self.year_born) class Child(Parent): def __init__(self,name,last_name, siblings=0, year_born=1900, age=get_age): super().__init__(name,last_name, siblings=0, year_born=1900, age=get_age) self.lives_with_parent= True self.stil_in_school= None When I create instances of the Parent class with the default values, the output is ok. When I create a Child instance with a different value for age, it still takes the default value. Dad=Parent('Fyodr','Dosto') print('Dad is' ,Dad._get_age) kid = Child('Joseph','Dosto', year_born=2000) print('Kid is' ,kid._get_age) Dad is 117 Kid is 117 I don't know if you have any other ideas of how to fix this or write it in a better way. Many thanks,
has comment: http://stackoverflow.com/comment/83020859
type: Question

http://stackoverflow.com/comment/83306488
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48163642
has text: yes I can :), but page turning seems, strange it's using + 20 each time, so page 1 = 0, page 2 = 20, page 3 = 40, page 4 = 60 and so on
score: 0

http://stackoverflow.com/a/48091136
has comment: http://stackoverflow.com/comment/83156551
type: Answer
has body: Another solution than regex is flashtext, this will be faster if you have more number of keywords i.e from flashtext import KeywordProcessor keyword_processor = KeywordProcessor() keyword_processor.add_keywords_from_list(df['procedure'].str.split().sum()) df2[df2['procedure'].apply(keyword_processor.extract_keywords).str.len()&gt;1] s.no procedure 0 1 kalai has a recruitment group 1 2 shiva is the network person in my office 3 4 anand is the database here 5 6 jana is working in the audit team To know more about this library and its speed you can check here Further Reading : Docs Regex was taking 5 days to run. So I built a tool that did it in 15 minutes. There is a need for easy interface via pandas, lets wait till its done.
downvote count: 0
answers question: http://stackoverflow.com/q/48090657
score: 1
has comment: http://stackoverflow.com/comment/83162323
has comment: http://stackoverflow.com/comment/83156516
upvote count: 1

http://stackoverflow.com/comment/83294395
score: 1
comment on: http://stackoverflow.com/q/48157476
type: Comment
type: QuestionComment
has text: Yes. Look into [broadcasting](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html), and then try `(x[:, None, :] == y).all(axis=-1)`. However, this is time efficient but not particularly space efficient (though in this particular case we're only talking about needing on the order of 10MB of space). Are you primarily worried about space efficiency or time efficiency? How large will `n` get in practice?

http://stackoverflow.com/comment/83028482
score: 0
type: Comment
type: QuestionComment
has text: @Isma I'm not trying to hide a window, but changing it into an irregular shape. Modifying question to make that clearer
comment on: http://stackoverflow.com/q/48029084

http://stackoverflow.com/q/48047276
has title: Makefile for Running Django Backend and React Frontend
tagged with: django
has answer: http://stackoverflow.com/a/48047401
type: Question
upvote count: 2
tagged with: reactjs
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I am working on a project which is developed by Django REST Framework and served by React app. There is a partition between the back end and front end. The structure of the path is: Root ├── backend ├── frontend ├── makefile ├── readme.md ├── requirements.pip └── venv Currently, I run the project by opening two different terminals. Then I start the django server first and then start the react app. In terminal 1, I start the django server: cd backend python manage.py runserver In terminal 2, I start the react app: cd frontend npm start So, it is quite irritating to redo these commands each time to run the project. Recently, I have heard about makefile. I think this will reduce the number of commands to start the project. I have created the following makefile: run: python backend/manage.py runserver cd frontend npm start When I write make run it successfully starts the Django server but it does not start the React application. What am I missing here? Can I run the both commands in a single command using make? Update: Problem is solved. The updated makefile contains: django: bash -c "python backend/manage.py runserver" react: bash -c "cd frontend &amp;&amp; npm start" run: make django &amp; make react
tagged with: makefile
tagged with: python
accepted answer: http://stackoverflow.com/a/48047401
score: 2
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/83001186
type: QuestionComment
has text: More than likely one of them is a shadow copy of the other, please provide how these items are defined.
comment on: http://stackoverflow.com/q/48015960
score: 1
type: Comment

http://stackoverflow.com/comment/83556481
type: Comment
has text: Updated my Answer with some more inputs. Now `webdriver` being a **W3C Recomendation Candidate** and the initialization and destroy process being **much cleaner** I don't see any necessity to wrap up the `initialization` in a `while-try-except loop`. We are in a position to deal with each error outcome.
comment on: http://stackoverflow.com/a/48077973
score: 0
type: AnswerComment

http://stackoverflow.com/a/48039823
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48039361
has comment: http://stackoverflow.com/comment/83050202
has body: I seem to fail the understand the issue... When you do this: class SuperC(): def __init__(self, a, b, c, d='D0'): self.A = a self.B = b self.C = c self.D = d self.E = 'E0' self.E is not "hidden". It just received a hardcoded value: the string "E0" and d='D0' can be read as If you're called with an specific value in the d argument, use that one, otherwise, just use the string "D0" (it's a named optional argument) When you do this: class SubC3(SuperC): def __init__(self, a, b, c, f, d='new D', e='new E'): super().__init__(a, b, c) self.D = d # set new self.E = e # set new self.F = f What's happening is that the call to super().__init__ creates a class with whatever a, b, c arguments you passed, a self.E and the hardcoded "E0". After that, you do self.E = e and then you overwrite that "E0" with the value of the argument e. Try this: class SubC3(SuperC): def __init__(self, a, b, c, f, d='new D', e='new E'): super().__init__(a, b, c) print("Before overwrite=%s" % self.E) self.D = d # set new self.E = e # set new print("After overwrite=%s" % self.E) self.F = f sub3 = SubC3('A3', 'B3', 'C3', 'F3') You'll see that right after the init, you see self.E being "E0" and then it's overwritten: Before overwrite=E0 After overwrite=new E About the d: Try this: class SubC3(SuperC): def __init__(self, a, b, c, f, d='new D', e='new E'): super().__init__(a, b, c) self.E = e # set new self.F = f sub3 = SubC3('A3', 'B3', 'C3', 'F3') print(sub3.D) You'll see that it's D0, because you didn't pass any d to the super and you didn't overwrite it in SubC3.__init__, so it used the default in the SuperC.__init__ (where you do d='D0')
has comment: http://stackoverflow.com/comment/83050131
answers question: http://stackoverflow.com/q/48039361
type: AcceptedAnswer
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/83050106

http://stackoverflow.com/comment/83240365
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48131527
has text: ok ... I'm not getting an error message anymore ... but the column is not dropped either

http://stackoverflow.com/a/48160002
has comment: http://stackoverflow.com/comment/83301728
answers question: http://stackoverflow.com/q/48159341
type: Answer
has body: This is a bug. A KeyError should be raised when using .loc[list-of-labels] if none of the labels are present. Per the docs, .loc[list-of-labels] will raise in the future if any labels are missing.
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48159341

http://stackoverflow.com/comment/83055582
type: QuestionComment
has text: If so, how should I separate the data values and assign each one to a variable, preferably inside the neuron class.@PeterLeimbigler
comment on: http://stackoverflow.com/q/48037509
score: 0
type: Comment

datetime
tags question: http://stackoverflow.com/q/48135843
tags question: http://stackoverflow.com/q/48154924
tags question: http://stackoverflow.com/q/48156752
tags question: http://stackoverflow.com/q/48136101
tags question: http://stackoverflow.com/q/48151024
tags question: http://stackoverflow.com/q/48016382
tags question: http://stackoverflow.com/q/48091504
tags question: http://stackoverflow.com/q/48161758
tags question: http://stackoverflow.com/q/48138003
tags question: http://stackoverflow.com/q/48150555
tags question: http://stackoverflow.com/q/48139087
tags question: http://stackoverflow.com/q/48153359
tags question: http://stackoverflow.com/q/48155048
tags question: http://stackoverflow.com/q/48130188
tags question: http://stackoverflow.com/q/48047935
tags question: http://stackoverflow.com/q/48144727
tags question: http://stackoverflow.com/q/48051100
tags question: http://stackoverflow.com/q/48123648
tags question: http://stackoverflow.com/q/48155787
tags question: http://stackoverflow.com/q/48144684
tags question: http://stackoverflow.com/q/48061022
tags question: http://stackoverflow.com/q/48100435
tags question: http://stackoverflow.com/q/48161024
tags question: http://stackoverflow.com/q/48073528
tags question: http://stackoverflow.com/q/48046647
tags question: http://stackoverflow.com/q/48046121
tags question: http://stackoverflow.com/q/48143307
tags question: http://stackoverflow.com/q/48143892
tag name: datetime
tags question: http://stackoverflow.com/q/48129251
tags question: http://stackoverflow.com/q/48088917
tags question: http://stackoverflow.com/q/48101815
tags question: http://stackoverflow.com/q/48116760
tags question: http://stackoverflow.com/q/48122046
tags question: http://stackoverflow.com/q/48052962
tags question: http://stackoverflow.com/q/48060775
tags question: http://stackoverflow.com/q/48145974
tags question: http://stackoverflow.com/q/48090043
tags question: http://stackoverflow.com/q/48037799
type: Tag
tags question: http://stackoverflow.com/q/48058304
tags question: http://stackoverflow.com/q/48124946
tags question: http://stackoverflow.com/q/48071339
tags question: http://stackoverflow.com/q/48168209
tags question: http://stackoverflow.com/q/48116067
tags question: http://stackoverflow.com/q/48140782
tags question: http://stackoverflow.com/q/48076220
tags question: http://stackoverflow.com/q/48168862
tags question: http://stackoverflow.com/q/48035105
tags question: http://stackoverflow.com/q/48019561
tags question: http://stackoverflow.com/q/48067036
tags question: http://stackoverflow.com/q/48027527

cors
type: Tag
tag name: cors
tags question: http://stackoverflow.com/q/48058178

http://stackoverflow.com/a/48082398
type: AcceptedAnswer
downvote count: 0
has body: Data input: df1=pd.DataFrame({'Line':[1,1,1],'Point':[2,3,4],'Res':[1,2,3]}) df2=pd.DataFrame({'Line':[1,2,3],'Point':[2,3,4],'Res':[1,2,3]}) df3=pd.DataFrame({'Line':[3,3,3],'Point':[4,3,4],'Res':[1,2,3]}) We using reduce merge outer l=[df1,df2,df3] import functools functools.reduce(lambda left,right: pd.merge(left,right,on=['Line','Point'],how='outer'), l) Out[228]: Line Point Res_x Res_y Res 0 1 2 1.0 1.0 NaN 1 1 3 2.0 NaN NaN 2 1 4 3.0 NaN NaN 3 2 3 NaN 2.0 NaN 4 3 4 NaN 3.0 1.0 5 3 4 NaN 3.0 3.0 6 3 3 NaN NaN 2.0
has comment: http://stackoverflow.com/comment/83168695
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48082257
score: 1
accepted answer of: http://stackoverflow.com/q/48082257
has comment: http://stackoverflow.com/comment/83143352

http://stackoverflow.com/q/48169520
favorite count: 0
has title: Neo4j as data source for pyspark
type: UnansweredQuestion
tagged with: python
has body: I have a requirement wherein I've to pull data from Neo4j and create Spark RDD's out of that data. I'm using Python in my project. There is this connector for the same purpose but it's written in Scala. So I can think of following workarounds for now - Query data from neo4j in small chunks/batches, convert each chunk to Spark RDD using parallize() method. Finally merge/combine all the RDD's using union() method to get single RDD. And then I can do transformations &amp; actions on them. Another approach is to read data from Neo4j and create a Kafka producer out of it. Then use Kafka as a data source for Spark. e.g. Neo4j -> Kafka -> Spark I want to know that which one is more efficient for large chunks of data? and if there is any better approach for solving this problem, please help me out with that. Note: I do tried to extend pyspark API in order to create custom RDD in python. pyspark is API is very different as compared to Spark's Scala/Java API. In case of Scala API's, custom RDD can be created by extending RDD class and overriding compute() and getPartitions() methods. But in pyspark API, I couldn't find compute() under RDD class in rdd.py
score: 2
downvote count: 0
type: Question
tagged with: apache-kafka
tagged with: pyspark
has answer: http://stackoverflow.com/a/48176376
upvote count: 2
tagged with: apache-spark
answer count: 1
tagged with: neo4j

http://stackoverflow.com/q/48134179
tagged with: tensorflow
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/48134756
accepted answer: http://stackoverflow.com/a/48134756
has title: Trained model detects almost everything as one class after a long training
upvote count: 1
answer count: 1
tagged with: object-detection
favorite count: 0
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
score: 1
has body: I trained a custom person detector using Tensorflow and Inception's pretrained model then after a few thousands of step and an average of 2-1 loss, I've stopped the training and tested it with a live video. The result was quite good and only gets few false positives. It can detect some person but not everyone so I decided to continue on training the model until I get an average loss of below 1 then tested it again. It now detects almost everything as a person even the whole frame of the video even when there is no object present. The models seems to work great on pictures but not on videos. Is that an overfitting? Sorry I forgot how many steps it is. I accidentally deleted the training folder that contains the ckpt and tfevents. edit: I forgot that I am also training the same model with same dataset but higher batch size on a cloud as a backup which is now on a higher step. I'll edit the post later and will provide the infos from tensorboard once I've finished downloading and testing the model from the cloud. edit2: I downloaded the trained model on 200k steps from the cloud and it is working, it detects persons but sometimes recognizes the whole frame as "person" for less than a second when I am moving the camera. I guess this could be improved by continuing on training the model. Total Loss on tensorboard For now, I'll just continue the training on the cloud and try to document every results of my test. I'll also try to resize some images on my dataset and train it on my local machine using mobilenet and compare the results from two models.

http://stackoverflow.com/q/48149081
has comment: http://stackoverflow.com/comment/83276571
has title: How would I divide one list/array by another?
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83276352
has answer: http://stackoverflow.com/a/48149246
accepted answer: http://stackoverflow.com/a/48149246
linked to: http://stackoverflow.com/q/1663807
answer count: 2
possible better answer: http://stackoverflow.com/a/48149300
downvote count: 0
has answer: http://stackoverflow.com/a/48149300
has comment: http://stackoverflow.com/comment/83276424
has body: For example, I have gathered a list of the lowest numbers of a list and I need to divide them by each other but repeat themselves down the list similar to a Cartesian product. Not exact code below, but similar. Exact code would just be confusing if I posted it. lowestnumbers = [2,3,4,5,6,7,8] highestnumbers = [2,3,4,5,6,7,8] for matchhigh in highestnumbers: print (matchhigh) for matchlow in lowestnumbers: print (matchlow) percentage = (matchlow / matchhigh - 1.0) print (percentage) When I've done this, it repeats the last number of from "matchhigh" and repeatedly divides itself by that last number. I need something to do something along the lines of below and I'm completely lost. list1 = [1,2,3] list2 = [3,2,1] for number in list1 answer = number / list2 print = answer Desired Output: 0.3333333333333333 0.5 1 0.6666666666666667 1 2 1 1.5 3 Please let me know if there is a solution to the issue I am having, it's driving me insane.
favorite count: 0

http://stackoverflow.com/a/48024992
upvote count: 1
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/83020192
has comment: http://stackoverflow.com/comment/83021150
has comment: http://stackoverflow.com/comment/83020386
has comment: http://stackoverflow.com/comment/83020056
accepted answer of: http://stackoverflow.com/q/48024319
has comment: http://stackoverflow.com/comment/83019859
has comment: http://stackoverflow.com/comment/83020240
answers question: http://stackoverflow.com/q/48024319
has body: You have not tried using the Django message framework. Look: Adding a message To add a message, call: from django.contrib import messages messages.add_message(request, messages.INFO, 'Hello world.') Some shortcut methods provide a standard way to add messages with commonly used tags (which are usually represented as HTML classes for the message): messages.debug(request, '%s SQL statements were executed.' % count) messages.info(request, 'Three credits remain in your account.') messages.success(request, 'Profile details updated.') messages.warning(request, 'Your account expires in three days.') messages.error(request, 'Document deleted.') Displaying messages get_messages(request)[source] In your template, use something like: {% if messages %} &lt;ul class="messages"&gt; {% for message in messages %} &lt;li{% if message.tags %} class="{{ message.tags }}"{% endif %}&gt;{{ message }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} If you’re using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context. Even if you know there is only just one message, you should still iterate over the messages sequence, because otherwise the message storage will not be cleared for the next request. The context processor also provides a DEFAULT_MESSAGE_LEVELS variable which is a mapping of the message level names to their numeric value: {% if messages %} &lt;ul class="messages"&gt; {% for message in messages %} &lt;li{% if message.tags %} class="{{ message.tags }}"{% endif %}&gt; {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %} {{ message }} &lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} EDIT: def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): userObj = form.cleaned_data username = userObj['username'] email = userObj['email'] password1 = userObj['password1'] password2 = userObj['password2'] if password1 != password2: message…
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/83020835

http://stackoverflow.com/comment/83032784
score: 0
has text: mm yes i import tabula
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48031163

http://stackoverflow.com/q/48036114
has answer: http://stackoverflow.com/a/48078277
has title: How can I grab Coordinates and TimeStamp of Twitter tweets in specific bounding box with Python/Tweepy?
tagged with: twitter
type: Question
tagged with: location
score: 0
answer count: 1
has body: I am trying to extract tweet locations from a specific area with python using tweepy + writing it into a csv-file. I am not very much into python but I could manage to put together the following sript which kind of works: import json from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener #Enter Twitter API Key information consumer_key = 'cons_key' consumer_secret = 'cons_secret' access_token = 'acc_token' access_secret = 'acc-secret' file = open("C:\Python27\Output2.csv", "w") file.write("X,Y\n") data_list = [] count = 0 class listener(StreamListener): def on_data(self, data): global count #How many tweets you want to find, could change to time based if count &lt;= 100: json_data = json.loads(data) coords = json_data["coordinates"] if coords is not None: print coords["coordinates"] lon = coords["coordinates"][0] lat = coords["coordinates"][1] data_list.append(json_data) file.write(str(lon) + ",") file.write(str(lat) + "\n") count += 1 return True else: file.close() return False def on_error(self, status): print status auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) twitterStream = Stream(auth, listener()) #What you want to search for here twitterStream.filter(locations=[11.01,47.85,12.09,48.43]) the problem is, that it extracts the coordinates very slowly (like 10 entries per 30 minutes). Would there be a way to make this faster? How can I add the timestamps for each tweet? Is there way to make sure to retrieve all tweets possible for the specific region (I guess the max is all tweets of the past week)? thanks very much in advance!
type: UnansweredQuestion
tagged with: python
tagged with: tweepy
tagged with: timestamp

http://stackoverflow.com/a/56837893
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48170388
upvote count: 1
type: Answer
has body: Based on the docs, you need to use delegated_credentials = credentials.create_delegated('user_to_impersonate@mycompany.com') instead of delegated_credentials = credentials.create_delegated('myproject@myproject-123456.iam.gserviceaccount.com').

http://stackoverflow.com/a/48098126
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48097995
has body: you can use plt.subplots_adjust(left=0.09, bottom=0.07, right=0.98, top=0.97, wspace=0.2 , hspace=0.17 ) to adjust the window. But the issue is that a lot of the space in your plot is empty maybe you should change plt.subplot2grid((4,3)... to plt.subplot2grid((2,2)
type: Answer

http://stackoverflow.com/comment/124483566
type: AnswerComment
has text: amazing thanks!!!!
type: Comment
score: 2
comment on: http://stackoverflow.com/a/67139316

http://stackoverflow.com/comment/130298800
type: AnswerComment
type: Comment
score: 2
comment on: http://stackoverflow.com/a/62925227
has text: Another thing you should note: If you're trying to create the fist migration, the database you're connecting with **must be empty**. You may connect to a temp db to generate the migration and then switch back.

http://stackoverflow.com/comment/83175109
type: QuestionComment
has text: No problem! I wouldn't expect you to find that question, it takes me a minute to find it and I already know it's there. I renamed the title of the duplicate target, hopefully it will be easier to find in future.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48099340

http://stackoverflow.com/comment/83006526
comment on: http://stackoverflow.com/q/48018686
has text: @MukulSharma that doesn't help me too much. I could manually create the copies, it's being able to address them with a variable that I'm looking for.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48029683
has body: I'm trying to learn Python, upon following an exercise I get the following error: SyntaxError: keyword can't be an expression on the following line: boton = Button(ventanita.text="Evento",command=parpadeo) No idea what that means, any help is appreciated.
has comment: http://stackoverflow.com/comment/100538406
tagged with: syntax
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/48029730
has comment: http://stackoverflow.com/comment/83029528
type: Question
has answer: http://stackoverflow.com/a/48029731
has comment: http://stackoverflow.com/comment/83029523
score: -2
has title: SyntaxError: keyword can't be an expression Python 3.6.3
has comment: http://stackoverflow.com/comment/83029588
answer count: 2
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83029517
linked to: http://stackoverflow.com/q/11633421

http://stackoverflow.com/q/48090426
answer count: 1
tagged with: gensim
tagged with: nlp
favorite count: 0
downvote count: 2
tagged with: machine-learning
tagged with: python
has title: AttributeError: 'list' object has no attribute 'words' in python gensim module
has comment: http://stackoverflow.com/comment/90091346
accepted answer: http://stackoverflow.com/a/48248532
type: AnsweredQuestion
upvote count: 3
score: 1
type: Question
tagged with: doc2vec
has comment: http://stackoverflow.com/comment/83479824
has answer: http://stackoverflow.com/a/48248532
has body: While training using doc2vec, I got this error: AttributeError: 'list' object has no attribute 'words' in python gensim module This is my code: # Extracting titles from csv to list with open(query+'_titles.csv', 'rb') as f: reader = csv.reader(f) titlelist = list(reader) # build model = doc2vec.Doc2Vec(size=30, window=1, alpha=0.01, min_count=2, sample=1e-5, workers=100) model.build_vocab(titlelist) titlearray = np.asarray(titlelist) print 'Training Model...' I use python 2.7.11 and gensim version is 3.2.0 if that helps. There must be something I am really missing.

http://stackoverflow.com/comment/83200592
has text: @d-coder If you want to write an answer that improves the OP's code, with explanations, go ahead. You'll probably score an upvote or two. ;)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48112343
type: QuestionComment

http://stackoverflow.com/comment/83141059
type: Comment
type: QuestionComment
has text: Fancy indexing is probably the wrong term here.
comment on: http://stackoverflow.com/q/48083226
score: 0

http://stackoverflow.com/comment/83103589
type: Comment
comment on: http://stackoverflow.com/q/48065070
score: 0
has text: Yes. I am picking up python, and still learning the nuances. That was the answer I needed. Thank You.
type: QuestionComment

http://stackoverflow.com/q/48108787
tagged with: python-3.x
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48108894
has body: Here I have dictionary like d_ = {"k3":(2,3), "k1":(4,5), "k5":(8,9), "k2":(6,8), "k4":(2,7)} I have to sort this based on descending order of first value in the tuples. I am doing this: sorted(d_.items(), key=d_.get(1) , reverse=True) But I am getting this: [('k5', (8, 9)), ('k4', (2, 7)), ('k3', (2, 3)), ('k2', (6, 8)), ('k1', (4, 5))] The Output should look like this: [("k5",(8,9)),("k2",(6,8)),("k1",(4,5)),("k3",(2,3)),("k4",(2,7))]
type: AnsweredQuestion
downvote count: 1
has title: How to sort a dictionary based on values with tuple
type: Question
has comment: http://stackoverflow.com/comment/83192744
accepted answer: http://stackoverflow.com/a/48108894
possible better answer: http://stackoverflow.com/a/48110637
score: -1
tagged with: sorting
has answer: http://stackoverflow.com/a/48110637
answer count: 2
upvote count: 0
favorite count: 0

http://stackoverflow.com/comment/83306814
has text: @georgexsh I could but, how do I change the protocol? Is it just changing the port or do I have to do something else?
score: 0
comment on: http://stackoverflow.com/q/48158110
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82999550
has text: Are you mixing up extrapolate and interpolate?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48015191

http://stackoverflow.com/comment/139157708
type: AnswerComment
comment on: http://stackoverflow.com/a/78872221
type: Comment
has text: I do however like your picture, which I assume is a gifted Blender-render of foliage in fall.
score: 1

http://stackoverflow.com/comment/83298262
has text: It should be `import the_py_file_in_the_same_directory_of_this_script_that_has_PageTwo as an_abbreviation` then use the `PageTwo` class in `an_abbreviation.PageTwo(parent, controller)` or `from the_py_file_in_the_same_directory_of_this_script_that_has_PageTwo import PageTwo` to be used like `PageTwo(parent, controller)`.
comment on: http://stackoverflow.com/q/48159155
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48619263
answers question: http://stackoverflow.com/q/48033333
has body: You are (in this case) apparently running Python 2.7.x, however parse module is in urllib package in Python 3.x. In Python 2.x its name was (just) urlparse. Based on that, I'd guess different configuration (mismatch in versions used between Code and/or 3rd party packages and/or python interpreter is behind the problem you're seeing). EDIT: sorry, I should have also noticed you are looking for urlencode on the last bit. In python 2.7 that is a function in urllib module: from urllib import urlencode.
has comment: http://stackoverflow.com/comment/84318025
downvote count: 0
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84319284

http://stackoverflow.com/comment/83196603
comment on: http://stackoverflow.com/q/48108723
type: Comment
type: QuestionComment
has text: @Evert Thank you very much for your comments. My numpy version is 1.13.0 and sklearn version is 0.18.1. Also, I have updated my tsne values in the question. Can you please let me know where I am making the code wrong?
score: 0

http://stackoverflow.com/q/48158871
upvote count: 2
type: UnansweredQuestion
score: 2
has body: I want to list tags for all ec2 resources(customer-gateway | dhcp-options | image | instance | internet-gateway | network-acl | network-interface | reserved-instances | route-table | security-group | snapshot | spot-instances-request | subnet | volume | vpc | vpn-connection and vpn-gateway). The following code lists all the resources for my ec2 client which have tags: session = boto3.Session(profile_name='default') ec2Client = session.client('ec2', region_name='eu-west-2') allTags = ec2Client.describe_tags()['Tags'] for tag in allTags: print tag PROBLEM The problem here is that only resources like in case of 'instances', the instances which do not have tags are not included. If there are 5 instances in ec2, 3 with tags and 2 without tags, the above code will list only those 3 instances with tags. DESIRED OUTPUT I want all the resources (instances, VPCs, subnet, security groups etc.), to be listed whether the tags are defined or not. If there are tags it shows tags, if not I still want it to be included in the result without tags. One way is to use describe_xxx method for each resource to get the reservations and look for tags, but I would have to call it for every resource (like describe_instances(), describe_snapshots, describe_security_groups() etc.), which, in my opinion is not so cleaned and generic way solution. QUESTION Is there any way using boto3 library to list all the resources, if the resources have tags show the tags too if not then show the resources only?
has answer: http://stackoverflow.com/a/48168585
type: Question
has title: In AWS, boto3 how can I list all reservations regardless of the tags and other values
has comment: http://stackoverflow.com/comment/83297370
answer count: 1
downvote count: 0
tagged with: boto3
tagged with: amazon-web-services
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/83297561
type: Comment
has text: I guess [calling connect() on a UDP socket](https://erlerobotics.gitbooks.io/erle-robotics-python-gitbook-free/udp_and_tcp/connecting_udp_sockets.html) does do something useful, but it does not establish a connection, so `connect()` will not timeout while trying to establish a connection.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48156294

http://stackoverflow.com/q/48149442
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48149887
has comment: http://stackoverflow.com/comment/83278698
type: Question
tagged with: algorithm
has comment: http://stackoverflow.com/comment/83277323
has body: I use random.shuffle when I want to shuffle a sequence. I have read the source code of random.shuffle, it is a typical implementation of Fisher–Yates_shuffle. However, I once saw an incorrect implementation of a shuffling algorithm. The code was the following: def myshuffle(lst): length = len(lst) for idx in xrange(length): t_idx = random.randint(0, length-1) lst[idx], lst[t_idx] = lst[t_idx], lst[idx] I know there is something wrong and I have tested it. But it is not clear to me why this is incorrect. Let's say p[i][j] means the probability of element move from pos i to pos j, can anybody make it clear? Here is my test code. if __name__ == '__main__': random.seed() pre_lst = ['a', 'b', 'c', 'd', 'e'] count = dict((e, {}) for e in pre_lst) TRY = 1000000 for i in xrange(TRY): lst = pre_lst[:] myshuffle(lst) for alpha in pre_lst: idx = lst.index(alpha) count[alpha][idx] = count[alpha].get(idx, 0) + 1 for alpha, alpha_count in sorted(count.iteritems(), key=lambda e: e[0]): result_lst = [] for k, v in sorted(alpha_count.iteritems(), key=lambda e: e[0]): result_lst.append(round(v * 1.0 / TRY, 3)) print alpha, result_lst And the result: &gt; a [0.2, 0.2, 0.2, 0.2, 0.2] &gt; b [0.242, 0.18, 0.185, 0.192, 0.2] &gt; c [0.21, 0.23, 0.173, 0.186, 0.2] &gt; d [0.184, 0.205, 0.231, 0.18, 0.2] &gt; e [0.164, 0.184, 0.21, 0.242, 0.2]
has comment: http://stackoverflow.com/comment/83278178
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/83278233
has title: Why is my shuffle implementation incorrect?
score: 2
tagged with: shuffle
upvote count: 2

http://stackoverflow.com/q/48064772
possible better answer: http://stackoverflow.com/a/48064909
score: -1
has title: "Largest product in a series" Python code
has answer: http://stackoverflow.com/a/48065577
accepted answer: http://stackoverflow.com/a/48064829
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/48064909
tagged with: python
has answer: http://stackoverflow.com/a/48064829
type: AnsweredQuestion
downvote count: 2
has body: After converting a string into an array, I really don't know why this isn't working... Can you explain what's my error, please? Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? seq = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450' new = [] for n in seq: new.append(int(n)) max_prod = 0 for i in range(0, len(new)-13): product = 1 for j in range(i, i+13): product *= j if product &gt; max_prod: max_prod = product print(max_prod)
upvote count: 1
type: Question
tagged with: euler-angles

http://stackoverflow.com/a/48058306
score: 1
has body: First let me say this: you can use map this way, but I don't think it's a good idea. It's meant to transform iterables, not to have side effects. When used for the side effects, as you do, the original imperative code is IMO much clearer. Now, if you insist to use map, read on. There are potentially two issues here. First, as explained in other answers, you can't pass the destination directory the way you do. tripleee shows some solutions/workarounds; here's another one: from functools import partial map(partial(shutil.move, dst='DirHTML'), books) Second, if you're using Python 3: map is lazy. It only evaluates its result when you iterate over it. For example, you could pass the result to list(): list(map(partial(shutil.move, dst='DirHTML'), books)) Tip: write a little wrapper around shutil.move that prints its arguments, to better see exactly what's going on.
upvote count: 1
answers question: http://stackoverflow.com/q/48057446
downvote count: 0
type: Answer

http://stackoverflow.com/comment/83241713
comment on: http://stackoverflow.com/q/48132215
has text: so if i download Anaconda from say https://pypi.python.org/simple/ and unpack the tar ball and cd into it can i then use it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83079722
has text: Yes - although the real point to larger `n` is to make `n` (which is part of the public key! it's not a secret) harder to factor. Any `n` can be used to send a message of any size - just view a large message as, e.g., being an integer in base `n`, and encrypt one "digit" at a time.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48052799

http://stackoverflow.com/comment/83133890
comment on: http://stackoverflow.com/q/48079903
type: Comment
type: QuestionComment
has text: I second @hop . You might also want to take a look at docker containers.
score: 0

http://stackoverflow.com/q/48039409
has comment: http://stackoverflow.com/comment/83049387
tagged with: pandas
answer count: 1
favorite count: 0
has title: pandas getattr(df, "mean") doesn't work like df.mean()
tagged with: python
linked to: http://stackoverflow.com/q/4075190
has comment: http://stackoverflow.com/comment/83049286
type: AnsweredQuestion
tagged with: dynamic
upvote count: 2
has comment: http://stackoverflow.com/comment/83049274
score: 1
has answer: http://stackoverflow.com/a/48039460
duplicate of: http://stackoverflow.com/q/4075190
downvote count: 1
type: Question
has body: When I use getattr() to dynamically access the mean of a pandas dataframe or series, it returns a Series.mean object. However, when I use df.mean() to access the mean, it returns a float. Why doesn't getattr() return the same thing that the normal method does? Minimal reproducible code: import pandas as pd import numpy as np s = pd.Series(np.random.randn(5)) print(getattr(s, "mean")) &gt;&gt;&gt; &lt;bound method Series.mean of &gt;&gt;&gt; 0 1.158042 &gt;&gt;&gt; 1 -0.586821 &gt;&gt;&gt; 2 -1.976764 &gt;&gt;&gt; 3 1.722072 &gt;&gt;&gt; 4 1.129570 print(s.mean()) &gt;&gt;&gt; dtype: float64&gt; &gt;&gt;&gt; 0.28921963496328584 I have used dir(getattr(s, "mean")) to attempt to get the mean value, but can't figure out which attribute, if any, will get me the float mean value.
accepted answer: http://stackoverflow.com/a/48039460
has comment: http://stackoverflow.com/comment/83049264
tagged with: numpy

http://stackoverflow.com/comment/83305620
has text: how can i change it so it will run in Python 2.7?
comment on: http://stackoverflow.com/q/48162162
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48082785
upvote count: 0
has title: get position of certain digit in float (python)
has comment: http://stackoverflow.com/comment/83140131
linked to: http://stackoverflow.com/q/48054972
favorite count: 0
has comment: http://stackoverflow.com/comment/83139988
has body: say i have a float 0.001000 then i want as output 4 more examples: 0.1 -&gt; 2 1 -&gt; 1 0.00001000 -&gt; 6 all the inputs will look like this (with 1's and 0's ) How could you do this in python3.6? Or maybe there is a way to truncate a float to the same digit directly? e.g 0.00100 2.44521 ------- 2.445
has comment: http://stackoverflow.com/comment/83143291
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48083573
tagged with: python
has comment: http://stackoverflow.com/comment/83182106
has answer: http://stackoverflow.com/a/48084041
tagged with: floating-point
downvote count: 1
has answer: http://stackoverflow.com/a/48082999
type: Question
score: -1
has comment: http://stackoverflow.com/comment/83140044
has comment: http://stackoverflow.com/comment/83140076
has comment: http://stackoverflow.com/comment/83140245
has comment: http://stackoverflow.com/comment/83141512
has comment: http://stackoverflow.com/comment/83140889
answer count: 3

http://stackoverflow.com/q/48149243
has comment: http://stackoverflow.com/comment/83277106
has answer: http://stackoverflow.com/a/48149760
score: 0
has comment: http://stackoverflow.com/comment/83276802
has comment: http://stackoverflow.com/comment/83276994
tagged with: python
linked to: http://stackoverflow.com/q/4173787
has body: I have a file with below content 1191,agg.list,ShareCapitalHistory[CapitalAmount],CompanyElementDefinition 838983,atom.list,ShareCapitalHistory[CapitalAmount][*],CompanyElementDefinition 789,agg.list,CapitalAmount,CompanyElementDefinition 08f610,atom.list,CapitalAmount[*],CompanyElementDefinition I am writing a program to filter all the lines that matches my key ignoring the brackets and stars. The key will the third column of the file which has agg.list. For example CapitalAmount is a agg.list value and this will be the key for the search. And when I search with he above as key I should get CapitalAmount[*]. To achieve this I have the below program import sys with open(sys.argv[1]) as myfile: for row in myfile: if (sys.argv[2] in row.replace('[', '').replace(']', '') and "[*]" in row): if row.split(',')[1] != 'agg.list': print row.split(',')[2] I pass the second argument as CapitalAmount but what I get is shown below CapitalAmount[*] ShareCapitalHistory[CapitalAmount][*] My program is checking if the key is available and prints all the lines that has the key in it. But what I want is to print only CapitalAmount[*] I heard about regsps and also found a relevant post here. But I am not sure how to use it in my program. Any help is much appreciated.
type: UnansweredQuestion
type: Question
has title: How to match the exact pattern in a file
has comment: http://stackoverflow.com/comment/83276773
answer count: 1

http://stackoverflow.com/comment/83236352
has text: I try not to emphasize `super` as an all-purpose replacement for a single parent class. Using `super` has a specific semantic meaning, which is not better or worse than hardcoding the parent class, just different.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48129663
type: Comment

http://stackoverflow.com/q/48055318
linked to: http://stackoverflow.com/q/9813243
upvote count: 3
tagged with: unzip
tagged with: python-zipfile
favorite count: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/9813243
has title: How Python zipFile module unzipfile keep file last modified time?
has body: z1 = zipfile.ZipFile('path\Test.zip') z1.extractall('path\Test') z1.close() When I use zipfile of Python to unzip a zip file, the date modified of all files will become the unzip time now. How to keep the date modified not change when unzip? Other language like C# has API to keep not change the date modified
answer count: 0
downvote count: 0
type: UnansweredQuestion
type: Question
score: 3
tagged with: gzip

http://stackoverflow.com/a/48125542
answers question: http://stackoverflow.com/q/48125278
score: 10
has comment: http://stackoverflow.com/comment/83227777
accepted answer of: http://stackoverflow.com/q/48125278
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83227814
type: Answer
upvote count: 10
has body: As the per docs of Vue v1.0 say: // ES6 template string style Vue.config.delimiters = ['${', '}'] So, in your example change to: $(function() { Vue.config.delimiters = ['[[', ']]']; var app = new Vue({ el: '#myApp', data: { message: 'Hello, world!' } }); }); It is strongly recomended, though, to use the new version of Vue (version 2) in order to be up-to-date!

http://stackoverflow.com/comment/83255686
has text: wwii - Which data should I print? there are no variables except the list itself..
comment on: http://stackoverflow.com/q/48138578
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48058665
score: 3
has body: You are looking for the pivot functionality: from pyspark.sql.functions import max df1 = df.groupBy("id") \ .pivot("code") \ .agg(max("veh_cd"), max("veh_p_cd")) \ .orderBy("id") To rename your columns we can use vanilla Python regex: import re newnames = [re.sub("max|\(|\)", '', i) for i in df1.columns] df1.toDF(*newnames).show() +----+----------+------------+-----------+-------------+ | id|BI__veh_cd|BI__veh_p_cd|col__veh_cd|col__veh_p_cd| +----+----------+------------+-----------+-------------+ |1001| 45| 55| 18| 21| |1002| null| null| 21| 25| +----+----------+------------+-----------+-------------+
type: Answer
answers question: http://stackoverflow.com/q/48058008
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48058008
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48038986
type: Question
has body: For context: The following version of my code works fine to download+write an entire image file to disk without reading any data from it before writing. response = requests.get(url, stream=True) if response.status_code == 200: with open(filename, 'wb') as outfile: for chunk in response.iter_content(chunk_size=256): outfile.write(chunk) outfile.close() My miserable attempts at reading the first chunk (containing the header of the file itself--not the http response, don't need that) with the following are failing. with open(filename, 'wb') as outfile: chunk1 = response.iter_content(chunk_size=256) # This gives: '&lt;generator object Response.iter_content.&lt;locals&gt;.generate at 0x033E57E0&gt;' print(chunk1) # This fails with error: 'TypeError: a bytes-like object is required, not 'generator' outfile.write(chunk1) # Doesn't get to here anymore for chunk in response.iter_content(chunk_size=256): outfile.write(chunk) outfile.close() I'm confused at this point. I don't understand why chunk1 refuses to be written, while all chunks in the for loop in my first version of the code were written just fine. Is it the print(chunk1) statement changing chunk1 somehow? Is my use of the iterator incorrect? I also don't know how to see what properties chunk1 might have that would contain the data... I also tried print(response.content) print(response.raw.data) # No good: these both download the entire image file, THEN print it to console. # But they at least print the data itself instead of giving an object The point of accessing the header before downloading everything is to stop the download entirely if the header reveals the image is undesirable for any reason. So I figure I have to read the chunks retrieved with iter_contents somehow. But how do I do that?
tagged with: response
downvote count: 0
answer count: 1
favorite count: 0
tagged with: download
has answer: http://stackoverflow.com/a/48039068
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has title: Reading data from a file during download with Requests.response
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/48039068

http://stackoverflow.com/q/48089244
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
tagged with: mysql
type: Question
downvote count: 0
upvote count: 1
has body: Platform Win10 Python3.6 My code to use mysql: import subprocess cmd = "mysql -uroot -proot -Dtest &lt;C:\\Users\\Administrator\\Desktop\\test.sql" status, output = subprocess.getstatusoutput(cmd) print(output) my test.sql is SELECT count(*) FROM wp_posts; SELECT "中" FROM wp_posts limit 1; SELECT count(*) FROM wp_posts123; The result from the Python code is: The result from cmd is: Question: Why is the error message in a different position?
has title: Error message location in Python vs cmd
favorite count: 0

http://stackoverflow.com/comment/83313027
has text: `ReadTimeoutError: HTTPSConnectionPool(host='pypi.python.org', port=443): Read timed out.`. Are you able to access the site?
comment on: http://stackoverflow.com/q/48166923
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48756030
score: 5
upvote count: 5
has body: Since you're using very similar dependencies, I suggest to take a look at the following Python package as it addresses your exact problem setting: pip install video2tfrecord or refer to https://github.com/ferreirafabio/video2tfrecord. It should also be adaptable enough to use tf.data.Dataset. disclaimer: I am one of the authors of the package.
downvote count: 0
answers question: http://stackoverflow.com/q/48101576
type: Answer

tabs
type: Tag
tags question: http://stackoverflow.com/q/48131242
tag name: tabs

http://stackoverflow.com/a/48040799
score: 4
has body: There are usefull built-in fuctions all (and any) for checking multiple conditions: def checker(a_list): return all(str(item).isdigit() for item in a_list)
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/83052611
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/83058309
has comment: http://stackoverflow.com/comment/83060672
accepted answer of: http://stackoverflow.com/q/48040762
has comment: http://stackoverflow.com/comment/83058805
has comment: http://stackoverflow.com/comment/83052232
has comment: http://stackoverflow.com/comment/83075876
answers question: http://stackoverflow.com/q/48040762

http://stackoverflow.com/comment/83032511
comment on: http://stackoverflow.com/q/48031020
score: 0
has text: This USACO problem is getting harder every time I think about it. With thousands of characters in the answer, a brute force solution(what I have right now) probably won't work.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83137708
type: AnswerComment
comment on: http://stackoverflow.com/a/48081452
type: Comment
score: 1
has text: You were right. What I am actually doing is to read that string from a query. Looks like the bottleneck is on receiving the whole data from the client. Didn't think that it is going to take so long to get such data.. Thanks!!

http://stackoverflow.com/a/48028687
type: Answer
score: 1
upvote count: 1
has body: It's important to understand that processes run in isolated areas of memory. Each process will have their own instance of hotels_url_list and there's no (easy) way of "sticking" those values into the parent process' list: if in the parent process you create an instance of list, that instance is not the same that the subprocesses use: When you do a .fork() (a.k.a. create a subprocess), the memory of the parent process is cloned on the child process. So, if the parent had an instance of list in the hotels_url_list variable, you'll also have an instance of list (also called hotels_url_list) in the child process BUT they will not be the same (they'll occupy different areas in memory). This doesn't happen with Threads. They do share memory. I would say (it's not like I'm much of an expert here) that the canonical way of communicating processes in this case would be a Queue: The child process puts things in the queue, the parent process grabs them: from multiprocessing import Process, Queue def get_spain_accomodations(): q = Queue() processes = [] links = ['http://foo.com', 'http://bar.com', 'http://baz.com'] hotels_url_list = [] for link in links: p = Process(target=get_page_links, args=(link, q,)) p.start() processes.append(p) for p in processes: p.join() hotels_url_list.append(q.get()) print("Collected: %s" % hotels_url_list) def get_page_links(link, q): print("link==%s" % link) hotel_url = "https://www.booking.com" + link q.put(hotel_url) if __name__ == "__main__": get_spain_accomodations() This outputs each link prepended with https://www.booking.com, the pre-pending happening on independent processes: link==http://foo.com link==http://bar.com link==http://baz.com Collected: ['https://www.booking.comhttp://foo.com', 'https://www.booking.comhttp://bar.com', 'https://www.booking.comhttp://baz.com'] I don't know if it will help you, but to me, it helps seeing the Queue as a "shared file" that both processes know about. Imagine you have two complete different programs, a…
answers question: http://stackoverflow.com/q/48028407
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48028407

http://stackoverflow.com/q/48043337
downvote count: 1
type: Question
has title: regex lookahead assertion
linked to: http://stackoverflow.com/q/8575281
score: 0
has body: I'm new to python regex and am learning the lookahead assertion. I found the following strange. Could someone tell me how it works? import regex as re re.search('(\d*)(?&lt;=a)(\.)','1a.') &lt;regex.Match object; span=(2, 3), match='.'&gt; re.search('(\d+)(?&lt;=a)(\.)','1a.') out put nothing Why doesn't the second one match anything?
answer count: 1
has answer: http://stackoverflow.com/a/48043412
accepted answer: http://stackoverflow.com/a/48043412
favorite count: 0
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/83057670
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/8575281
upvote count: 1

http://stackoverflow.com/comment/83109263
comment on: http://stackoverflow.com/q/48057309
type: Comment
has text: As one can still not simply copy-and-paste your data. People here are not paid so it is up to the person who asks the question to make it as easy as possible to answer it. Did you try my line from above? Could you not just copy three of the dataframes above and post them here so that one can just copy them?
score: 0
type: QuestionComment

http://stackoverflow.com/a/48222300
accepted answer of: http://stackoverflow.com/q/48139574
has body: I am trying to answer my own question. As my business-email (receiver email) and the customer-email (sender email) were both from India and according to India banking regulations, one would not be able to send payments from one Indian account to another. So, to solve the issue from Indian customers I am accepting payment through paytm and for international customers through paypal. If you don't have access to international paypal account and want to test your website, then you can create a test account and test in sandbox mode. If it works, then most likely it will work on production also.
answers question: http://stackoverflow.com/q/48139574
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/comment/83115377
score: 0
comment on: http://stackoverflow.com/q/48070823
type: Comment
type: QuestionComment
has text: You will get more and better answers if you create a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example. Especially make sure that the input and expected data are complete (not pseudo-data), and can be easily cut and and paste into an editor to allow testing proposed solutions.

http://stackoverflow.com/comment/83231661
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48118152
has text: Silly question: is the script and python installed on Informatica server that executes the workflow? Those paths are local from server perspective.
score: 0

http://stackoverflow.com/comment/83230811
has text: The installers for this package seem to be broken - the 0.1.2 & 0.1.3 installers don't install the `utils.py` submodule; 0.1.1 does install it, but doesn't install `resources/avrodict.json`. You might be able to get it working by cloning directly from github.
score: 0
comment on: http://stackoverflow.com/q/48081663
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83546074
type: Comment
comment on: http://stackoverflow.com/a/48077973
score: 1
type: AnswerComment
has text: Thanks for the answer - but I do not understand the conclusion. What connection was not successfull? The connection of selenium to its driver? Also, following these suggestions, the error still persists, at a level of maybe 2%. Maybe put the webdriver code in a while-try-except loop?

http://stackoverflow.com/comment/83252416
has text: @schwobaseggl: compare it to calculating that a coordinate is within a circle with radius `d`, we can do this with `sqrt(x*x+y*y) <= d`. We can calculate that with `sqrt`, but `sqrt` is a slow operation, so frequently it is done with `x*x+y*y <= d*d`, so it is equivalent. We did not change the semantics of the distance function (it is still with the square root), but we found a way to move sqrt out of the equation.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48137397
type: AnswerComment

checkbox
tag name: checkbox
tags question: http://stackoverflow.com/q/48084772
tags question: http://stackoverflow.com/q/48074233
type: Tag
tags question: http://stackoverflow.com/q/48085771

http://stackoverflow.com/q/48016230
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48016402
has answer: http://stackoverflow.com/a/48017056
has answer: http://stackoverflow.com/a/48016887
accepted answer: http://stackoverflow.com/a/48016402
has body: I am new to Python so I am unsure about the difference in variable assignment before or after the function definition. Specifically, the first example was adopted from Lutz's book. def tester(start): print("inside tester") def nested(label): print("inside nested") print(label,nested.state) nested.state += 1 print("done with nested") nested.state = start print("done with tester") return nested F = tester(0) F('spam') F.state F.state The objective of the code is to store the state information without using nonlocal. I am unsure what nested.state means here. I am unsure because nested.state is used inside nested() function (i.e. nested.state +=1) and outside nested() function (i.e. nested.state = start). I modified the code above to see whether Python accepts assigning variable after function declaration for nested() and to see whether there is any concept I am missing relating to function.variable call (i.e. nested.state call). def tester(start): def nested(label): print(label, state) state += 1 #replaced 'nested.state' with 'state' here state = start #replaced 'nested.state' with 'state' here return nested F=tester(0) F('spam') F('ham') Unfortunately, above code generates error local variable 'state' referenced before assignment. This tells me that I am missing some concept about function.variable (i.e. nested.state). Can someone please help me understand three things: I. why it is that the code with nested.state doesn't generate any error but state does? II. what does nested.state mean? If nested.state is a mechanism to access function's variables, why is it that the call inside nested() function also uses nested.state and not state? III. If nested.state is a mechanism to access variable inside function, then why is it that PyCharm fails to show state under dropdown when I type nested.? I'd appreciate any help. I research SO, and couldn't find any explanation on such problems.
tagged with: scope
answer count: 3
possible better answer: http://stackoverflow.com/a/48016887
downvote count: 0
tagged with: nested
has title: assignment of variable after function definition in Python
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: pycharm

http://stackoverflow.com/q/48038473
tagged with: python
has answer: http://stackoverflow.com/a/48070581
has comment: http://stackoverflow.com/comment/83048624
type: Question
has answer: http://stackoverflow.com/a/48038881
has comment: http://stackoverflow.com/comment/83047534
has comment: http://stackoverflow.com/comment/83047595
has comment: http://stackoverflow.com/comment/83048658
downvote count: 11
upvote count: 3
has answer: http://stackoverflow.com/a/77101325
answer count: 3
favorite count: 0
has body: I'm using Tkinter to create a software that works like a sketchpad. One of the capabilities is for the user to be able to change the pen colour. I have no idea how to do so. How can the user change the pen colour?
tagged with: tkinter
has comment: http://stackoverflow.com/comment/83055704
type: UnansweredQuestion
has title: How to change the pen color in tkinter?
score: -8

http://stackoverflow.com/q/48042460
has comment: http://stackoverflow.com/comment/83055651
accepted answer: http://stackoverflow.com/a/48042510
has comment: http://stackoverflow.com/comment/128427373
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83055640
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
has title: Log precision in python
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/48042510
has comment: http://stackoverflow.com/comment/83055590
has body: Following is sourcecode which checks that wether a number can be expressed in power but why does the code fail for n = 76 ** 89 - 1 and n = 76 ** 89. How can I solve this error? For both n it gives x=log(n,2)/log(i,2)=89.0 from math import log,sqrt,floor import sys n= 76 ** 89 - 1 t=floor(sqrt(n))+1 flag=False for i in range(2,t): x=log(n,2)/log(i,2) print(x) if x-int(x)&lt;sys.float_info.epsilon: print("YESSSSSSSSSSSSS!") flag=True break if not flag: print("Nooooooooooooooooooo!")
answer count: 1
has comment: http://stackoverflow.com/comment/83055575
has comment: http://stackoverflow.com/comment/83055630

http://stackoverflow.com/comment/83166831
type: QuestionComment
has text: Is the data always going to be in the second column with the first row being skipped?
score: 0
comment on: http://stackoverflow.com/q/48095872
type: Comment

http://stackoverflow.com/comment/83243134
has text: @leo_someone dont name your variables after modules. you have a string variable called random that shadows the module `random` so you cant acces its methods anymore. also do not name anything `list`, `dict` or any other module/inbuild name: https://docs.python.org/3/library/functions.html
comment on: http://stackoverflow.com/a/48132439
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/q/48122131
linked to: http://stackoverflow.com/q/36462257
answer count: 1
has answer: http://stackoverflow.com/a/48122648
has title: Importing from SQL into pandas dataframe directly as number instead of object using psycopg2
tagged with: pandas
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/83221892
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I can import into a dataframe like so: df=pd.DataFrame(cursor.fetchall(),columns=['name','ts','open','close'])) All df column dtypes will be of object. I can convert them into the proper numbers after by: df2=df.apply(pd.to_numeric, errors='ignore').info() Is there any way to do it on the fly where i specify the datatype without having to do multiple calculations/lines of code?
tagged with: psycopg2
score: 1
type: Question

http://stackoverflow.com/a/48198948
type: Answer
upvote count: 1
score: 1
has body: I was able to install it with pip (through the pip install face_recognition command) after I had Boost and CMake installed. to install face_recognition install Boost from here here and then install Cmake if both get successful then you can directly install it. and you also need to have visual studio C++ packages to ensure boost work properly
accepted answer of: http://stackoverflow.com/q/48156814
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48156814

http://stackoverflow.com/comment/83219581
comment on: http://stackoverflow.com/a/48120958
score: 0
type: Comment
has text: the WebDriverWait doesn't seem to work on linkedin... I've never had a problem using it on any other site, but LinkedIn has firewalls (I think) that make them faulty. The only way I've been able to force a wait is with time.sleep()
type: AnswerComment

http://stackoverflow.com/comment/83294226
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48154787
score: 1
has text: Can you still show the code where you try to access the file?

http://stackoverflow.com/a/48169914
score: 1
answers question: http://stackoverflow.com/q/48169791
has comment: http://stackoverflow.com/comment/83323525
downvote count: 0
has comment: http://stackoverflow.com/comment/83323928
has comment: http://stackoverflow.com/comment/83321482
has comment: http://stackoverflow.com/comment/83323185
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/83324117
has body: In your example feature_map doesn't have a value as it's an operation. Therefore you can't change it's value as such. What you can do, is pass another value in as part of the feed_dict parameter of session.run. So for example if your feature_map is followed by an operation like this: other_op = tf.gradient(feature_map, X) Then you can change the value passed in to that op (gradient in this case) via feed_dict like so: session.run(other_op, feed_dict={feature_map: &lt;new value&gt;})
has comment: http://stackoverflow.com/comment/83320217
has comment: http://stackoverflow.com/comment/83324703
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48169791

http://stackoverflow.com/comment/83233526
comment on: http://stackoverflow.com/a/48128411
type: Comment
has text: Thanks ! I knew that it was just a little mistake which cost me nearly 2 hours :D But what if I want to make the bars wider?
score: 0
type: AnswerComment

http://stackoverflow.com/a/48117691
has body: The rules of the grid layout manager are that it will compress the layout to the maximum size of any widget in a row or column. So the columns 1, 2 and 3 will have zero width, as these contain no widgets. If you move the widget in column 4 to one of these columns, that will not make a difference to the visible state of your layout. Column 4 will now have zero width and its space will be taken up by the column you moved the widget to. As to your statement ' Padding ends up padding the entire UI', I do not understand what you mean here, can't help you there.
answers question: http://stackoverflow.com/q/48117224
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/83212110
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/83212023

http://stackoverflow.com/q/48160623
upvote count: 1
has body: I have the json data want to convert to csv [ { "status": "changed", "dataset": { "id": "5a4b463c855d783af4f5f695", "name": "AE_E", "label": "1- ADVERSE EVENTS - Not Analyzed" }, "details": { "variables": [ { "variable": { "id": "5a4b4647855d783b494f9d3f", "name": "CPEVENT", "label": "CPEVENT" }, "status": "changed", "details": { "r_type": { "new_value": "unary", "old_value": "factor" } }, "message": "Variable with different R Type" }, { "variable": { "id": "5a4b4647855d783b494f9d25", "name": "CPEVENT2", "label": "CPEVENT2" }, "status": "changed", "details": { "r_type": { "new_value": "unary", "old_value": "binary" } }, "message": "Variable with different R Type" }, { "variable": { "id": "5a4b4647855d783b494f9d26", "name": "CP_UNSCHEDULED", "label": "CP_UNSCHEDULED" }, "status": "changed", "details": { "r_type": { "new_value": "undefined", "old_value": "unary" } }, "message": "Variable with different R Type" }, { "variable": { "id": "5a4b4647855d783b494f9d02", "name": "VISIT_NUMBER", "label": "VISIT_NUMBER" }, "status": "changed", "details": { "r_type": { "new_value": "unary", "old_value": "integer" } }, "message": "Variable with different R Type" }, { "variable": { "id": "5a4b4647855d783b494f9ccf", "name": "VISIT_NUMBER2", "label": "VISIT_NUMBER2" }, "status": "changed", "details": { "r_type": { "new_value": "unary", "old_value": "binary" } }, "message": "Variable with different R Type" } ], "many_visits": null } }, { "status": "changed", "dataset": { "id": "5a4b465b855d783af4f5f737", "name": "AE_EQG2", "label": "2 - ADVERSE EVENTS- Not Analyzed" }, "details": { "variables": [ { "variable": { "id": "5a4b4666855d783b4b5175ce", "name": "ADVE_MEDDRA_SOC", "label": "SYSTEM ORGAN CLASS" }, "status": "changed", "details": { "r_type": { "new_value": "character", "old_value": "factor" } }, "message": "Variable with different R Type" } ], "many_visits": null } }, { "status": "changed", "dataset": { "id": "5a4b467a855d783af4f5f7d7", "name": "AE_M", "label": "3- ADVERSE EVENT…
tagged with: http://stackoverflow.com/tag/json
type: Question
has comment: http://stackoverflow.com/comment/83300878
downvote count: 0
score: 1
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
favorite count: 0
has title: python json to csv , code can only parse part of json data
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/83048813
has text: Knock me over with a feather duster. Works like a charm: https://imgur.com/27GAoek (I added a scrolling text field, just for funsies).
type: Comment
comment on: http://stackoverflow.com/a/48039105
score: 1
type: AnswerComment

http://stackoverflow.com/comment/83128552
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48077401
has text: How does the csv file look like?
score: 0

http://stackoverflow.com/q/48122588
has answer: http://stackoverflow.com/a/48122663
answer count: 1
has title: Update values of a struct pointer in ctypes python without using a C function
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/83222107
accepted answer: http://stackoverflow.com/a/48122663
score: 1
tagged with: http://stackoverflow.com/tag/c
type: Question
tagged with: struct
tagged with: ctypes
has body: I'm having a C function that returns a pointer to an struct: struct iperf_test * iperf_new_test() { struct iperf_test *test; test = (struct iperf_test *) malloc(sizeof(struct iperf_test)); ... return test; } This function is called from Python in the following way: self.lib = cdll.LoadLibrary("lib.so") self._test = self.lib.iperf_new_test() The struct has some values such as: struct iperf_test { int server_port; int bind_port; }; The examples I see on the internet shows that I need to use a function that receives a pointer to alter the values, for example in python: self.lib.iperf_set_test_server_port(self._test, int(port)) And in C: void iperf_set_test_server_port(struct iperf_test *ipt, int srv_port) { ipt-&gt;server_port = srv_port; } Is there a way to change the value bind_port directly without using a C function?
downvote count: 0
tagged with: pointers

livereload
type: Tag
tag name: livereload
tags question: http://stackoverflow.com/q/48037526

http://stackoverflow.com/q/48129687
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48130110
has body: I made a chess board, but I need help with coloring the different squares. I only have white squares but I need black squares. Here is my code. import pygame def board(): width=480 # measurements for the window height=480 block_size=59 window = pygame.display.set_mode((width,height)) background_color = (0,0,0) # This is how I make the lines window.fill(background_color) for y in range(height): for x in range(width): rect = pygame.Rect(x*(block_size+1), y*(block_size+1), block_size, block_size) pygame.draw.rect(window, (255,255,255), rect) # Leaves space for lines to be visible. pygame.display.flip() board() # It's just the board. I already know I violated PEP 8.
accepted answer: http://stackoverflow.com/a/48130110
score: 0
answer count: 3
has title: How do I color in specific blocks for a chess board?
linked to: http://stackoverflow.com/q/66082526
has answer: http://stackoverflow.com/a/66918462
linked to: http://stackoverflow.com/q/45945254
favorite count: 0
possible better answer: http://stackoverflow.com/a/48133507
duplicate of: http://stackoverflow.com/q/66082526
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48133507
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/83289835
type: QuestionComment
has text: I don't really understand your question, but maybe [this example](https://gist.github.com/novel-yet-trivial/3e2863fef2b8cd2afa317ff0c7389d3d) of how to make a password box will help you.
comment on: http://stackoverflow.com/q/48155246
score: 1
type: Comment

http://stackoverflow.com/comment/83084117
has text: For my naked eye, from your sample data everything should be stable because BBB also appears in both dates. otherwise, `BBB,28/12/2017,No Analized` under what condition? Also, lets delete some comments above to keep it clean
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48055372
score: 0

http://stackoverflow.com/a/48174680
type: Answer
answers question: http://stackoverflow.com/q/48140571
has body: I was able to get the expected result like this: #!/usr/bin/env python3 import datetime import asyncio import random from time import sleep from multiprocessing import Process, Queue def can_get_speed(q): while True: print("IN get_speed") r = random.randint(1, 4) sleep(r) print("Return {0}".format(r)) q.put(r) def can_get_rpm(q): while True: print("IN get_rpm") r = random.randint(1, 4) sleep(r) print("Return {0}".format(r)) q.put(r) if __name__ == "__main__": q = Queue() q2 = Queue() p = Process(target=can_get_speed, args=(q,)) p2 = Process(target=can_get_rpm, args=(q2,)) p.start() p2.start() speed = None rpm = None while True: if not q.empty(): speed = q.get() if not q2.empty(): rpm = q2.get() print("Speed: {0} - RPM: {1} - {2}".format(speed, rpm, datetime.datetime.now())) Is there a smarter way ?
score: 0

http://stackoverflow.com/comment/83078269
comment on: http://stackoverflow.com/a/48052996
has text: good point. I edited to add a more detailed explanation on where it'd break
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/83189188
score: 0
type: Comment
has text: Don't write API method into `MyFlaskApp`, write them in proper routes with either `@app.route` or `Flask-Restful`'s `Resource` class (for better APIs...). Look at the example I gave below.
type: AnswerComment
comment on: http://stackoverflow.com/a/48094443

http://stackoverflow.com/comment/83218467
type: QuestionComment
score: 1
has text: @roganjosh yeah, it didn't help
comment on: http://stackoverflow.com/q/48120881
type: Comment

http://stackoverflow.com/comment/83243521
comment on: http://stackoverflow.com/a/48132182
has text: @COLDSPEED No problem, could you help me with one more thing I realized so I don't have to ask a separate question? I would like to add markers where the 30_sma crosses the Adj Close (e.g. green or red circles), is this possible?
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/a/48048911
type: Answer
score: 2
has body: A set is unordered and so will yield its elements in any order. However, this order is consistent within one python invocation. That is, set_ = set(range(N)); list(set_) == list(set_) is always true within in the same python program. Python 3.2+ explicitly makes sure that the ordering will inconsistent from one python instance to the next (this is a security consideration relating to denial of service attacks involving dictionary construction). This is the behaviour you are seeing. To avoid this you need to set the environment variable PYTHONHASHSEED to the same value before you start your program. This is in addition to setting the random seed before using random.choice. export PYTHONHASHSEED=1 python myscript.py A simpler solution, however, is to create a sorted list before doing random.choice. ie. random.choice(sorted({1, 2, 3}))
answers question: http://stackoverflow.com/q/48048789
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48048789
upvote count: 2

alexa-skills-kit
tag name: alexa-skills-kit
tags question: http://stackoverflow.com/q/48131710
type: Tag
tags question: http://stackoverflow.com/q/48078836
tags question: http://stackoverflow.com/q/48144214
tags question: http://stackoverflow.com/q/48104535

http://stackoverflow.com/comment/83022372
has text: You can't compare the returncode to `1` to check for failure - anything other than 0 is a failure. Also, the returncode attribute of the CalledProcessError will never be 0, as it's not thrown on success. If all you want to do is check for success/failure, there's no point checking returncode - just catch the exception and handle the failure case there.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48026197
type: Comment

http://stackoverflow.com/comment/111296727
has text: Perfect! I had a similar problem: `psutil` not updating from version `5.7.0` to `5.7.1` under `python3.5`. Likewise, as suggested by @Ojus, I just installed the `libpython3.5-dev` (even no need to fully install `python3.5-dev`) and the problem was solved.
type: Comment
comment on: http://stackoverflow.com/a/62895556
score: 3
type: AnswerComment

http://stackoverflow.com/comment/83152607
comment on: http://stackoverflow.com/a/48087050
type: AnswerComment
has text: Thanks you so much. I had already subclassed it, but for god know why, you actually need to set current cell to be selected before calling the edit. The function i used to do the selection, apparently didn't work for this purpose either...
score: 0
type: Comment

http://stackoverflow.com/comment/101226841
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48163430
has text: Possible duplicate of [Python MySQLdb issues (TypeError: %d format: a number is required, not str)](https://stackoverflow.com/questions/5785154/python-mysqldb-issues-typeerror-d-format-a-number-is-required-not-str)

http://stackoverflow.com/a/48376926
downvote count: 0
has comment: http://stackoverflow.com/comment/83770770
type: Answer
answers question: http://stackoverflow.com/q/48074049
has comment: http://stackoverflow.com/comment/83788409
has comment: http://stackoverflow.com/comment/83792330
has body: You can do this using the nose plug-in framework. Basically your plug-in needs to provide an addError method, which gets called when a test errors. The method gets the test case passed in, and you should be able to introspect what went wrong and log extra debugging information there. Have a look at the TestTextResult and ResultProxy classes. The examples contain a complete plug-in that modifies the output stream (HTMLPlugin) to be html formatted. update The documentation is indeed very bad. Here's what I've pieced together. import sys from nose.tools import assert_true import nose from nose.plugins import Plugin class Plugin1(Plugin): def __init__(self): self.reports = [] # self.name = 'mega-plugin' super(Plugin1, self).__init__() def addSuccess(self, test): print('Test successful') self.reports.append("Test successful") self.stream.writeln("Test successful") def setOutputStream(self, stream): self.stream = stream return None def finalize(self, result): for t in self.reports: self.stream.writeln('finalize - ' + t) class TestSuite(object): def test1(self): assert_true(True) if __name__ == '__main__': nose.main(argv=sys.argv + ['--with-plugin1'], addplugins=[Plugin1()]) the output from that is Test successful . ---------------------------------------------------------------------- Ran 1 test in 0.003s OK finalize - Test successful A couple of observations: using addplugins only registers the plugin it doesn't enable it you have to specify --with-PLUGIN-NAME to actually use it the --with-PLUGIN-NAME can not be first in argv as that would traditionally be the program name plug ins get an automatic name from the class name and an automatic --with-PLUGIN-NAME flag, you can override the name and thus also the --with-SOMETHING flag. if you want to print to stderr while the tests are running you have to also specify --nocapture otherwise nose will block stdout (notice that the print from addSuccess is not shown in the output) you should implement a setOutputStream method and…
has comment: http://stackoverflow.com/comment/83788606
has comment: http://stackoverflow.com/comment/83756099
has comment: http://stackoverflow.com/comment/119564870
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83789034

http://stackoverflow.com/q/48074845
favorite count: 0
tagged with: pandas
tagged with: python
has title: Add indicator to inform where the data came from Python
accepted answer: http://stackoverflow.com/a/48075070
upvote count: 2
downvote count: 1
type: AnsweredQuestion
score: 1
has body: Many thanks for reading. I have a pandas data frame which is the result of a concatenation of multiple smaller data frames. What I want to do is add multiple indicator columns to my final data frame, so that I can see what smaller data frame each row came from. This would be my desired result: Forename Surname Ind_1 Ind_2 Ind_3 Ind_4 jon smith 0 0 0 1 charlie jim 1 0 0 1 ian james 0 1 0 0 For example, "Jon Smith" came from data frame 4, and 'Charlie Jim" came from data frames 1 and 4 (duplicate rows). I have been able to achieve this for rows that only came from one data frame (e.g. rows 1 and 3) but not for duplicate rows that came from multiple data frames (e.g. row 2). Many thanks for any help.
type: Question
tagged with: concatenation
has answer: http://stackoverflow.com/a/48075070
answer count: 1
tagged with: indicator

http://stackoverflow.com/comment/83199876
score: 3
has text: Did you get an Error when you execute the two querys seperated?
comment on: http://stackoverflow.com/q/48112125
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48162322
tagged with: neural-network
has answer: http://stackoverflow.com/a/48171820
answer count: 1
downvote count: 0
tagged with: valueerror
has title: Tensorflow ValueError: GraphDef cannot be larger than 2GB
favorite count: 0
accepted answer: http://stackoverflow.com/a/48171820
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has body: Link to my notebook with code and error logs. The GraphDef size seems to be increasing with number of steps. If done properly I don't think this should be happening. However when I change only the "display_step" variable it allows me to run some more steps until the error occurs. Any ideas on how I could fix this?
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/83087812
has text: The reason you are getting a 'NoneType' object is that your soup.find() is not returning any matches, so table is set to None. Are you sure you typed the id correctly? Is the element generated dynamically, or does it exist on page load?
type: Comment
comment on: http://stackoverflow.com/q/48057732
score: 0
type: QuestionComment

http://stackoverflow.com/a/48101353
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0
has body: If you are looking for a colour changing rectangle (or any other shape), then pygame has some very useful draw commands Take this, pygame.draw.rect taken from the pygame docs pygame.draw.rect() draw a rectangle shape rect(Surface, color, Rect, width=0) -&gt; Rect Draws a rectangular shape on the Surface. The given Rect is the area of the rectangle. The width argument is the thickness to draw the outer edge. If width is zero then the rectangle will be filled. In this case, color will be a 3 element tuple for red, green, and blue colour values. These will all be between 0 and 255. For example, (255, 255, 255) would be pure white. If you keep track of a health and a max_health variable then you can find out how much of the rectangle should be red and how much should be green. For example green_value = 255 * (health / max_health) red_value = 255 * ((max_health - health) / max_health) Say your health was at 20 out of a maximum of 100, then your green value would be 20% of 255, and your red value would be 80% of 255, and your pygame.draw.rect function would take in a color parameter of (red_value, green_value, 0) As long as you remember to update the green_value and red_value variables you should be fine.
type: Answer
answers question: http://stackoverflow.com/q/48100964
accepted answer of: http://stackoverflow.com/q/48100964

http://stackoverflow.com/comment/83059232
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48043150
type: Comment
has text: `lst = [lst[x+1] - lst[x] for x in range(len(lst)-1)]`

http://stackoverflow.com/comment/83147796
has text: Nope, ODBC acts differently then sql server studio- there are a bunch of bugs such as necessity to quote reserved keywords that pyodbc has, which sql server is able to avoid
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48086032

http://stackoverflow.com/comment/85007059
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48112931
has text: Just a side note : do not make use of Optparse it is marked deprecated and is probably not included in py3.
score: 0

http://stackoverflow.com/a/48105969
downvote count: 0
has comment: http://stackoverflow.com/comment/83187719
type: AcceptedAnswer
type: Answer
score: 6
upvote count: 6
has body: I'd give the sprite a list of points (self.waypoints) and assign the first one to a self.target attribute. In the update method I subtract the self.pos from the self.target position to get a vector (heading) that points to the target and has a length equal to the distance. Scale this vector to the desired speed and use it as the velocity (which gets added to the self.pos vector each frame) and the entity will move towards the target. When the target is reached, I just increment the waypoint index and assign the next waypoint in the list to self.target. It's a good idea to slow down when you're getting near the target, otherwise the sprite could get stuck and moves back and forth if it can't reach the target point exactly. Therefore I also check if the sprite is closer than the self.target_radius and decrease the velocity to a fraction of the maximum speed. import pygame as pg from pygame.math import Vector2 class Entity(pg.sprite.Sprite): def __init__(self, pos, waypoints): super().__init__() self.image = pg.Surface((30, 50)) self.image.fill(pg.Color('dodgerblue1')) self.rect = self.image.get_rect(center=pos) self.vel = Vector2(0, 0) self.max_speed = 3 self.pos = Vector2(pos) self.waypoints = waypoints self.waypoint_index = 0 self.target = self.waypoints[self.waypoint_index] self.target_radius = 50 def update(self): # A vector pointing from self to the target. heading = self.target - self.pos distance = heading.length() # Distance to the target. heading.normalize_ip() if distance &lt;= 2: # We're closer than 2 pixels. # Increment the waypoint index to swtich the target. # The modulo sets the index back to 0 if it's equal to the length. self.waypoint_index = (self.waypoint_index + 1) % len(self.waypoints) self.target = self.waypoints[self.waypoint_index] if distance &lt;= self.target_radius: # If we're approaching the target, we slow down. self.vel = heading * (distance / self.target_radius * self.max_speed) else: # Otherwise move with max_speed. self.vel = heading *…
accepted answer of: http://stackoverflow.com/q/48102791
answers question: http://stackoverflow.com/q/48102791

http://stackoverflow.com/a/48046762
accepted answer of: http://stackoverflow.com/q/48046494
type: AcceptedAnswer
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48046494
has body: An uncaught exception is just every exception which has not been handled by an except-handler within a try-except statement and hence causes your script to stop. If this happens the interpreter by default prints the type of the exception, an error message and a traceback. So if you, for example try to print(1/0), you'll get an exception with type ZeroDivisionError, an error message "division by zero" and the last steps through your code which led to the exception (traceback). print(1/0) Traceback (most recent call last): File "E:\Programme\Anaconda3\envs\py36\lib\site- packages\IPython\core\interactiveshell.py", line 2910, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-12-2fc232d1511a&gt;", line 1, in &lt;module&gt; print(1/0) ZeroDivisionError: division by zero An uncaught exception lets you know that something went wrong. You then have to remove the error source (maybe you actually wanted to write print(1/10), or you have to catch and handle the exception, allowing your program to resume execution of code beneath the error source. try: 1/0 except ZeroDivisionError as err: # error is caught here pass # e.g just do nothing # print(type(err).__name__, flush=True) # or do something, like print # error type print("will be printed because exception before was caught")

http://stackoverflow.com/a/48018217
score: 1
has comment: http://stackoverflow.com/comment/133169047
upvote count: 1
has comment: http://stackoverflow.com/comment/133107473
has comment: http://stackoverflow.com/comment/83006627
answers question: http://stackoverflow.com/q/48017874
has comment: http://stackoverflow.com/comment/133174824
has body: you dont need all of this, use the simple syntax def home(request): context = { 'title':'Home Page', 'year':datetime.now().year, 'request': request, 'user': request.user, } return render( request, 'index.html',context) but request.user will return null until the user is not logged in add this to your MIDDLEWARE at the end 'social_django.middleware.SocialAuthExceptionMiddleware', add this to templates context processor at the end 'social_django.context_processors.backends', # &lt;-- 'social_django.context_processors.login_redirect', # &lt;--
downvote count: 0
has comment: http://stackoverflow.com/comment/83005419
type: Answer

http://stackoverflow.com/comment/83070512
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48049474
has text: But why have you defined it inside another function? If you want to call `func2` without calling `func1`, then it should be outside `func1`. Maybe your both functions are better fit for single class??
type: Comment

http://stackoverflow.com/q/48099075
has body: I have a sparse matrix X &lt;1000000x153047 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 5082518 stored elements in Compressed Sparse Column format&gt; and I have an array columns_to_use It consist of 10000 id of columns of matrix X. I want to use only these columns and drop another columns. I try to use such code: X_new = X[:, columns_to_use] And it works good with small X (10 000 rows), but with 100 000 rows or more I get memory error. How to get specific columns without memory error?
downvote count: 0
linked to: http://stackoverflow.com/q/39500649
tagged with: sparse-matrix
tagged with: matrix
has answer: http://stackoverflow.com/a/48102314
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83175427
type: UnansweredQuestion
has title: How to get columns from big sparse csc matrix
tagged with: python
score: 3
upvote count: 3
tagged with: scipy
type: Question

http://stackoverflow.com/a/48252703
has body: solution: update the library, using the following command py -m pip install --upgrade google-assistant-sdk[samples] Apparently there was a bug in the library. Updating the library solved the issue.
has comment: http://stackoverflow.com/comment/83506282
type: Answer
answers question: http://stackoverflow.com/q/48167501
score: 0

python-datetime
tag name: python-datetime
tags question: http://stackoverflow.com/q/48055428
tags question: http://stackoverflow.com/q/48054974
tags question: http://stackoverflow.com/q/48129251
type: Tag

http://stackoverflow.com/comment/83293500
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48154637
has text: The 1 means there was an error. The arguments you are passing to `call()` should also work without Python. Have you tried that? Pleae try what is mentioned here https://stackoverflow.com/questions/12130163/how-to-get-resulting-subprocess-command-string, get the resulting command line, print it and execute it on the console (cmd). Your command should be `subprocess.list2cmdline(['java', '-classpath', '"xalan.jar";"serializer.jar"', 'org.apache.xalan.xslt.Process', '-in', filepath, '-xsl', 'C:\Users\User\Desktop\XSL_Folder\debproj3.xsl', '-out', filepathplc, '/n']`).

http://stackoverflow.com/comment/83202003
has text: ContactForm has no attribute save.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48106367
type: AnswerComment

http://stackoverflow.com/comment/83094286
has text: if you use `Frame` to create class then you should rather use this frame (`self`) as parent for widgets (instead of `root`)
score: 1
comment on: http://stackoverflow.com/q/48057591
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/83033071
type: AnswerComment
has text: Thanks I will try that, but can you please write where "this question" link suppose to go?
type: Comment
comment on: http://stackoverflow.com/a/48031438
score: 0

http://stackoverflow.com/a/48171123
has comment: http://stackoverflow.com/comment/83347794
has comment: http://stackoverflow.com/comment/83345099
type: Answer
accepted answer of: http://stackoverflow.com/q/48168328
answers question: http://stackoverflow.com/q/48168328
has body: This will give you the names of all directories/folders along with their creation date from recent to old: import os, time DIR = "D:\Test1" t = {} for dirName in os.listdir(DIR): if os.path.isdir(os.path.join(DIR, dirName)): t[str( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getctime(os.path.join(DIR, dirName)))))] = dirName for key in sorted(t.keys(), reverse=True): print("%s : %s" % (key, t[key])) Here os.listdir(DIR) gives the name of all the files and directories present in DIR directory. os.path.isdir(SOME_VAR) checks whether SOME_VAR is a directory or not. os.path.join(DIR, dirName) used to get the absolute path of the directory whose name is stored in dirName like if dirName is 123 the absolute path is D:\Test1\1234 Output : 2017-12-29 12:41:16 : Python 2017-10-30 11:30:55 : gccPrgms 2017-09-27 15:25:39 : Projects 2017-09-06 11:26:23 : shellscript 2017-06-22 08:59:19 : shashank
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/83141245
has text: Do you care about the z-position of each image, or do you just want to have each image in a horizontal plane with the color representing the image data?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48082590

http://stackoverflow.com/a/48096692
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48095700
type: Answer
has body: First, the EOL stands for "End of Line" and you'll typically get this error if python doesn't like how you've defined a string or have used some wonky characters. To avoid this you can triple quote your string in your original code like so: stock_history = ''' Overview Specification Gallery Coming soon ''' This is ugly, so I did away with that big string because it isn't necessary. The only information you should want to obtain from your stock variable is whether or not the product is sold out or not. To do this, you can convert the bs4.element.Tag into a str type and use regular expressions to check for the presence of the "sold out!" substring. Regular expressions really do come in handy wherever you're doing Scraping, working with text data, or performing any form of XML or HTML parsing so I encourage you to read up on them. More info: https://www.regular-expressions.info/ You can easily test python regex captures here: https://pythex.org/ Here's the altered code, which does what you were trying to get it to do. import re import csv import requests from datetime import datetime from bs4 import BeautifulSoup def stock_check(url): """Function checks url for 'sold out!' substring in url.content""" soup = BeautifulSoup(url.content, "lxml") #Need to use lxml parser stock = soup.find("div", "buy-now-bar-con") #Check the html tags for sold out/coming soon info. stock_status = re.findall(r"(sold out!)", str(stock)) #Returns list of captured substring if exists. return stock_status[0] # returns "sold out!" from soup string. now = datetime.now() url = requests.get('https://shop.bitmain.com/antminer_s9_asic_bitcoin_miner.htm') if stock_check(url) == "sold out!": print(str(now) + ": Still not in stock...") else: print(str(now) + ": Now in stock!") Try it out and let me know if you have any questions! EDIT: OP asked how to periodically check webpage and include e-mail notification. A few things needed to be changed from the original solution such as setting userAgent informat…
answers question: http://stackoverflow.com/q/48095700
has comment: http://stackoverflow.com/comment/83552886
score: 4
has comment: http://stackoverflow.com/comment/83553158
upvote count: 4

http://stackoverflow.com/q/48081129
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/83136571
tagged with: multithreading
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83136669
has comment: http://stackoverflow.com/comment/83137252
has comment: http://stackoverflow.com/comment/83136749
tagged with: retry-logic
has title: Python thread retry every X seconds up to Y minutes
downvote count: 0
linked to: http://stackoverflow.com/q/15431044
has body: I'm trying to implement the client-server architecture in Python, where I have: Server application List of clients, who can subscribe to updates via API (sending POST requests to /subscribe endpoint). It works fine. On the server side, I have a list of subscriber's URLs. The main idea is to send requests from the server to all subscribed clients every X seconds (something similar to monitoring system). I'm trying to do this part using threads: class Monitor(threading.Thread): def __init__(self): super(Monitor, self).__init__() self.setDaemon(True) def send_notifications(self, subscribers): for subscriber in subscribers: request.post(subscriber["url"], json=subscriber["data"], timeout=0.5) def run(self): subscribers = get_subscribers() # getting list of subscribers via API call. while True: self.send_notifications(subscribers) time.sleep(Y) More or less it works, but I need to improve it a little. The expected behaviour is: The server should send notifications every X seconds to each subscribed client. If sending the notification to some client fails for Y minutes(5 minutes for example) it should unsubscribe this unresponsive client. Is there some best practices for this?
favorite count: 0

http://stackoverflow.com/a/48048180
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48047935
accepted answer of: http://stackoverflow.com/q/48047935
has body: It appears your dates start with the day being first. pandas might misinterpret your dates this way, so make sure you specify dayfirst=True when loading your csv - df1 = pd.read_csv( "../../Stock_data/{}.csv".format(symbol), sep='\t', lineterminator='\n', usecols=["date", "g1_c"], index_col="date", parse_dates=True, dayfirst=True ) The dayfirst parameter is forwarded to date parser library (which parses the dates for pandas), which handles the dates as appropriate.

http://stackoverflow.com/q/48104031
favorite count: 0
tagged with: python-3.x
has title: getting the paths of a tree in a a dictionary with a true,false values according to which path i took
has comment: http://stackoverflow.com/comment/83186395
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/83183737
tagged with: dictionary
tagged with: tree
has body: So i have a tree in python where i want to take each route until the leaf, and put each route alone in a dictionary where next to each node i put"true" if i went right, and "false" if i went left. cough true/ \ false fever healthy true/ \ false influenza cold like according to this tree, i want to get this for an example {cough:true,fever:true} and all the other paths. i tried using recursion where in each iteration i give it the right and left child, but when i do that i get all the nodes and paths in the same dictionary.
has comment: http://stackoverflow.com/comment/83213640
answer count: 0
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/83184030
has comment: http://stackoverflow.com/comment/83184536
score: 0
linked to: http://stackoverflow.com/q/48054654
has comment: http://stackoverflow.com/comment/83190454
tagged with: decision-tree

http://stackoverflow.com/a/48100492
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48100396
downvote count: 0
type: Answer
has body: This can be done using unstack + swaplevel + sort_index - df three four one two A 1 a 1 2 b 2 B 1 c 3 2 d 4 C 1 e 5 2 f 6 df = df.unstack(0) df.columns = df.columns.swaplevel() df.sort_index(axis=1) one A B C four three four three four three two 1 1 a 3 c 5 e 2 2 b 4 d 6 f
score: 1
accepted answer of: http://stackoverflow.com/q/48100396
upvote count: 1

http://stackoverflow.com/q/48141221
has body: I am trying to access an element in Selenium, but none of the typical methods are working. So far I have tried using every variation of 'find_elements_by_x' with no success. I also spent about a day looking at various forums, but nothing seems to be working. I recently used Selenium in another successful project, but the same structure is not working for this particular website. Here is a snippet of the HTML containing the elements I am trying to access: &lt;input type="text" name="username" id="username" placeholder="Username / Email" autocapitalize="off" autocorrect="off" required="" ng- model="credentials.username" class="ng-pristine ng-invalid ng-invalid- required"&gt; As is probably obvious, this is a username input for logging in. Below are a few lines I have tried so far that have not worked. from selenium import webdriver driver = webdriver.Chrome("chromedriver.exe filepath") driver.get('url') username = driver.find_element_by_xpath('//input[@id="username"]') That XPath navigates to the element in question if I search for it using the console in Chrome. I also tried: username = driver.find_element_by_name('username') which also did not work. I am pretty new to Selenium, and I have no experience at all with HTML, so I don't know if there can be complications in the HTML that that must be taken into account when looking for elements through Selenium. Any help at all is appreciated. This is also my first time posting here, so I hope I did not violate any rules.
tagged with: python
tagged with: xpath
type: AnsweredQuestion
tagged with: selenium
has answer: http://stackoverflow.com/a/48141644
has comment: http://stackoverflow.com/comment/83260326
has comment: http://stackoverflow.com/comment/83260321
type: Question
has comment: http://stackoverflow.com/comment/83266376
has answer: http://stackoverflow.com/a/48163927
possible better answer: http://stackoverflow.com/a/48141358
has answer: http://stackoverflow.com/a/48141358
has comment: http://stackoverflow.com/comment/83260392
score: 0
linked to: http://stackoverflow.com/q/7534622
answer count: 3
has comment: http://stackoverflow.com/comment/83266383
accepted answer: http://stackoverflow.com/a/48141644
has title: Python + Selenium -- Cannot access elements on a webpage
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/48171498
accepted answer: http://stackoverflow.com/a/48192897
answer count: 1
downvote count: 0
has body: In Pyomo I want to solve the following minimization problem, which matches the playback rate and timing of two audio files: import pyomo from pyomo.environ import * from pyomo.opt import SolverFactory import soundfile as sf import math import numpy #Create Model: model = ConcreteModel() #Declare Variables: model.P = Var(initialize = 1, within=PositiveReals, bounds = (0.5,2)) model.T = Var(initialize = 0, within=Reals, bounds = (-500,500)) #Objective function: def shift(data,rate,t,point): Y=numpy.zeros(len(data)) for i in range(len(data)): for j in range(point): if math.floor(i*rate+t-j+point/2)&gt;=0 and math.floor(i*rate+t-j+point/2)&lt;=len(data)-1: Y[i]+=data[math.floor(i*rate+t-j+point/2)]*numpy.sinc((math.floor(i*rate+t)-i*rate-t)-(j-point/2)) return Y def obj_fun(model): #Read data from audiofile: Audio1, samplerate = sf.read('C:/Audio1.wav') Audio2, samplerate = sf.read('C:/Audio2.wav') Audio1=Audio1[:,0] Audio2=Audio2[:,0] Audio2= numpy.pad(Audio2,(0,len(Audio1)-len(Audio2)),'constant', constant_values=(0, 0)) return -1*numpy.sum(shift(Audio2,model.P,model.T,4)*Audio1) #Create obj function: model.obj = Objective(rule=obj_fun, sense=1) The problem is the following error: TypeError: Implicit conversion of Pyomo NumericValue type `&lt;class 'pyomo.core.base.expr_coopr3._SumExpression'&gt;' to a float is disabled. This error is often the result of using Pyomo components as arguments to one of the Python built-in math module functions when defining expressions. Avoid this error by using Pyomo-provided math functions. The solver can't function unless numpy's/math's sinc and floor functions are changed. However, in Pyomo's documentation there is no reference to Pyomo-provided functions. What do I change the standard sinc/floor functions with in order to get the model object created without errors? Also I am wondering whether there is a smarter way to read the data into the model. As of now, it's unnecessarily read on every pass of the objective function.
favorite count: 0
has title: Finding Pyomo provided math functions
tagged with: optimization
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48192897
type: AnsweredQuestion
score: 1
type: Question
tagged with: pyomo

http://stackoverflow.com/q/48041269
has comment: http://stackoverflow.com/comment/83053660
has body: Consider two list comprehensions gamma and delta with nearly redundant code. The difference being the sliced lists alpha and beta, namely gamma = [alpha[i:i+30] for i in range(0,49980,30)] delta = [beta[i:i+30] for i in range(0,49980,30)] Is there a pythonic way to write this as a one liner (say gamma,delta = ... )? I have a few other pieces of code that are similar in nature, and I'd like to simplify the code's seeming redundancy.
possible better answer: http://stackoverflow.com/a/48041422
linked to: http://stackoverflow.com/q/434287
tagged with: list-comprehension
type: Question
has comment: http://stackoverflow.com/comment/83053698
has comment: http://stackoverflow.com/comment/83053322
has answer: http://stackoverflow.com/a/48041299
linked to: http://stackoverflow.com/q/312443
has title: One-liner for nearly redundant list comprehensions
score: 4
has comment: http://stackoverflow.com/comment/83054693
has answer: http://stackoverflow.com/a/48041307
has answer: http://stackoverflow.com/a/48042095
has comment: http://stackoverflow.com/comment/83053173
has answer: http://stackoverflow.com/a/48041422
tagged with: python
has comment: http://stackoverflow.com/comment/83054615
has comment: http://stackoverflow.com/comment/83054604
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/83053804
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/83053341
downvote count: 0
has comment: http://stackoverflow.com/comment/83053680
upvote count: 4
has comment: http://stackoverflow.com/comment/83053730
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48041299

http://stackoverflow.com/a/50851125
downvote count: 0
score: 1
has body: There could be several reasons for this error but all of them are related to project/settings.py file. Check if you have initialised SECRET_KEY in it. Check if you have application in INSTALLED_APPS and is not installed.
upvote count: 1
answers question: http://stackoverflow.com/q/48163641
type: Answer

http://stackoverflow.com/a/51663094
has comment: http://stackoverflow.com/comment/90672293
has body: I had a similar problem when invoking tests either with pytest or python setup.py test. For pytest invocation installing pytest-django in my virtual env solved the problem. For python setup.py install adding pytest-django to the tests_require argument of setup() solved it. Here's the snippet of setup.py: TEST_REQUIREMENTS = [ 'pytest', 'pytest-django', 'pylint', 'pylint_django', 'git-pylint-commit-hook', ] setup( name='foo', version='0.0.1', description='Foo package', author='...', author_email='...', packages=['foo'], install_requires=INSTALL_REQUIREMENTS, setup_requires=SETUP_REQUIREMENTS, tests_require=TEST_REQUIREMENTS, )
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/48106347
score: 9
downvote count: 1

http://stackoverflow.com/comment/83113812
has text: thanks but i want it to bounce when it collides on the bottom of a platform. anyway to do that. you are doing the bottom and top of the entire window not a single platform.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48069743